customMaterial.dd39ecee.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  101. "use strict";
  102. Object.defineProperty(exports, "__esModule", {
  103. value: true
  104. });
  105. exports.AmbientLight = AmbientLight;
  106. exports.AmbientLightProbe = AmbientLightProbe;
  107. exports.AnimationClip = AnimationClip;
  108. exports.AnimationLoader = AnimationLoader;
  109. exports.AnimationMixer = AnimationMixer;
  110. exports.AnimationObjectGroup = AnimationObjectGroup;
  111. exports.ArcCurve = ArcCurve;
  112. exports.ArrayCamera = ArrayCamera;
  113. exports.AudioLoader = AudioLoader;
  114. exports.AxisHelper = AxisHelper;
  115. exports.BinaryTextureLoader = BinaryTextureLoader;
  116. exports.Bone = Bone;
  117. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  118. exports.BoundingBoxHelper = BoundingBoxHelper;
  119. exports.BufferAttribute = BufferAttribute;
  120. exports.BufferGeometry = BufferGeometry;
  121. exports.BufferGeometryLoader = BufferGeometryLoader;
  122. exports.Camera = Camera;
  123. exports.CanvasRenderer = CanvasRenderer;
  124. exports.CanvasTexture = CanvasTexture;
  125. exports.CatmullRomCurve3 = CatmullRomCurve3;
  126. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  127. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  128. exports.CompressedTexture = CompressedTexture;
  129. exports.CompressedTextureLoader = CompressedTextureLoader;
  130. exports.CubeCamera = CubeCamera;
  131. exports.CubeTexture = CubeTexture;
  132. exports.CubeTextureLoader = CubeTextureLoader;
  133. exports.CubicBezierCurve = CubicBezierCurve;
  134. exports.CubicBezierCurve3 = CubicBezierCurve3;
  135. exports.CubicInterpolant = CubicInterpolant;
  136. exports.Curve = Curve;
  137. exports.CurvePath = CurvePath;
  138. exports.DataTexture = DataTexture;
  139. exports.DataTexture2DArray = DataTexture2DArray;
  140. exports.DataTexture3D = DataTexture3D;
  141. exports.DataTextureLoader = DataTextureLoader;
  142. exports.DepthTexture = DepthTexture;
  143. exports.DirectionalLight = DirectionalLight;
  144. exports.DiscreteInterpolant = DiscreteInterpolant;
  145. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  146. exports.EdgesHelper = EdgesHelper;
  147. exports.EllipseCurve = EllipseCurve;
  148. exports.EventDispatcher = EventDispatcher;
  149. exports.Face4 = Face4;
  150. exports.FileLoader = FileLoader;
  151. exports.Float16BufferAttribute = Float16BufferAttribute;
  152. exports.Float32Attribute = Float32Attribute;
  153. exports.Float32BufferAttribute = Float32BufferAttribute;
  154. exports.Float64Attribute = Float64Attribute;
  155. exports.Float64BufferAttribute = Float64BufferAttribute;
  156. exports.Font = Font;
  157. exports.FontLoader = FontLoader;
  158. exports.GLBufferAttribute = GLBufferAttribute;
  159. exports.Geometry = Geometry;
  160. exports.Group = Group;
  161. exports.HemisphereLight = HemisphereLight;
  162. exports.HemisphereLightProbe = HemisphereLightProbe;
  163. exports.ImageBitmapLoader = ImageBitmapLoader;
  164. exports.ImageLoader = ImageLoader;
  165. exports.ImmediateRenderObject = ImmediateRenderObject;
  166. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  167. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  168. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  169. exports.InstancedMesh = InstancedMesh;
  170. exports.Int16Attribute = Int16Attribute;
  171. exports.Int16BufferAttribute = Int16BufferAttribute;
  172. exports.Int32Attribute = Int32Attribute;
  173. exports.Int32BufferAttribute = Int32BufferAttribute;
  174. exports.Int8Attribute = Int8Attribute;
  175. exports.Int8BufferAttribute = Int8BufferAttribute;
  176. exports.InterleavedBuffer = InterleavedBuffer;
  177. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  178. exports.Interpolant = Interpolant;
  179. exports.JSONLoader = JSONLoader;
  180. exports.KeyframeTrack = KeyframeTrack;
  181. exports.LOD = LOD;
  182. exports.LensFlare = LensFlare;
  183. exports.Light = Light;
  184. exports.LightProbe = LightProbe;
  185. exports.Line = Line;
  186. exports.LineBasicMaterial = LineBasicMaterial;
  187. exports.LineCurve = LineCurve;
  188. exports.LineCurve3 = LineCurve3;
  189. exports.LineDashedMaterial = LineDashedMaterial;
  190. exports.LineLoop = LineLoop;
  191. exports.LineSegments = LineSegments;
  192. exports.LinearInterpolant = LinearInterpolant;
  193. exports.Loader = Loader;
  194. exports.LoadingManager = LoadingManager;
  195. exports.Material = Material;
  196. exports.MaterialLoader = MaterialLoader;
  197. exports.Mesh = Mesh;
  198. exports.MeshBasicMaterial = MeshBasicMaterial;
  199. exports.MeshDepthMaterial = MeshDepthMaterial;
  200. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  201. exports.MeshFaceMaterial = MeshFaceMaterial;
  202. exports.MeshLambertMaterial = MeshLambertMaterial;
  203. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  204. exports.MeshNormalMaterial = MeshNormalMaterial;
  205. exports.MeshPhongMaterial = MeshPhongMaterial;
  206. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  207. exports.MeshStandardMaterial = MeshStandardMaterial;
  208. exports.MeshToonMaterial = MeshToonMaterial;
  209. exports.MultiMaterial = MultiMaterial;
  210. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  211. exports.Object3D = Object3D;
  212. exports.OrthographicCamera = OrthographicCamera;
  213. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  214. exports.ParametricGeometry = ParametricGeometry;
  215. exports.Particle = Particle;
  216. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  217. exports.ParticleSystem = ParticleSystem;
  218. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  219. exports.Path = Path;
  220. exports.PerspectiveCamera = PerspectiveCamera;
  221. exports.PointCloud = PointCloud;
  222. exports.PointCloudMaterial = PointCloudMaterial;
  223. exports.PointLight = PointLight;
  224. exports.Points = Points;
  225. exports.PointsMaterial = PointsMaterial;
  226. exports.PropertyBinding = PropertyBinding;
  227. exports.PropertyMixer = PropertyMixer;
  228. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  229. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  230. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  231. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  232. exports.RawShaderMaterial = RawShaderMaterial;
  233. exports.Raycaster = Raycaster;
  234. exports.RectAreaLight = RectAreaLight;
  235. exports.ShaderMaterial = ShaderMaterial;
  236. exports.ShadowMaterial = ShadowMaterial;
  237. exports.Shape = Shape;
  238. exports.ShapePath = ShapePath;
  239. exports.Skeleton = Skeleton;
  240. exports.SkinnedMesh = SkinnedMesh;
  241. exports.Spline = Spline;
  242. exports.SplineCurve = SplineCurve;
  243. exports.SplineCurve3 = SplineCurve3;
  244. exports.SpotLight = SpotLight;
  245. exports.Sprite = Sprite;
  246. exports.SpriteMaterial = SpriteMaterial;
  247. exports.StereoCamera = StereoCamera;
  248. exports.StringKeyframeTrack = StringKeyframeTrack;
  249. exports.Texture = Texture;
  250. exports.TextureLoader = TextureLoader;
  251. exports.Uint16Attribute = Uint16Attribute;
  252. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  253. exports.Uint32Attribute = Uint32Attribute;
  254. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  255. exports.Uint8Attribute = Uint8Attribute;
  256. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  257. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  258. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  259. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  260. exports.Vertex = Vertex;
  261. exports.VideoTexture = VideoTexture;
  262. exports.WebGL1Renderer = WebGL1Renderer;
  263. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  264. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  265. exports.WebGLRenderTarget = WebGLRenderTarget;
  266. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  267. exports.WebGLRenderer = WebGLRenderer;
  268. exports.WebGLUtils = WebGLUtils;
  269. exports.WireframeHelper = WireframeHelper;
  270. exports.XHRLoader = XHRLoader;
  271. exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.IcosahedronGeometry = exports.IcosahedronBufferGeometry = exports.HemisphereLightHelper = exports.HalfFloatType = exports.GridHelper = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.GLSL3 = exports.GLSL1 = exports.Frustum = exports.FrontSide = exports.FogExp2 = exports.Fog = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.Face3 = exports.ExtrudeGeometry = exports.ExtrudeBufferGeometry = exports.Euler = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.EdgesGeometry = exports.DynamicReadUsage = exports.DynamicDrawUsage = exports.DynamicCopyUsage = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DodecahedronGeometry = exports.DodecahedronBufferGeometry = exports.DirectionalLightHelper = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.DataUtils = exports.Cylindrical = exports.CylinderGeometry = exports.CylinderBufferGeometry = exports.CustomToneMapping = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ConeGeometry = exports.ConeBufferGeometry = exports.Color = exports.Clock = exports.ClampToEdgeWrapping = exports.CircleGeometry = exports.CircleBufferGeometry = exports.CineonToneMapping = exports.CameraHelper = exports.Cache = exports.ByteType = exports.BoxHelper = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.Box3Helper = exports.Box3 = exports.Box2 = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AxesHelper = exports.AudioListener = exports.AudioContext = exports.AudioAnalyser = exports.Audio = exports.ArrowHelper = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AdditiveAnimationBlendMode = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  272. exports.RGBEEncoding = exports.RGBDEncoding = exports.RGBA_S3TC_DXT5_Format = exports.RGBA_S3TC_DXT3_Format = exports.RGBA_S3TC_DXT1_Format = exports.RGBA_PVRTC_4BPPV1_Format = exports.RGBA_PVRTC_2BPPV1_Format = exports.RGBA_ETC2_EAC_Format = exports.RGBA_BPTC_Format = exports.RGBA_ASTC_8x8_Format = exports.RGBA_ASTC_8x6_Format = exports.RGBA_ASTC_8x5_Format = exports.RGBA_ASTC_6x6_Format = exports.RGBA_ASTC_6x5_Format = exports.RGBA_ASTC_5x5_Format = exports.RGBA_ASTC_5x4_Format = exports.RGBA_ASTC_4x4_Format = exports.RGBA_ASTC_12x12_Format = exports.RGBA_ASTC_12x10_Format = exports.RGBA_ASTC_10x8_Format = exports.RGBA_ASTC_10x6_Format = exports.RGBA_ASTC_10x5_Format = exports.RGBA_ASTC_10x10_Format = exports.RGBAIntegerFormat = exports.RGBAFormat = exports.RGBADepthPacking = exports.REVISION = exports.Quaternion = exports.PositionalAudio = exports.PolyhedronGeometry = exports.PolyhedronBufferGeometry = exports.PolarGridHelper = exports.PointLightHelper = exports.PlaneHelper = exports.PlaneGeometry = exports.PlaneBufferGeometry = exports.Plane = exports.PMREMGenerator = exports.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.OctahedronGeometry = exports.OctahedronBufferGeometry = exports.ObjectSpaceNormalMap = exports.ObjectLoader = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = exports.NormalAnimationBlendMode = exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = exports.NeverDepth = exports.NearestMipmapNearestFilter = exports.NearestMipmapLinearFilter = exports.NearestMipMapNearestFilter = exports.NearestMipMapLinearFilter = exports.NearestFilter = exports.MultiplyOperation = exports.MultiplyBlending = exports.MixOperation = exports.MirroredRepeatWrapping = exports.MinEquation = exports.MaxEquation = exports.Matrix4 = exports.Matrix3 = exports.MathUtils = exports.Math = exports.MOUSE = exports.LuminanceFormat = exports.LuminanceAlphaFormat = exports.LoopRepeat = exports.LoopPingPong = exports.LoopOnce = exports.LogLuvEncoding = exports.LoaderUtils = exports.LinearToneMapping = exports.LinearMipmapNearestFilter = exports.LinearMipmapLinearFilter = exports.LinearMipMapNearestFilter = exports.LinearMipMapLinearFilter = exports.LinearFilter = exports.LinearEncoding = exports.LineStrip = exports.LinePieces = exports.Line3 = exports.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.Layers = exports.LatheGeometry = exports.LatheBufferGeometry = exports.KeepStencilOp = exports.InvertStencilOp = void 0;
  273. exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.WireframeGeometry = exports.VertexColors = exports.Vector4 = exports.Vector3 = exports.Vector2 = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = exports.UniformsLib = exports.Uniform = exports.UVMapping = exports.TubeGeometry = exports.TubeBufferGeometry = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.Triangle = exports.TorusKnotGeometry = exports.TorusKnotBufferGeometry = exports.TorusGeometry = exports.TorusBufferGeometry = exports.TextGeometry = exports.TextBufferGeometry = exports.TetrahedronGeometry = exports.TetrahedronBufferGeometry = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.StreamReadUsage = exports.StreamDrawUsage = exports.StreamCopyUsage = exports.StaticReadUsage = exports.StaticDrawUsage = exports.StaticCopyUsage = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SpotLightHelper = exports.SphericalHarmonics3 = exports.Spherical = exports.SphereGeometry = exports.SphereBufferGeometry = exports.Sphere = exports.SmoothShading = exports.SkeletonHelper = exports.ShortType = exports.ShapeUtils = exports.ShapeGeometry = exports.ShapeBufferGeometry = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.Scene = exports.SRGB8_ALPHA8_ASTC_8x8_Format = exports.SRGB8_ALPHA8_ASTC_8x6_Format = exports.SRGB8_ALPHA8_ASTC_8x5_Format = exports.SRGB8_ALPHA8_ASTC_6x6_Format = exports.SRGB8_ALPHA8_ASTC_6x5_Format = exports.SRGB8_ALPHA8_ASTC_5x5_Format = exports.SRGB8_ALPHA8_ASTC_5x4_Format = exports.SRGB8_ALPHA8_ASTC_4x4_Format = exports.SRGB8_ALPHA8_ASTC_12x12_Format = exports.SRGB8_ALPHA8_ASTC_12x10_Format = exports.SRGB8_ALPHA8_ASTC_10x8_Format = exports.SRGB8_ALPHA8_ASTC_10x6_Format = exports.SRGB8_ALPHA8_ASTC_10x5_Format = exports.SRGB8_ALPHA8_ASTC_10x10_Format = exports.RingGeometry = exports.RingBufferGeometry = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedIntegerFormat = exports.RedFormat = exports.Ray = exports.RGIntegerFormat = exports.RGFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC2_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBIntegerFormat = exports.RGBFormat = exports.RGBEFormat = void 0;
  274. exports.sRGBEncoding = void 0;
  275. // threejs.org/license
  276. const REVISION = '123';
  277. exports.REVISION = REVISION;
  278. const MOUSE = {
  279. LEFT: 0,
  280. MIDDLE: 1,
  281. RIGHT: 2,
  282. ROTATE: 0,
  283. DOLLY: 1,
  284. PAN: 2
  285. };
  286. exports.MOUSE = MOUSE;
  287. const TOUCH = {
  288. ROTATE: 0,
  289. PAN: 1,
  290. DOLLY_PAN: 2,
  291. DOLLY_ROTATE: 3
  292. };
  293. exports.TOUCH = TOUCH;
  294. const CullFaceNone = 0;
  295. exports.CullFaceNone = CullFaceNone;
  296. const CullFaceBack = 1;
  297. exports.CullFaceBack = CullFaceBack;
  298. const CullFaceFront = 2;
  299. exports.CullFaceFront = CullFaceFront;
  300. const CullFaceFrontBack = 3;
  301. exports.CullFaceFrontBack = CullFaceFrontBack;
  302. const BasicShadowMap = 0;
  303. exports.BasicShadowMap = BasicShadowMap;
  304. const PCFShadowMap = 1;
  305. exports.PCFShadowMap = PCFShadowMap;
  306. const PCFSoftShadowMap = 2;
  307. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  308. const VSMShadowMap = 3;
  309. exports.VSMShadowMap = VSMShadowMap;
  310. const FrontSide = 0;
  311. exports.FrontSide = FrontSide;
  312. const BackSide = 1;
  313. exports.BackSide = BackSide;
  314. const DoubleSide = 2;
  315. exports.DoubleSide = DoubleSide;
  316. const FlatShading = 1;
  317. exports.FlatShading = FlatShading;
  318. const SmoothShading = 2;
  319. exports.SmoothShading = SmoothShading;
  320. const NoBlending = 0;
  321. exports.NoBlending = NoBlending;
  322. const NormalBlending = 1;
  323. exports.NormalBlending = NormalBlending;
  324. const AdditiveBlending = 2;
  325. exports.AdditiveBlending = AdditiveBlending;
  326. const SubtractiveBlending = 3;
  327. exports.SubtractiveBlending = SubtractiveBlending;
  328. const MultiplyBlending = 4;
  329. exports.MultiplyBlending = MultiplyBlending;
  330. const CustomBlending = 5;
  331. exports.CustomBlending = CustomBlending;
  332. const AddEquation = 100;
  333. exports.AddEquation = AddEquation;
  334. const SubtractEquation = 101;
  335. exports.SubtractEquation = SubtractEquation;
  336. const ReverseSubtractEquation = 102;
  337. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  338. const MinEquation = 103;
  339. exports.MinEquation = MinEquation;
  340. const MaxEquation = 104;
  341. exports.MaxEquation = MaxEquation;
  342. const ZeroFactor = 200;
  343. exports.ZeroFactor = ZeroFactor;
  344. const OneFactor = 201;
  345. exports.OneFactor = OneFactor;
  346. const SrcColorFactor = 202;
  347. exports.SrcColorFactor = SrcColorFactor;
  348. const OneMinusSrcColorFactor = 203;
  349. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  350. const SrcAlphaFactor = 204;
  351. exports.SrcAlphaFactor = SrcAlphaFactor;
  352. const OneMinusSrcAlphaFactor = 205;
  353. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  354. const DstAlphaFactor = 206;
  355. exports.DstAlphaFactor = DstAlphaFactor;
  356. const OneMinusDstAlphaFactor = 207;
  357. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  358. const DstColorFactor = 208;
  359. exports.DstColorFactor = DstColorFactor;
  360. const OneMinusDstColorFactor = 209;
  361. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  362. const SrcAlphaSaturateFactor = 210;
  363. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  364. const NeverDepth = 0;
  365. exports.NeverDepth = NeverDepth;
  366. const AlwaysDepth = 1;
  367. exports.AlwaysDepth = AlwaysDepth;
  368. const LessDepth = 2;
  369. exports.LessDepth = LessDepth;
  370. const LessEqualDepth = 3;
  371. exports.LessEqualDepth = LessEqualDepth;
  372. const EqualDepth = 4;
  373. exports.EqualDepth = EqualDepth;
  374. const GreaterEqualDepth = 5;
  375. exports.GreaterEqualDepth = GreaterEqualDepth;
  376. const GreaterDepth = 6;
  377. exports.GreaterDepth = GreaterDepth;
  378. const NotEqualDepth = 7;
  379. exports.NotEqualDepth = NotEqualDepth;
  380. const MultiplyOperation = 0;
  381. exports.MultiplyOperation = MultiplyOperation;
  382. const MixOperation = 1;
  383. exports.MixOperation = MixOperation;
  384. const AddOperation = 2;
  385. exports.AddOperation = AddOperation;
  386. const NoToneMapping = 0;
  387. exports.NoToneMapping = NoToneMapping;
  388. const LinearToneMapping = 1;
  389. exports.LinearToneMapping = LinearToneMapping;
  390. const ReinhardToneMapping = 2;
  391. exports.ReinhardToneMapping = ReinhardToneMapping;
  392. const CineonToneMapping = 3;
  393. exports.CineonToneMapping = CineonToneMapping;
  394. const ACESFilmicToneMapping = 4;
  395. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  396. const CustomToneMapping = 5;
  397. exports.CustomToneMapping = CustomToneMapping;
  398. const UVMapping = 300;
  399. exports.UVMapping = UVMapping;
  400. const CubeReflectionMapping = 301;
  401. exports.CubeReflectionMapping = CubeReflectionMapping;
  402. const CubeRefractionMapping = 302;
  403. exports.CubeRefractionMapping = CubeRefractionMapping;
  404. const EquirectangularReflectionMapping = 303;
  405. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  406. const EquirectangularRefractionMapping = 304;
  407. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  408. const CubeUVReflectionMapping = 306;
  409. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  410. const CubeUVRefractionMapping = 307;
  411. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  412. const RepeatWrapping = 1000;
  413. exports.RepeatWrapping = RepeatWrapping;
  414. const ClampToEdgeWrapping = 1001;
  415. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  416. const MirroredRepeatWrapping = 1002;
  417. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  418. const NearestFilter = 1003;
  419. exports.NearestFilter = NearestFilter;
  420. const NearestMipmapNearestFilter = 1004;
  421. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  422. const NearestMipMapNearestFilter = 1004;
  423. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  424. const NearestMipmapLinearFilter = 1005;
  425. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  426. const NearestMipMapLinearFilter = 1005;
  427. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  428. const LinearFilter = 1006;
  429. exports.LinearFilter = LinearFilter;
  430. const LinearMipmapNearestFilter = 1007;
  431. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  432. const LinearMipMapNearestFilter = 1007;
  433. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  434. const LinearMipmapLinearFilter = 1008;
  435. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  436. const LinearMipMapLinearFilter = 1008;
  437. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  438. const UnsignedByteType = 1009;
  439. exports.UnsignedByteType = UnsignedByteType;
  440. const ByteType = 1010;
  441. exports.ByteType = ByteType;
  442. const ShortType = 1011;
  443. exports.ShortType = ShortType;
  444. const UnsignedShortType = 1012;
  445. exports.UnsignedShortType = UnsignedShortType;
  446. const IntType = 1013;
  447. exports.IntType = IntType;
  448. const UnsignedIntType = 1014;
  449. exports.UnsignedIntType = UnsignedIntType;
  450. const FloatType = 1015;
  451. exports.FloatType = FloatType;
  452. const HalfFloatType = 1016;
  453. exports.HalfFloatType = HalfFloatType;
  454. const UnsignedShort4444Type = 1017;
  455. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  456. const UnsignedShort5551Type = 1018;
  457. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  458. const UnsignedShort565Type = 1019;
  459. exports.UnsignedShort565Type = UnsignedShort565Type;
  460. const UnsignedInt248Type = 1020;
  461. exports.UnsignedInt248Type = UnsignedInt248Type;
  462. const AlphaFormat = 1021;
  463. exports.AlphaFormat = AlphaFormat;
  464. const RGBFormat = 1022;
  465. exports.RGBFormat = RGBFormat;
  466. const RGBAFormat = 1023;
  467. exports.RGBAFormat = RGBAFormat;
  468. const LuminanceFormat = 1024;
  469. exports.LuminanceFormat = LuminanceFormat;
  470. const LuminanceAlphaFormat = 1025;
  471. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  472. const RGBEFormat = RGBAFormat;
  473. exports.RGBEFormat = RGBEFormat;
  474. const DepthFormat = 1026;
  475. exports.DepthFormat = DepthFormat;
  476. const DepthStencilFormat = 1027;
  477. exports.DepthStencilFormat = DepthStencilFormat;
  478. const RedFormat = 1028;
  479. exports.RedFormat = RedFormat;
  480. const RedIntegerFormat = 1029;
  481. exports.RedIntegerFormat = RedIntegerFormat;
  482. const RGFormat = 1030;
  483. exports.RGFormat = RGFormat;
  484. const RGIntegerFormat = 1031;
  485. exports.RGIntegerFormat = RGIntegerFormat;
  486. const RGBIntegerFormat = 1032;
  487. exports.RGBIntegerFormat = RGBIntegerFormat;
  488. const RGBAIntegerFormat = 1033;
  489. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  490. const RGB_S3TC_DXT1_Format = 33776;
  491. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  492. const RGBA_S3TC_DXT1_Format = 33777;
  493. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  494. const RGBA_S3TC_DXT3_Format = 33778;
  495. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  496. const RGBA_S3TC_DXT5_Format = 33779;
  497. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  498. const RGB_PVRTC_4BPPV1_Format = 35840;
  499. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  500. const RGB_PVRTC_2BPPV1_Format = 35841;
  501. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  502. const RGBA_PVRTC_4BPPV1_Format = 35842;
  503. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  504. const RGBA_PVRTC_2BPPV1_Format = 35843;
  505. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  506. const RGB_ETC1_Format = 36196;
  507. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  508. const RGB_ETC2_Format = 37492;
  509. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  510. const RGBA_ETC2_EAC_Format = 37496;
  511. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  512. const RGBA_ASTC_4x4_Format = 37808;
  513. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  514. const RGBA_ASTC_5x4_Format = 37809;
  515. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  516. const RGBA_ASTC_5x5_Format = 37810;
  517. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  518. const RGBA_ASTC_6x5_Format = 37811;
  519. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  520. const RGBA_ASTC_6x6_Format = 37812;
  521. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  522. const RGBA_ASTC_8x5_Format = 37813;
  523. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  524. const RGBA_ASTC_8x6_Format = 37814;
  525. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  526. const RGBA_ASTC_8x8_Format = 37815;
  527. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  528. const RGBA_ASTC_10x5_Format = 37816;
  529. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  530. const RGBA_ASTC_10x6_Format = 37817;
  531. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  532. const RGBA_ASTC_10x8_Format = 37818;
  533. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  534. const RGBA_ASTC_10x10_Format = 37819;
  535. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  536. const RGBA_ASTC_12x10_Format = 37820;
  537. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  538. const RGBA_ASTC_12x12_Format = 37821;
  539. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  540. const RGBA_BPTC_Format = 36492;
  541. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  542. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  543. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  544. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  545. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  546. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  547. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  548. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  549. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  550. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  551. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  552. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  553. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  554. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  555. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  556. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  557. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  558. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  559. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  560. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  561. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  562. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  563. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  564. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  565. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  566. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  567. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  568. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  569. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  570. const LoopOnce = 2200;
  571. exports.LoopOnce = LoopOnce;
  572. const LoopRepeat = 2201;
  573. exports.LoopRepeat = LoopRepeat;
  574. const LoopPingPong = 2202;
  575. exports.LoopPingPong = LoopPingPong;
  576. const InterpolateDiscrete = 2300;
  577. exports.InterpolateDiscrete = InterpolateDiscrete;
  578. const InterpolateLinear = 2301;
  579. exports.InterpolateLinear = InterpolateLinear;
  580. const InterpolateSmooth = 2302;
  581. exports.InterpolateSmooth = InterpolateSmooth;
  582. const ZeroCurvatureEnding = 2400;
  583. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  584. const ZeroSlopeEnding = 2401;
  585. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  586. const WrapAroundEnding = 2402;
  587. exports.WrapAroundEnding = WrapAroundEnding;
  588. const NormalAnimationBlendMode = 2500;
  589. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  590. const AdditiveAnimationBlendMode = 2501;
  591. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  592. const TrianglesDrawMode = 0;
  593. exports.TrianglesDrawMode = TrianglesDrawMode;
  594. const TriangleStripDrawMode = 1;
  595. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  596. const TriangleFanDrawMode = 2;
  597. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  598. const LinearEncoding = 3000;
  599. exports.LinearEncoding = LinearEncoding;
  600. const sRGBEncoding = 3001;
  601. exports.sRGBEncoding = sRGBEncoding;
  602. const GammaEncoding = 3007;
  603. exports.GammaEncoding = GammaEncoding;
  604. const RGBEEncoding = 3002;
  605. exports.RGBEEncoding = RGBEEncoding;
  606. const LogLuvEncoding = 3003;
  607. exports.LogLuvEncoding = LogLuvEncoding;
  608. const RGBM7Encoding = 3004;
  609. exports.RGBM7Encoding = RGBM7Encoding;
  610. const RGBM16Encoding = 3005;
  611. exports.RGBM16Encoding = RGBM16Encoding;
  612. const RGBDEncoding = 3006;
  613. exports.RGBDEncoding = RGBDEncoding;
  614. const BasicDepthPacking = 3200;
  615. exports.BasicDepthPacking = BasicDepthPacking;
  616. const RGBADepthPacking = 3201;
  617. exports.RGBADepthPacking = RGBADepthPacking;
  618. const TangentSpaceNormalMap = 0;
  619. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  620. const ObjectSpaceNormalMap = 1;
  621. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  622. const ZeroStencilOp = 0;
  623. exports.ZeroStencilOp = ZeroStencilOp;
  624. const KeepStencilOp = 7680;
  625. exports.KeepStencilOp = KeepStencilOp;
  626. const ReplaceStencilOp = 7681;
  627. exports.ReplaceStencilOp = ReplaceStencilOp;
  628. const IncrementStencilOp = 7682;
  629. exports.IncrementStencilOp = IncrementStencilOp;
  630. const DecrementStencilOp = 7683;
  631. exports.DecrementStencilOp = DecrementStencilOp;
  632. const IncrementWrapStencilOp = 34055;
  633. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  634. const DecrementWrapStencilOp = 34056;
  635. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  636. const InvertStencilOp = 5386;
  637. exports.InvertStencilOp = InvertStencilOp;
  638. const NeverStencilFunc = 512;
  639. exports.NeverStencilFunc = NeverStencilFunc;
  640. const LessStencilFunc = 513;
  641. exports.LessStencilFunc = LessStencilFunc;
  642. const EqualStencilFunc = 514;
  643. exports.EqualStencilFunc = EqualStencilFunc;
  644. const LessEqualStencilFunc = 515;
  645. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  646. const GreaterStencilFunc = 516;
  647. exports.GreaterStencilFunc = GreaterStencilFunc;
  648. const NotEqualStencilFunc = 517;
  649. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  650. const GreaterEqualStencilFunc = 518;
  651. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  652. const AlwaysStencilFunc = 519;
  653. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  654. const StaticDrawUsage = 35044;
  655. exports.StaticDrawUsage = StaticDrawUsage;
  656. const DynamicDrawUsage = 35048;
  657. exports.DynamicDrawUsage = DynamicDrawUsage;
  658. const StreamDrawUsage = 35040;
  659. exports.StreamDrawUsage = StreamDrawUsage;
  660. const StaticReadUsage = 35045;
  661. exports.StaticReadUsage = StaticReadUsage;
  662. const DynamicReadUsage = 35049;
  663. exports.DynamicReadUsage = DynamicReadUsage;
  664. const StreamReadUsage = 35041;
  665. exports.StreamReadUsage = StreamReadUsage;
  666. const StaticCopyUsage = 35046;
  667. exports.StaticCopyUsage = StaticCopyUsage;
  668. const DynamicCopyUsage = 35050;
  669. exports.DynamicCopyUsage = DynamicCopyUsage;
  670. const StreamCopyUsage = 35042;
  671. exports.StreamCopyUsage = StreamCopyUsage;
  672. const GLSL1 = "100";
  673. exports.GLSL1 = GLSL1;
  674. const GLSL3 = "300 es";
  675. /**
  676. * https://github.com/mrdoob/eventdispatcher.js/
  677. */
  678. exports.GLSL3 = GLSL3;
  679. function EventDispatcher() {}
  680. Object.assign(EventDispatcher.prototype, {
  681. addEventListener: function (type, listener) {
  682. if (this._listeners === undefined) this._listeners = {};
  683. const listeners = this._listeners;
  684. if (listeners[type] === undefined) {
  685. listeners[type] = [];
  686. }
  687. if (listeners[type].indexOf(listener) === -1) {
  688. listeners[type].push(listener);
  689. }
  690. },
  691. hasEventListener: function (type, listener) {
  692. if (this._listeners === undefined) return false;
  693. const listeners = this._listeners;
  694. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  695. },
  696. removeEventListener: function (type, listener) {
  697. if (this._listeners === undefined) return;
  698. const listeners = this._listeners;
  699. const listenerArray = listeners[type];
  700. if (listenerArray !== undefined) {
  701. const index = listenerArray.indexOf(listener);
  702. if (index !== -1) {
  703. listenerArray.splice(index, 1);
  704. }
  705. }
  706. },
  707. dispatchEvent: function (event) {
  708. if (this._listeners === undefined) return;
  709. const listeners = this._listeners;
  710. const listenerArray = listeners[event.type];
  711. if (listenerArray !== undefined) {
  712. event.target = this; // Make a copy, in case listeners are removed while iterating.
  713. const array = listenerArray.slice(0);
  714. for (let i = 0, l = array.length; i < l; i++) {
  715. array[i].call(this, event);
  716. }
  717. }
  718. }
  719. });
  720. const _lut = [];
  721. for (let i = 0; i < 256; i++) {
  722. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  723. }
  724. let _seed = 1234567;
  725. const MathUtils = {
  726. DEG2RAD: Math.PI / 180,
  727. RAD2DEG: 180 / Math.PI,
  728. generateUUID: function () {
  729. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  730. const d0 = Math.random() * 0xffffffff | 0;
  731. const d1 = Math.random() * 0xffffffff | 0;
  732. const d2 = Math.random() * 0xffffffff | 0;
  733. const d3 = Math.random() * 0xffffffff | 0;
  734. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  735. return uuid.toUpperCase();
  736. },
  737. clamp: function (value, min, max) {
  738. return Math.max(min, Math.min(max, value));
  739. },
  740. // compute euclidian modulo of m % n
  741. // https://en.wikipedia.org/wiki/Modulo_operation
  742. euclideanModulo: function (n, m) {
  743. return (n % m + m) % m;
  744. },
  745. // Linear mapping from range <a1, a2> to range <b1, b2>
  746. mapLinear: function (x, a1, a2, b1, b2) {
  747. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  748. },
  749. // https://en.wikipedia.org/wiki/Linear_interpolation
  750. lerp: function (x, y, t) {
  751. return (1 - t) * x + t * y;
  752. },
  753. // http://en.wikipedia.org/wiki/Smoothstep
  754. smoothstep: function (x, min, max) {
  755. if (x <= min) return 0;
  756. if (x >= max) return 1;
  757. x = (x - min) / (max - min);
  758. return x * x * (3 - 2 * x);
  759. },
  760. smootherstep: function (x, min, max) {
  761. if (x <= min) return 0;
  762. if (x >= max) return 1;
  763. x = (x - min) / (max - min);
  764. return x * x * x * (x * (x * 6 - 15) + 10);
  765. },
  766. // Random integer from <low, high> interval
  767. randInt: function (low, high) {
  768. return low + Math.floor(Math.random() * (high - low + 1));
  769. },
  770. // Random float from <low, high> interval
  771. randFloat: function (low, high) {
  772. return low + Math.random() * (high - low);
  773. },
  774. // Random float from <-range/2, range/2> interval
  775. randFloatSpread: function (range) {
  776. return range * (0.5 - Math.random());
  777. },
  778. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  779. seededRandom: function (s) {
  780. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  781. _seed = _seed * 16807 % 2147483647;
  782. return (_seed - 1) / 2147483646;
  783. },
  784. degToRad: function (degrees) {
  785. return degrees * MathUtils.DEG2RAD;
  786. },
  787. radToDeg: function (radians) {
  788. return radians * MathUtils.RAD2DEG;
  789. },
  790. isPowerOfTwo: function (value) {
  791. return (value & value - 1) === 0 && value !== 0;
  792. },
  793. ceilPowerOfTwo: function (value) {
  794. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  795. },
  796. floorPowerOfTwo: function (value) {
  797. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  798. },
  799. setQuaternionFromProperEuler: function (q, a, b, c, order) {
  800. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  801. // rotations are applied to the axes in the order specified by 'order'
  802. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  803. // angles are in radians
  804. const cos = Math.cos;
  805. const sin = Math.sin;
  806. const c2 = cos(b / 2);
  807. const s2 = sin(b / 2);
  808. const c13 = cos((a + c) / 2);
  809. const s13 = sin((a + c) / 2);
  810. const c1_3 = cos((a - c) / 2);
  811. const s1_3 = sin((a - c) / 2);
  812. const c3_1 = cos((c - a) / 2);
  813. const s3_1 = sin((c - a) / 2);
  814. switch (order) {
  815. case 'XYX':
  816. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  817. break;
  818. case 'YZY':
  819. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  820. break;
  821. case 'ZXZ':
  822. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  823. break;
  824. case 'XZX':
  825. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  826. break;
  827. case 'YXY':
  828. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  829. break;
  830. case 'ZYZ':
  831. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  832. break;
  833. default:
  834. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  835. }
  836. }
  837. };
  838. exports.MathUtils = exports.Math = MathUtils;
  839. class Vector2 {
  840. constructor(x = 0, y = 0) {
  841. Object.defineProperty(this, 'isVector2', {
  842. value: true
  843. });
  844. this.x = x;
  845. this.y = y;
  846. }
  847. get width() {
  848. return this.x;
  849. }
  850. set width(value) {
  851. this.x = value;
  852. }
  853. get height() {
  854. return this.y;
  855. }
  856. set height(value) {
  857. this.y = value;
  858. }
  859. set(x, y) {
  860. this.x = x;
  861. this.y = y;
  862. return this;
  863. }
  864. setScalar(scalar) {
  865. this.x = scalar;
  866. this.y = scalar;
  867. return this;
  868. }
  869. setX(x) {
  870. this.x = x;
  871. return this;
  872. }
  873. setY(y) {
  874. this.y = y;
  875. return this;
  876. }
  877. setComponent(index, value) {
  878. switch (index) {
  879. case 0:
  880. this.x = value;
  881. break;
  882. case 1:
  883. this.y = value;
  884. break;
  885. default:
  886. throw new Error('index is out of range: ' + index);
  887. }
  888. return this;
  889. }
  890. getComponent(index) {
  891. switch (index) {
  892. case 0:
  893. return this.x;
  894. case 1:
  895. return this.y;
  896. default:
  897. throw new Error('index is out of range: ' + index);
  898. }
  899. }
  900. clone() {
  901. return new this.constructor(this.x, this.y);
  902. }
  903. copy(v) {
  904. this.x = v.x;
  905. this.y = v.y;
  906. return this;
  907. }
  908. add(v, w) {
  909. if (w !== undefined) {
  910. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  911. return this.addVectors(v, w);
  912. }
  913. this.x += v.x;
  914. this.y += v.y;
  915. return this;
  916. }
  917. addScalar(s) {
  918. this.x += s;
  919. this.y += s;
  920. return this;
  921. }
  922. addVectors(a, b) {
  923. this.x = a.x + b.x;
  924. this.y = a.y + b.y;
  925. return this;
  926. }
  927. addScaledVector(v, s) {
  928. this.x += v.x * s;
  929. this.y += v.y * s;
  930. return this;
  931. }
  932. sub(v, w) {
  933. if (w !== undefined) {
  934. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  935. return this.subVectors(v, w);
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. return this;
  940. }
  941. subScalar(s) {
  942. this.x -= s;
  943. this.y -= s;
  944. return this;
  945. }
  946. subVectors(a, b) {
  947. this.x = a.x - b.x;
  948. this.y = a.y - b.y;
  949. return this;
  950. }
  951. multiply(v) {
  952. this.x *= v.x;
  953. this.y *= v.y;
  954. return this;
  955. }
  956. multiplyScalar(scalar) {
  957. this.x *= scalar;
  958. this.y *= scalar;
  959. return this;
  960. }
  961. divide(v) {
  962. this.x /= v.x;
  963. this.y /= v.y;
  964. return this;
  965. }
  966. divideScalar(scalar) {
  967. return this.multiplyScalar(1 / scalar);
  968. }
  969. applyMatrix3(m) {
  970. const x = this.x,
  971. y = this.y;
  972. const e = m.elements;
  973. this.x = e[0] * x + e[3] * y + e[6];
  974. this.y = e[1] * x + e[4] * y + e[7];
  975. return this;
  976. }
  977. min(v) {
  978. this.x = Math.min(this.x, v.x);
  979. this.y = Math.min(this.y, v.y);
  980. return this;
  981. }
  982. max(v) {
  983. this.x = Math.max(this.x, v.x);
  984. this.y = Math.max(this.y, v.y);
  985. return this;
  986. }
  987. clamp(min, max) {
  988. // assumes min < max, componentwise
  989. this.x = Math.max(min.x, Math.min(max.x, this.x));
  990. this.y = Math.max(min.y, Math.min(max.y, this.y));
  991. return this;
  992. }
  993. clampScalar(minVal, maxVal) {
  994. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  995. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  996. return this;
  997. }
  998. clampLength(min, max) {
  999. const length = this.length();
  1000. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1001. }
  1002. floor() {
  1003. this.x = Math.floor(this.x);
  1004. this.y = Math.floor(this.y);
  1005. return this;
  1006. }
  1007. ceil() {
  1008. this.x = Math.ceil(this.x);
  1009. this.y = Math.ceil(this.y);
  1010. return this;
  1011. }
  1012. round() {
  1013. this.x = Math.round(this.x);
  1014. this.y = Math.round(this.y);
  1015. return this;
  1016. }
  1017. roundToZero() {
  1018. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1019. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1020. return this;
  1021. }
  1022. negate() {
  1023. this.x = -this.x;
  1024. this.y = -this.y;
  1025. return this;
  1026. }
  1027. dot(v) {
  1028. return this.x * v.x + this.y * v.y;
  1029. }
  1030. cross(v) {
  1031. return this.x * v.y - this.y * v.x;
  1032. }
  1033. lengthSq() {
  1034. return this.x * this.x + this.y * this.y;
  1035. }
  1036. length() {
  1037. return Math.sqrt(this.x * this.x + this.y * this.y);
  1038. }
  1039. manhattanLength() {
  1040. return Math.abs(this.x) + Math.abs(this.y);
  1041. }
  1042. normalize() {
  1043. return this.divideScalar(this.length() || 1);
  1044. }
  1045. angle() {
  1046. // computes the angle in radians with respect to the positive x-axis
  1047. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  1048. return angle;
  1049. }
  1050. distanceTo(v) {
  1051. return Math.sqrt(this.distanceToSquared(v));
  1052. }
  1053. distanceToSquared(v) {
  1054. const dx = this.x - v.x,
  1055. dy = this.y - v.y;
  1056. return dx * dx + dy * dy;
  1057. }
  1058. manhattanDistanceTo(v) {
  1059. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1060. }
  1061. setLength(length) {
  1062. return this.normalize().multiplyScalar(length);
  1063. }
  1064. lerp(v, alpha) {
  1065. this.x += (v.x - this.x) * alpha;
  1066. this.y += (v.y - this.y) * alpha;
  1067. return this;
  1068. }
  1069. lerpVectors(v1, v2, alpha) {
  1070. this.x = v1.x + (v2.x - v1.x) * alpha;
  1071. this.y = v1.y + (v2.y - v1.y) * alpha;
  1072. return this;
  1073. }
  1074. equals(v) {
  1075. return v.x === this.x && v.y === this.y;
  1076. }
  1077. fromArray(array, offset = 0) {
  1078. this.x = array[offset];
  1079. this.y = array[offset + 1];
  1080. return this;
  1081. }
  1082. toArray(array = [], offset = 0) {
  1083. array[offset] = this.x;
  1084. array[offset + 1] = this.y;
  1085. return array;
  1086. }
  1087. fromBufferAttribute(attribute, index, offset) {
  1088. if (offset !== undefined) {
  1089. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1090. }
  1091. this.x = attribute.getX(index);
  1092. this.y = attribute.getY(index);
  1093. return this;
  1094. }
  1095. rotateAround(center, angle) {
  1096. const c = Math.cos(angle),
  1097. s = Math.sin(angle);
  1098. const x = this.x - center.x;
  1099. const y = this.y - center.y;
  1100. this.x = x * c - y * s + center.x;
  1101. this.y = x * s + y * c + center.y;
  1102. return this;
  1103. }
  1104. random() {
  1105. this.x = Math.random();
  1106. this.y = Math.random();
  1107. return this;
  1108. }
  1109. }
  1110. exports.Vector2 = Vector2;
  1111. class Matrix3 {
  1112. constructor() {
  1113. Object.defineProperty(this, 'isMatrix3', {
  1114. value: true
  1115. });
  1116. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1117. if (arguments.length > 0) {
  1118. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1119. }
  1120. }
  1121. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1122. const te = this.elements;
  1123. te[0] = n11;
  1124. te[1] = n21;
  1125. te[2] = n31;
  1126. te[3] = n12;
  1127. te[4] = n22;
  1128. te[5] = n32;
  1129. te[6] = n13;
  1130. te[7] = n23;
  1131. te[8] = n33;
  1132. return this;
  1133. }
  1134. identity() {
  1135. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  1136. return this;
  1137. }
  1138. clone() {
  1139. return new this.constructor().fromArray(this.elements);
  1140. }
  1141. copy(m) {
  1142. const te = this.elements;
  1143. const me = m.elements;
  1144. te[0] = me[0];
  1145. te[1] = me[1];
  1146. te[2] = me[2];
  1147. te[3] = me[3];
  1148. te[4] = me[4];
  1149. te[5] = me[5];
  1150. te[6] = me[6];
  1151. te[7] = me[7];
  1152. te[8] = me[8];
  1153. return this;
  1154. }
  1155. extractBasis(xAxis, yAxis, zAxis) {
  1156. xAxis.setFromMatrix3Column(this, 0);
  1157. yAxis.setFromMatrix3Column(this, 1);
  1158. zAxis.setFromMatrix3Column(this, 2);
  1159. return this;
  1160. }
  1161. setFromMatrix4(m) {
  1162. const me = m.elements;
  1163. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  1164. return this;
  1165. }
  1166. multiply(m) {
  1167. return this.multiplyMatrices(this, m);
  1168. }
  1169. premultiply(m) {
  1170. return this.multiplyMatrices(m, this);
  1171. }
  1172. multiplyMatrices(a, b) {
  1173. const ae = a.elements;
  1174. const be = b.elements;
  1175. const te = this.elements;
  1176. const a11 = ae[0],
  1177. a12 = ae[3],
  1178. a13 = ae[6];
  1179. const a21 = ae[1],
  1180. a22 = ae[4],
  1181. a23 = ae[7];
  1182. const a31 = ae[2],
  1183. a32 = ae[5],
  1184. a33 = ae[8];
  1185. const b11 = be[0],
  1186. b12 = be[3],
  1187. b13 = be[6];
  1188. const b21 = be[1],
  1189. b22 = be[4],
  1190. b23 = be[7];
  1191. const b31 = be[2],
  1192. b32 = be[5],
  1193. b33 = be[8];
  1194. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  1195. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  1196. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  1197. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  1198. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  1199. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  1200. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  1201. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  1202. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  1203. return this;
  1204. }
  1205. multiplyScalar(s) {
  1206. const te = this.elements;
  1207. te[0] *= s;
  1208. te[3] *= s;
  1209. te[6] *= s;
  1210. te[1] *= s;
  1211. te[4] *= s;
  1212. te[7] *= s;
  1213. te[2] *= s;
  1214. te[5] *= s;
  1215. te[8] *= s;
  1216. return this;
  1217. }
  1218. determinant() {
  1219. const te = this.elements;
  1220. const a = te[0],
  1221. b = te[1],
  1222. c = te[2],
  1223. d = te[3],
  1224. e = te[4],
  1225. f = te[5],
  1226. g = te[6],
  1227. h = te[7],
  1228. i = te[8];
  1229. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1230. }
  1231. invert() {
  1232. const te = this.elements,
  1233. n11 = te[0],
  1234. n21 = te[1],
  1235. n31 = te[2],
  1236. n12 = te[3],
  1237. n22 = te[4],
  1238. n32 = te[5],
  1239. n13 = te[6],
  1240. n23 = te[7],
  1241. n33 = te[8],
  1242. t11 = n33 * n22 - n32 * n23,
  1243. t12 = n32 * n13 - n33 * n12,
  1244. t13 = n23 * n12 - n22 * n13,
  1245. det = n11 * t11 + n21 * t12 + n31 * t13;
  1246. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  1247. const detInv = 1 / det;
  1248. te[0] = t11 * detInv;
  1249. te[1] = (n31 * n23 - n33 * n21) * detInv;
  1250. te[2] = (n32 * n21 - n31 * n22) * detInv;
  1251. te[3] = t12 * detInv;
  1252. te[4] = (n33 * n11 - n31 * n13) * detInv;
  1253. te[5] = (n31 * n12 - n32 * n11) * detInv;
  1254. te[6] = t13 * detInv;
  1255. te[7] = (n21 * n13 - n23 * n11) * detInv;
  1256. te[8] = (n22 * n11 - n21 * n12) * detInv;
  1257. return this;
  1258. }
  1259. transpose() {
  1260. let tmp;
  1261. const m = this.elements;
  1262. tmp = m[1];
  1263. m[1] = m[3];
  1264. m[3] = tmp;
  1265. tmp = m[2];
  1266. m[2] = m[6];
  1267. m[6] = tmp;
  1268. tmp = m[5];
  1269. m[5] = m[7];
  1270. m[7] = tmp;
  1271. return this;
  1272. }
  1273. getNormalMatrix(matrix4) {
  1274. return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
  1275. }
  1276. transposeIntoArray(r) {
  1277. const m = this.elements;
  1278. r[0] = m[0];
  1279. r[1] = m[3];
  1280. r[2] = m[6];
  1281. r[3] = m[1];
  1282. r[4] = m[4];
  1283. r[5] = m[7];
  1284. r[6] = m[2];
  1285. r[7] = m[5];
  1286. r[8] = m[8];
  1287. return this;
  1288. }
  1289. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  1290. const c = Math.cos(rotation);
  1291. const s = Math.sin(rotation);
  1292. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  1293. }
  1294. scale(sx, sy) {
  1295. const te = this.elements;
  1296. te[0] *= sx;
  1297. te[3] *= sx;
  1298. te[6] *= sx;
  1299. te[1] *= sy;
  1300. te[4] *= sy;
  1301. te[7] *= sy;
  1302. return this;
  1303. }
  1304. rotate(theta) {
  1305. const c = Math.cos(theta);
  1306. const s = Math.sin(theta);
  1307. const te = this.elements;
  1308. const a11 = te[0],
  1309. a12 = te[3],
  1310. a13 = te[6];
  1311. const a21 = te[1],
  1312. a22 = te[4],
  1313. a23 = te[7];
  1314. te[0] = c * a11 + s * a21;
  1315. te[3] = c * a12 + s * a22;
  1316. te[6] = c * a13 + s * a23;
  1317. te[1] = -s * a11 + c * a21;
  1318. te[4] = -s * a12 + c * a22;
  1319. te[7] = -s * a13 + c * a23;
  1320. return this;
  1321. }
  1322. translate(tx, ty) {
  1323. const te = this.elements;
  1324. te[0] += tx * te[2];
  1325. te[3] += tx * te[5];
  1326. te[6] += tx * te[8];
  1327. te[1] += ty * te[2];
  1328. te[4] += ty * te[5];
  1329. te[7] += ty * te[8];
  1330. return this;
  1331. }
  1332. equals(matrix) {
  1333. const te = this.elements;
  1334. const me = matrix.elements;
  1335. for (let i = 0; i < 9; i++) {
  1336. if (te[i] !== me[i]) return false;
  1337. }
  1338. return true;
  1339. }
  1340. fromArray(array, offset = 0) {
  1341. for (let i = 0; i < 9; i++) {
  1342. this.elements[i] = array[i + offset];
  1343. }
  1344. return this;
  1345. }
  1346. toArray(array = [], offset = 0) {
  1347. const te = this.elements;
  1348. array[offset] = te[0];
  1349. array[offset + 1] = te[1];
  1350. array[offset + 2] = te[2];
  1351. array[offset + 3] = te[3];
  1352. array[offset + 4] = te[4];
  1353. array[offset + 5] = te[5];
  1354. array[offset + 6] = te[6];
  1355. array[offset + 7] = te[7];
  1356. array[offset + 8] = te[8];
  1357. return array;
  1358. }
  1359. }
  1360. exports.Matrix3 = Matrix3;
  1361. let _canvas;
  1362. const ImageUtils = {
  1363. getDataURL: function (image) {
  1364. if (/^data:/i.test(image.src)) {
  1365. return image.src;
  1366. }
  1367. if (typeof HTMLCanvasElement == 'undefined') {
  1368. return image.src;
  1369. }
  1370. let canvas;
  1371. if (image instanceof HTMLCanvasElement) {
  1372. canvas = image;
  1373. } else {
  1374. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  1375. _canvas.width = image.width;
  1376. _canvas.height = image.height;
  1377. const context = _canvas.getContext('2d');
  1378. if (image instanceof ImageData) {
  1379. context.putImageData(image, 0, 0);
  1380. } else {
  1381. context.drawImage(image, 0, 0, image.width, image.height);
  1382. }
  1383. canvas = _canvas;
  1384. }
  1385. if (canvas.width > 2048 || canvas.height > 2048) {
  1386. return canvas.toDataURL('image/jpeg', 0.6);
  1387. } else {
  1388. return canvas.toDataURL('image/png');
  1389. }
  1390. }
  1391. };
  1392. exports.ImageUtils = ImageUtils;
  1393. let textureId = 0;
  1394. function Texture(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1395. Object.defineProperty(this, 'id', {
  1396. value: textureId++
  1397. });
  1398. this.uuid = MathUtils.generateUUID();
  1399. this.name = '';
  1400. this.image = image;
  1401. this.mipmaps = [];
  1402. this.mapping = mapping;
  1403. this.wrapS = wrapS;
  1404. this.wrapT = wrapT;
  1405. this.magFilter = magFilter;
  1406. this.minFilter = minFilter;
  1407. this.anisotropy = anisotropy;
  1408. this.format = format;
  1409. this.internalFormat = null;
  1410. this.type = type;
  1411. this.offset = new Vector2(0, 0);
  1412. this.repeat = new Vector2(1, 1);
  1413. this.center = new Vector2(0, 0);
  1414. this.rotation = 0;
  1415. this.matrixAutoUpdate = true;
  1416. this.matrix = new Matrix3();
  1417. this.generateMipmaps = true;
  1418. this.premultiplyAlpha = false;
  1419. this.flipY = true;
  1420. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1421. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1422. //
  1423. // Also changing the encoding after already used by a Material will not automatically make the Material
  1424. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1425. this.encoding = encoding;
  1426. this.version = 0;
  1427. this.onUpdate = null;
  1428. }
  1429. Texture.DEFAULT_IMAGE = undefined;
  1430. Texture.DEFAULT_MAPPING = UVMapping;
  1431. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  1432. constructor: Texture,
  1433. isTexture: true,
  1434. updateMatrix: function () {
  1435. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1436. },
  1437. clone: function () {
  1438. return new this.constructor().copy(this);
  1439. },
  1440. copy: function (source) {
  1441. this.name = source.name;
  1442. this.image = source.image;
  1443. this.mipmaps = source.mipmaps.slice(0);
  1444. this.mapping = source.mapping;
  1445. this.wrapS = source.wrapS;
  1446. this.wrapT = source.wrapT;
  1447. this.magFilter = source.magFilter;
  1448. this.minFilter = source.minFilter;
  1449. this.anisotropy = source.anisotropy;
  1450. this.format = source.format;
  1451. this.internalFormat = source.internalFormat;
  1452. this.type = source.type;
  1453. this.offset.copy(source.offset);
  1454. this.repeat.copy(source.repeat);
  1455. this.center.copy(source.center);
  1456. this.rotation = source.rotation;
  1457. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1458. this.matrix.copy(source.matrix);
  1459. this.generateMipmaps = source.generateMipmaps;
  1460. this.premultiplyAlpha = source.premultiplyAlpha;
  1461. this.flipY = source.flipY;
  1462. this.unpackAlignment = source.unpackAlignment;
  1463. this.encoding = source.encoding;
  1464. return this;
  1465. },
  1466. toJSON: function (meta) {
  1467. const isRootObject = meta === undefined || typeof meta === 'string';
  1468. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1469. return meta.textures[this.uuid];
  1470. }
  1471. const output = {
  1472. metadata: {
  1473. version: 4.5,
  1474. type: 'Texture',
  1475. generator: 'Texture.toJSON'
  1476. },
  1477. uuid: this.uuid,
  1478. name: this.name,
  1479. mapping: this.mapping,
  1480. repeat: [this.repeat.x, this.repeat.y],
  1481. offset: [this.offset.x, this.offset.y],
  1482. center: [this.center.x, this.center.y],
  1483. rotation: this.rotation,
  1484. wrap: [this.wrapS, this.wrapT],
  1485. format: this.format,
  1486. type: this.type,
  1487. encoding: this.encoding,
  1488. minFilter: this.minFilter,
  1489. magFilter: this.magFilter,
  1490. anisotropy: this.anisotropy,
  1491. flipY: this.flipY,
  1492. premultiplyAlpha: this.premultiplyAlpha,
  1493. unpackAlignment: this.unpackAlignment
  1494. };
  1495. if (this.image !== undefined) {
  1496. // TODO: Move to THREE.Image
  1497. const image = this.image;
  1498. if (image.uuid === undefined) {
  1499. image.uuid = MathUtils.generateUUID(); // UGH
  1500. }
  1501. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1502. let url;
  1503. if (Array.isArray(image)) {
  1504. // process array of images e.g. CubeTexture
  1505. url = [];
  1506. for (let i = 0, l = image.length; i < l; i++) {
  1507. // check cube texture with data textures
  1508. if (image[i].isDataTexture) {
  1509. url.push(serializeImage(image[i].image));
  1510. } else {
  1511. url.push(serializeImage(image[i]));
  1512. }
  1513. }
  1514. } else {
  1515. // process single image
  1516. url = serializeImage(image);
  1517. }
  1518. meta.images[image.uuid] = {
  1519. uuid: image.uuid,
  1520. url: url
  1521. };
  1522. }
  1523. output.image = image.uuid;
  1524. }
  1525. if (!isRootObject) {
  1526. meta.textures[this.uuid] = output;
  1527. }
  1528. return output;
  1529. },
  1530. dispose: function () {
  1531. this.dispatchEvent({
  1532. type: 'dispose'
  1533. });
  1534. },
  1535. transformUv: function (uv) {
  1536. if (this.mapping !== UVMapping) return uv;
  1537. uv.applyMatrix3(this.matrix);
  1538. if (uv.x < 0 || uv.x > 1) {
  1539. switch (this.wrapS) {
  1540. case RepeatWrapping:
  1541. uv.x = uv.x - Math.floor(uv.x);
  1542. break;
  1543. case ClampToEdgeWrapping:
  1544. uv.x = uv.x < 0 ? 0 : 1;
  1545. break;
  1546. case MirroredRepeatWrapping:
  1547. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1548. uv.x = Math.ceil(uv.x) - uv.x;
  1549. } else {
  1550. uv.x = uv.x - Math.floor(uv.x);
  1551. }
  1552. break;
  1553. }
  1554. }
  1555. if (uv.y < 0 || uv.y > 1) {
  1556. switch (this.wrapT) {
  1557. case RepeatWrapping:
  1558. uv.y = uv.y - Math.floor(uv.y);
  1559. break;
  1560. case ClampToEdgeWrapping:
  1561. uv.y = uv.y < 0 ? 0 : 1;
  1562. break;
  1563. case MirroredRepeatWrapping:
  1564. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1565. uv.y = Math.ceil(uv.y) - uv.y;
  1566. } else {
  1567. uv.y = uv.y - Math.floor(uv.y);
  1568. }
  1569. break;
  1570. }
  1571. }
  1572. if (this.flipY) {
  1573. uv.y = 1 - uv.y;
  1574. }
  1575. return uv;
  1576. }
  1577. });
  1578. Object.defineProperty(Texture.prototype, "needsUpdate", {
  1579. set: function (value) {
  1580. if (value === true) this.version++;
  1581. }
  1582. });
  1583. function serializeImage(image) {
  1584. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1585. // default images
  1586. return ImageUtils.getDataURL(image);
  1587. } else {
  1588. if (image.data) {
  1589. // images of DataTexture
  1590. return {
  1591. data: Array.prototype.slice.call(image.data),
  1592. width: image.width,
  1593. height: image.height,
  1594. type: image.data.constructor.name
  1595. };
  1596. } else {
  1597. console.warn('THREE.Texture: Unable to serialize Texture.');
  1598. return {};
  1599. }
  1600. }
  1601. }
  1602. class Vector4 {
  1603. constructor(x = 0, y = 0, z = 0, w = 1) {
  1604. Object.defineProperty(this, 'isVector4', {
  1605. value: true
  1606. });
  1607. this.x = x;
  1608. this.y = y;
  1609. this.z = z;
  1610. this.w = w;
  1611. }
  1612. get width() {
  1613. return this.z;
  1614. }
  1615. set width(value) {
  1616. this.z = value;
  1617. }
  1618. get height() {
  1619. return this.w;
  1620. }
  1621. set height(value) {
  1622. this.w = value;
  1623. }
  1624. set(x, y, z, w) {
  1625. this.x = x;
  1626. this.y = y;
  1627. this.z = z;
  1628. this.w = w;
  1629. return this;
  1630. }
  1631. setScalar(scalar) {
  1632. this.x = scalar;
  1633. this.y = scalar;
  1634. this.z = scalar;
  1635. this.w = scalar;
  1636. return this;
  1637. }
  1638. setX(x) {
  1639. this.x = x;
  1640. return this;
  1641. }
  1642. setY(y) {
  1643. this.y = y;
  1644. return this;
  1645. }
  1646. setZ(z) {
  1647. this.z = z;
  1648. return this;
  1649. }
  1650. setW(w) {
  1651. this.w = w;
  1652. return this;
  1653. }
  1654. setComponent(index, value) {
  1655. switch (index) {
  1656. case 0:
  1657. this.x = value;
  1658. break;
  1659. case 1:
  1660. this.y = value;
  1661. break;
  1662. case 2:
  1663. this.z = value;
  1664. break;
  1665. case 3:
  1666. this.w = value;
  1667. break;
  1668. default:
  1669. throw new Error('index is out of range: ' + index);
  1670. }
  1671. return this;
  1672. }
  1673. getComponent(index) {
  1674. switch (index) {
  1675. case 0:
  1676. return this.x;
  1677. case 1:
  1678. return this.y;
  1679. case 2:
  1680. return this.z;
  1681. case 3:
  1682. return this.w;
  1683. default:
  1684. throw new Error('index is out of range: ' + index);
  1685. }
  1686. }
  1687. clone() {
  1688. return new this.constructor(this.x, this.y, this.z, this.w);
  1689. }
  1690. copy(v) {
  1691. this.x = v.x;
  1692. this.y = v.y;
  1693. this.z = v.z;
  1694. this.w = v.w !== undefined ? v.w : 1;
  1695. return this;
  1696. }
  1697. add(v, w) {
  1698. if (w !== undefined) {
  1699. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1700. return this.addVectors(v, w);
  1701. }
  1702. this.x += v.x;
  1703. this.y += v.y;
  1704. this.z += v.z;
  1705. this.w += v.w;
  1706. return this;
  1707. }
  1708. addScalar(s) {
  1709. this.x += s;
  1710. this.y += s;
  1711. this.z += s;
  1712. this.w += s;
  1713. return this;
  1714. }
  1715. addVectors(a, b) {
  1716. this.x = a.x + b.x;
  1717. this.y = a.y + b.y;
  1718. this.z = a.z + b.z;
  1719. this.w = a.w + b.w;
  1720. return this;
  1721. }
  1722. addScaledVector(v, s) {
  1723. this.x += v.x * s;
  1724. this.y += v.y * s;
  1725. this.z += v.z * s;
  1726. this.w += v.w * s;
  1727. return this;
  1728. }
  1729. sub(v, w) {
  1730. if (w !== undefined) {
  1731. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1732. return this.subVectors(v, w);
  1733. }
  1734. this.x -= v.x;
  1735. this.y -= v.y;
  1736. this.z -= v.z;
  1737. this.w -= v.w;
  1738. return this;
  1739. }
  1740. subScalar(s) {
  1741. this.x -= s;
  1742. this.y -= s;
  1743. this.z -= s;
  1744. this.w -= s;
  1745. return this;
  1746. }
  1747. subVectors(a, b) {
  1748. this.x = a.x - b.x;
  1749. this.y = a.y - b.y;
  1750. this.z = a.z - b.z;
  1751. this.w = a.w - b.w;
  1752. return this;
  1753. }
  1754. multiplyScalar(scalar) {
  1755. this.x *= scalar;
  1756. this.y *= scalar;
  1757. this.z *= scalar;
  1758. this.w *= scalar;
  1759. return this;
  1760. }
  1761. applyMatrix4(m) {
  1762. const x = this.x,
  1763. y = this.y,
  1764. z = this.z,
  1765. w = this.w;
  1766. const e = m.elements;
  1767. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1768. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1769. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1770. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1771. return this;
  1772. }
  1773. divideScalar(scalar) {
  1774. return this.multiplyScalar(1 / scalar);
  1775. }
  1776. setAxisAngleFromQuaternion(q) {
  1777. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1778. // q is assumed to be normalized
  1779. this.w = 2 * Math.acos(q.w);
  1780. const s = Math.sqrt(1 - q.w * q.w);
  1781. if (s < 0.0001) {
  1782. this.x = 1;
  1783. this.y = 0;
  1784. this.z = 0;
  1785. } else {
  1786. this.x = q.x / s;
  1787. this.y = q.y / s;
  1788. this.z = q.z / s;
  1789. }
  1790. return this;
  1791. }
  1792. setAxisAngleFromRotationMatrix(m) {
  1793. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1794. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1795. let angle, x, y, z; // variables for result
  1796. const epsilon = 0.01,
  1797. // margin to allow for rounding errors
  1798. epsilon2 = 0.1,
  1799. // margin to distinguish between 0 and 180 degrees
  1800. te = m.elements,
  1801. m11 = te[0],
  1802. m12 = te[4],
  1803. m13 = te[8],
  1804. m21 = te[1],
  1805. m22 = te[5],
  1806. m23 = te[9],
  1807. m31 = te[2],
  1808. m32 = te[6],
  1809. m33 = te[10];
  1810. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1811. // singularity found
  1812. // first check for identity matrix which must have +1 for all terms
  1813. // in leading diagonal and zero in other terms
  1814. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1815. // this singularity is identity matrix so angle = 0
  1816. this.set(1, 0, 0, 0);
  1817. return this; // zero angle, arbitrary axis
  1818. } // otherwise this singularity is angle = 180
  1819. angle = Math.PI;
  1820. const xx = (m11 + 1) / 2;
  1821. const yy = (m22 + 1) / 2;
  1822. const zz = (m33 + 1) / 2;
  1823. const xy = (m12 + m21) / 4;
  1824. const xz = (m13 + m31) / 4;
  1825. const yz = (m23 + m32) / 4;
  1826. if (xx > yy && xx > zz) {
  1827. // m11 is the largest diagonal term
  1828. if (xx < epsilon) {
  1829. x = 0;
  1830. y = 0.707106781;
  1831. z = 0.707106781;
  1832. } else {
  1833. x = Math.sqrt(xx);
  1834. y = xy / x;
  1835. z = xz / x;
  1836. }
  1837. } else if (yy > zz) {
  1838. // m22 is the largest diagonal term
  1839. if (yy < epsilon) {
  1840. x = 0.707106781;
  1841. y = 0;
  1842. z = 0.707106781;
  1843. } else {
  1844. y = Math.sqrt(yy);
  1845. x = xy / y;
  1846. z = yz / y;
  1847. }
  1848. } else {
  1849. // m33 is the largest diagonal term so base result on this
  1850. if (zz < epsilon) {
  1851. x = 0.707106781;
  1852. y = 0.707106781;
  1853. z = 0;
  1854. } else {
  1855. z = Math.sqrt(zz);
  1856. x = xz / z;
  1857. y = yz / z;
  1858. }
  1859. }
  1860. this.set(x, y, z, angle);
  1861. return this; // return 180 deg rotation
  1862. } // as we have reached here there are no singularities so we can handle normally
  1863. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1864. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1865. // caught by singularity test above, but I've left it in just in case
  1866. this.x = (m32 - m23) / s;
  1867. this.y = (m13 - m31) / s;
  1868. this.z = (m21 - m12) / s;
  1869. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1870. return this;
  1871. }
  1872. min(v) {
  1873. this.x = Math.min(this.x, v.x);
  1874. this.y = Math.min(this.y, v.y);
  1875. this.z = Math.min(this.z, v.z);
  1876. this.w = Math.min(this.w, v.w);
  1877. return this;
  1878. }
  1879. max(v) {
  1880. this.x = Math.max(this.x, v.x);
  1881. this.y = Math.max(this.y, v.y);
  1882. this.z = Math.max(this.z, v.z);
  1883. this.w = Math.max(this.w, v.w);
  1884. return this;
  1885. }
  1886. clamp(min, max) {
  1887. // assumes min < max, componentwise
  1888. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1889. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1890. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1891. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1892. return this;
  1893. }
  1894. clampScalar(minVal, maxVal) {
  1895. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1896. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1897. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1898. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1899. return this;
  1900. }
  1901. clampLength(min, max) {
  1902. const length = this.length();
  1903. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1904. }
  1905. floor() {
  1906. this.x = Math.floor(this.x);
  1907. this.y = Math.floor(this.y);
  1908. this.z = Math.floor(this.z);
  1909. this.w = Math.floor(this.w);
  1910. return this;
  1911. }
  1912. ceil() {
  1913. this.x = Math.ceil(this.x);
  1914. this.y = Math.ceil(this.y);
  1915. this.z = Math.ceil(this.z);
  1916. this.w = Math.ceil(this.w);
  1917. return this;
  1918. }
  1919. round() {
  1920. this.x = Math.round(this.x);
  1921. this.y = Math.round(this.y);
  1922. this.z = Math.round(this.z);
  1923. this.w = Math.round(this.w);
  1924. return this;
  1925. }
  1926. roundToZero() {
  1927. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1928. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1929. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1930. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1931. return this;
  1932. }
  1933. negate() {
  1934. this.x = -this.x;
  1935. this.y = -this.y;
  1936. this.z = -this.z;
  1937. this.w = -this.w;
  1938. return this;
  1939. }
  1940. dot(v) {
  1941. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1942. }
  1943. lengthSq() {
  1944. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1945. }
  1946. length() {
  1947. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1948. }
  1949. manhattanLength() {
  1950. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1951. }
  1952. normalize() {
  1953. return this.divideScalar(this.length() || 1);
  1954. }
  1955. setLength(length) {
  1956. return this.normalize().multiplyScalar(length);
  1957. }
  1958. lerp(v, alpha) {
  1959. this.x += (v.x - this.x) * alpha;
  1960. this.y += (v.y - this.y) * alpha;
  1961. this.z += (v.z - this.z) * alpha;
  1962. this.w += (v.w - this.w) * alpha;
  1963. return this;
  1964. }
  1965. lerpVectors(v1, v2, alpha) {
  1966. this.x = v1.x + (v2.x - v1.x) * alpha;
  1967. this.y = v1.y + (v2.y - v1.y) * alpha;
  1968. this.z = v1.z + (v2.z - v1.z) * alpha;
  1969. this.w = v1.w + (v2.w - v1.w) * alpha;
  1970. return this;
  1971. }
  1972. equals(v) {
  1973. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1974. }
  1975. fromArray(array, offset = 0) {
  1976. this.x = array[offset];
  1977. this.y = array[offset + 1];
  1978. this.z = array[offset + 2];
  1979. this.w = array[offset + 3];
  1980. return this;
  1981. }
  1982. toArray(array = [], offset = 0) {
  1983. array[offset] = this.x;
  1984. array[offset + 1] = this.y;
  1985. array[offset + 2] = this.z;
  1986. array[offset + 3] = this.w;
  1987. return array;
  1988. }
  1989. fromBufferAttribute(attribute, index, offset) {
  1990. if (offset !== undefined) {
  1991. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1992. }
  1993. this.x = attribute.getX(index);
  1994. this.y = attribute.getY(index);
  1995. this.z = attribute.getZ(index);
  1996. this.w = attribute.getW(index);
  1997. return this;
  1998. }
  1999. random() {
  2000. this.x = Math.random();
  2001. this.y = Math.random();
  2002. this.z = Math.random();
  2003. this.w = Math.random();
  2004. return this;
  2005. }
  2006. }
  2007. /*
  2008. In options, we can specify:
  2009. * Texture parameters for an auto-generated target texture
  2010. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2011. */
  2012. exports.Vector4 = Vector4;
  2013. function WebGLRenderTarget(width, height, options) {
  2014. this.width = width;
  2015. this.height = height;
  2016. this.scissor = new Vector4(0, 0, width, height);
  2017. this.scissorTest = false;
  2018. this.viewport = new Vector4(0, 0, width, height);
  2019. options = options || {};
  2020. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2021. this.texture.image = {};
  2022. this.texture.image.width = width;
  2023. this.texture.image.height = height;
  2024. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2025. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2026. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2027. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2028. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2029. }
  2030. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2031. constructor: WebGLRenderTarget,
  2032. isWebGLRenderTarget: true,
  2033. setSize: function (width, height) {
  2034. if (this.width !== width || this.height !== height) {
  2035. this.width = width;
  2036. this.height = height;
  2037. this.texture.image.width = width;
  2038. this.texture.image.height = height;
  2039. this.dispose();
  2040. }
  2041. this.viewport.set(0, 0, width, height);
  2042. this.scissor.set(0, 0, width, height);
  2043. },
  2044. clone: function () {
  2045. return new this.constructor().copy(this);
  2046. },
  2047. copy: function (source) {
  2048. this.width = source.width;
  2049. this.height = source.height;
  2050. this.viewport.copy(source.viewport);
  2051. this.texture = source.texture.clone();
  2052. this.depthBuffer = source.depthBuffer;
  2053. this.stencilBuffer = source.stencilBuffer;
  2054. this.depthTexture = source.depthTexture;
  2055. return this;
  2056. },
  2057. dispose: function () {
  2058. this.dispatchEvent({
  2059. type: 'dispose'
  2060. });
  2061. }
  2062. });
  2063. function WebGLMultisampleRenderTarget(width, height, options) {
  2064. WebGLRenderTarget.call(this, width, height, options);
  2065. this.samples = 4;
  2066. }
  2067. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2068. constructor: WebGLMultisampleRenderTarget,
  2069. isWebGLMultisampleRenderTarget: true,
  2070. copy: function (source) {
  2071. WebGLRenderTarget.prototype.copy.call(this, source);
  2072. this.samples = source.samples;
  2073. return this;
  2074. }
  2075. });
  2076. class Quaternion {
  2077. constructor(x = 0, y = 0, z = 0, w = 1) {
  2078. Object.defineProperty(this, 'isQuaternion', {
  2079. value: true
  2080. });
  2081. this._x = x;
  2082. this._y = y;
  2083. this._z = z;
  2084. this._w = w;
  2085. }
  2086. static slerp(qa, qb, qm, t) {
  2087. return qm.copy(qa).slerp(qb, t);
  2088. }
  2089. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2090. // fuzz-free, array-based Quaternion SLERP operation
  2091. let x0 = src0[srcOffset0 + 0],
  2092. y0 = src0[srcOffset0 + 1],
  2093. z0 = src0[srcOffset0 + 2],
  2094. w0 = src0[srcOffset0 + 3];
  2095. const x1 = src1[srcOffset1 + 0],
  2096. y1 = src1[srcOffset1 + 1],
  2097. z1 = src1[srcOffset1 + 2],
  2098. w1 = src1[srcOffset1 + 3];
  2099. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2100. let s = 1 - t;
  2101. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2102. dir = cos >= 0 ? 1 : -1,
  2103. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2104. if (sqrSin > Number.EPSILON) {
  2105. const sin = Math.sqrt(sqrSin),
  2106. len = Math.atan2(sin, cos * dir);
  2107. s = Math.sin(s * len) / sin;
  2108. t = Math.sin(t * len) / sin;
  2109. }
  2110. const tDir = t * dir;
  2111. x0 = x0 * s + x1 * tDir;
  2112. y0 = y0 * s + y1 * tDir;
  2113. z0 = z0 * s + z1 * tDir;
  2114. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2115. if (s === 1 - t) {
  2116. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2117. x0 *= f;
  2118. y0 *= f;
  2119. z0 *= f;
  2120. w0 *= f;
  2121. }
  2122. }
  2123. dst[dstOffset] = x0;
  2124. dst[dstOffset + 1] = y0;
  2125. dst[dstOffset + 2] = z0;
  2126. dst[dstOffset + 3] = w0;
  2127. }
  2128. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2129. const x0 = src0[srcOffset0];
  2130. const y0 = src0[srcOffset0 + 1];
  2131. const z0 = src0[srcOffset0 + 2];
  2132. const w0 = src0[srcOffset0 + 3];
  2133. const x1 = src1[srcOffset1];
  2134. const y1 = src1[srcOffset1 + 1];
  2135. const z1 = src1[srcOffset1 + 2];
  2136. const w1 = src1[srcOffset1 + 3];
  2137. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2138. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2139. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2140. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2141. return dst;
  2142. }
  2143. get x() {
  2144. return this._x;
  2145. }
  2146. set x(value) {
  2147. this._x = value;
  2148. this._onChangeCallback();
  2149. }
  2150. get y() {
  2151. return this._y;
  2152. }
  2153. set y(value) {
  2154. this._y = value;
  2155. this._onChangeCallback();
  2156. }
  2157. get z() {
  2158. return this._z;
  2159. }
  2160. set z(value) {
  2161. this._z = value;
  2162. this._onChangeCallback();
  2163. }
  2164. get w() {
  2165. return this._w;
  2166. }
  2167. set w(value) {
  2168. this._w = value;
  2169. this._onChangeCallback();
  2170. }
  2171. set(x, y, z, w) {
  2172. this._x = x;
  2173. this._y = y;
  2174. this._z = z;
  2175. this._w = w;
  2176. this._onChangeCallback();
  2177. return this;
  2178. }
  2179. clone() {
  2180. return new this.constructor(this._x, this._y, this._z, this._w);
  2181. }
  2182. copy(quaternion) {
  2183. this._x = quaternion.x;
  2184. this._y = quaternion.y;
  2185. this._z = quaternion.z;
  2186. this._w = quaternion.w;
  2187. this._onChangeCallback();
  2188. return this;
  2189. }
  2190. setFromEuler(euler, update) {
  2191. if (!(euler && euler.isEuler)) {
  2192. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2193. }
  2194. const x = euler._x,
  2195. y = euler._y,
  2196. z = euler._z,
  2197. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2198. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2199. // content/SpinCalc.m
  2200. const cos = Math.cos;
  2201. const sin = Math.sin;
  2202. const c1 = cos(x / 2);
  2203. const c2 = cos(y / 2);
  2204. const c3 = cos(z / 2);
  2205. const s1 = sin(x / 2);
  2206. const s2 = sin(y / 2);
  2207. const s3 = sin(z / 2);
  2208. switch (order) {
  2209. case 'XYZ':
  2210. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2211. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2212. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2213. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2214. break;
  2215. case 'YXZ':
  2216. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2217. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2218. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2219. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2220. break;
  2221. case 'ZXY':
  2222. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2223. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2224. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2225. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2226. break;
  2227. case 'ZYX':
  2228. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2229. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2230. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2231. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2232. break;
  2233. case 'YZX':
  2234. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2235. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2236. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2237. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2238. break;
  2239. case 'XZY':
  2240. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2241. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2242. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2243. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2244. break;
  2245. default:
  2246. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2247. }
  2248. if (update !== false) this._onChangeCallback();
  2249. return this;
  2250. }
  2251. setFromAxisAngle(axis, angle) {
  2252. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2253. // assumes axis is normalized
  2254. const halfAngle = angle / 2,
  2255. s = Math.sin(halfAngle);
  2256. this._x = axis.x * s;
  2257. this._y = axis.y * s;
  2258. this._z = axis.z * s;
  2259. this._w = Math.cos(halfAngle);
  2260. this._onChangeCallback();
  2261. return this;
  2262. }
  2263. setFromRotationMatrix(m) {
  2264. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2265. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2266. const te = m.elements,
  2267. m11 = te[0],
  2268. m12 = te[4],
  2269. m13 = te[8],
  2270. m21 = te[1],
  2271. m22 = te[5],
  2272. m23 = te[9],
  2273. m31 = te[2],
  2274. m32 = te[6],
  2275. m33 = te[10],
  2276. trace = m11 + m22 + m33;
  2277. if (trace > 0) {
  2278. const s = 0.5 / Math.sqrt(trace + 1.0);
  2279. this._w = 0.25 / s;
  2280. this._x = (m32 - m23) * s;
  2281. this._y = (m13 - m31) * s;
  2282. this._z = (m21 - m12) * s;
  2283. } else if (m11 > m22 && m11 > m33) {
  2284. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2285. this._w = (m32 - m23) / s;
  2286. this._x = 0.25 * s;
  2287. this._y = (m12 + m21) / s;
  2288. this._z = (m13 + m31) / s;
  2289. } else if (m22 > m33) {
  2290. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2291. this._w = (m13 - m31) / s;
  2292. this._x = (m12 + m21) / s;
  2293. this._y = 0.25 * s;
  2294. this._z = (m23 + m32) / s;
  2295. } else {
  2296. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2297. this._w = (m21 - m12) / s;
  2298. this._x = (m13 + m31) / s;
  2299. this._y = (m23 + m32) / s;
  2300. this._z = 0.25 * s;
  2301. }
  2302. this._onChangeCallback();
  2303. return this;
  2304. }
  2305. setFromUnitVectors(vFrom, vTo) {
  2306. // assumes direction vectors vFrom and vTo are normalized
  2307. const EPS = 0.000001;
  2308. let r = vFrom.dot(vTo) + 1;
  2309. if (r < EPS) {
  2310. r = 0;
  2311. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2312. this._x = -vFrom.y;
  2313. this._y = vFrom.x;
  2314. this._z = 0;
  2315. this._w = r;
  2316. } else {
  2317. this._x = 0;
  2318. this._y = -vFrom.z;
  2319. this._z = vFrom.y;
  2320. this._w = r;
  2321. }
  2322. } else {
  2323. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2324. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2325. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2326. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2327. this._w = r;
  2328. }
  2329. return this.normalize();
  2330. }
  2331. angleTo(q) {
  2332. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  2333. }
  2334. rotateTowards(q, step) {
  2335. const angle = this.angleTo(q);
  2336. if (angle === 0) return this;
  2337. const t = Math.min(1, step / angle);
  2338. this.slerp(q, t);
  2339. return this;
  2340. }
  2341. identity() {
  2342. return this.set(0, 0, 0, 1);
  2343. }
  2344. invert() {
  2345. // quaternion is assumed to have unit length
  2346. return this.conjugate();
  2347. }
  2348. conjugate() {
  2349. this._x *= -1;
  2350. this._y *= -1;
  2351. this._z *= -1;
  2352. this._onChangeCallback();
  2353. return this;
  2354. }
  2355. dot(v) {
  2356. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2357. }
  2358. lengthSq() {
  2359. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2360. }
  2361. length() {
  2362. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2363. }
  2364. normalize() {
  2365. let l = this.length();
  2366. if (l === 0) {
  2367. this._x = 0;
  2368. this._y = 0;
  2369. this._z = 0;
  2370. this._w = 1;
  2371. } else {
  2372. l = 1 / l;
  2373. this._x = this._x * l;
  2374. this._y = this._y * l;
  2375. this._z = this._z * l;
  2376. this._w = this._w * l;
  2377. }
  2378. this._onChangeCallback();
  2379. return this;
  2380. }
  2381. multiply(q, p) {
  2382. if (p !== undefined) {
  2383. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2384. return this.multiplyQuaternions(q, p);
  2385. }
  2386. return this.multiplyQuaternions(this, q);
  2387. }
  2388. premultiply(q) {
  2389. return this.multiplyQuaternions(q, this);
  2390. }
  2391. multiplyQuaternions(a, b) {
  2392. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2393. const qax = a._x,
  2394. qay = a._y,
  2395. qaz = a._z,
  2396. qaw = a._w;
  2397. const qbx = b._x,
  2398. qby = b._y,
  2399. qbz = b._z,
  2400. qbw = b._w;
  2401. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2402. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2403. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2404. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2405. this._onChangeCallback();
  2406. return this;
  2407. }
  2408. slerp(qb, t) {
  2409. if (t === 0) return this;
  2410. if (t === 1) return this.copy(qb);
  2411. const x = this._x,
  2412. y = this._y,
  2413. z = this._z,
  2414. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2415. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2416. if (cosHalfTheta < 0) {
  2417. this._w = -qb._w;
  2418. this._x = -qb._x;
  2419. this._y = -qb._y;
  2420. this._z = -qb._z;
  2421. cosHalfTheta = -cosHalfTheta;
  2422. } else {
  2423. this.copy(qb);
  2424. }
  2425. if (cosHalfTheta >= 1.0) {
  2426. this._w = w;
  2427. this._x = x;
  2428. this._y = y;
  2429. this._z = z;
  2430. return this;
  2431. }
  2432. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2433. if (sqrSinHalfTheta <= Number.EPSILON) {
  2434. const s = 1 - t;
  2435. this._w = s * w + t * this._w;
  2436. this._x = s * x + t * this._x;
  2437. this._y = s * y + t * this._y;
  2438. this._z = s * z + t * this._z;
  2439. this.normalize();
  2440. this._onChangeCallback();
  2441. return this;
  2442. }
  2443. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2444. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2445. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2446. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2447. this._w = w * ratioA + this._w * ratioB;
  2448. this._x = x * ratioA + this._x * ratioB;
  2449. this._y = y * ratioA + this._y * ratioB;
  2450. this._z = z * ratioA + this._z * ratioB;
  2451. this._onChangeCallback();
  2452. return this;
  2453. }
  2454. equals(quaternion) {
  2455. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2456. }
  2457. fromArray(array, offset = 0) {
  2458. this._x = array[offset];
  2459. this._y = array[offset + 1];
  2460. this._z = array[offset + 2];
  2461. this._w = array[offset + 3];
  2462. this._onChangeCallback();
  2463. return this;
  2464. }
  2465. toArray(array = [], offset = 0) {
  2466. array[offset] = this._x;
  2467. array[offset + 1] = this._y;
  2468. array[offset + 2] = this._z;
  2469. array[offset + 3] = this._w;
  2470. return array;
  2471. }
  2472. fromBufferAttribute(attribute, index) {
  2473. this._x = attribute.getX(index);
  2474. this._y = attribute.getY(index);
  2475. this._z = attribute.getZ(index);
  2476. this._w = attribute.getW(index);
  2477. return this;
  2478. }
  2479. _onChange(callback) {
  2480. this._onChangeCallback = callback;
  2481. return this;
  2482. }
  2483. _onChangeCallback() {}
  2484. }
  2485. exports.Quaternion = Quaternion;
  2486. class Vector3 {
  2487. constructor(x = 0, y = 0, z = 0) {
  2488. Object.defineProperty(this, 'isVector3', {
  2489. value: true
  2490. });
  2491. this.x = x;
  2492. this.y = y;
  2493. this.z = z;
  2494. }
  2495. set(x, y, z) {
  2496. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2497. this.x = x;
  2498. this.y = y;
  2499. this.z = z;
  2500. return this;
  2501. }
  2502. setScalar(scalar) {
  2503. this.x = scalar;
  2504. this.y = scalar;
  2505. this.z = scalar;
  2506. return this;
  2507. }
  2508. setX(x) {
  2509. this.x = x;
  2510. return this;
  2511. }
  2512. setY(y) {
  2513. this.y = y;
  2514. return this;
  2515. }
  2516. setZ(z) {
  2517. this.z = z;
  2518. return this;
  2519. }
  2520. setComponent(index, value) {
  2521. switch (index) {
  2522. case 0:
  2523. this.x = value;
  2524. break;
  2525. case 1:
  2526. this.y = value;
  2527. break;
  2528. case 2:
  2529. this.z = value;
  2530. break;
  2531. default:
  2532. throw new Error('index is out of range: ' + index);
  2533. }
  2534. return this;
  2535. }
  2536. getComponent(index) {
  2537. switch (index) {
  2538. case 0:
  2539. return this.x;
  2540. case 1:
  2541. return this.y;
  2542. case 2:
  2543. return this.z;
  2544. default:
  2545. throw new Error('index is out of range: ' + index);
  2546. }
  2547. }
  2548. clone() {
  2549. return new this.constructor(this.x, this.y, this.z);
  2550. }
  2551. copy(v) {
  2552. this.x = v.x;
  2553. this.y = v.y;
  2554. this.z = v.z;
  2555. return this;
  2556. }
  2557. add(v, w) {
  2558. if (w !== undefined) {
  2559. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2560. return this.addVectors(v, w);
  2561. }
  2562. this.x += v.x;
  2563. this.y += v.y;
  2564. this.z += v.z;
  2565. return this;
  2566. }
  2567. addScalar(s) {
  2568. this.x += s;
  2569. this.y += s;
  2570. this.z += s;
  2571. return this;
  2572. }
  2573. addVectors(a, b) {
  2574. this.x = a.x + b.x;
  2575. this.y = a.y + b.y;
  2576. this.z = a.z + b.z;
  2577. return this;
  2578. }
  2579. addScaledVector(v, s) {
  2580. this.x += v.x * s;
  2581. this.y += v.y * s;
  2582. this.z += v.z * s;
  2583. return this;
  2584. }
  2585. sub(v, w) {
  2586. if (w !== undefined) {
  2587. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2588. return this.subVectors(v, w);
  2589. }
  2590. this.x -= v.x;
  2591. this.y -= v.y;
  2592. this.z -= v.z;
  2593. return this;
  2594. }
  2595. subScalar(s) {
  2596. this.x -= s;
  2597. this.y -= s;
  2598. this.z -= s;
  2599. return this;
  2600. }
  2601. subVectors(a, b) {
  2602. this.x = a.x - b.x;
  2603. this.y = a.y - b.y;
  2604. this.z = a.z - b.z;
  2605. return this;
  2606. }
  2607. multiply(v, w) {
  2608. if (w !== undefined) {
  2609. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2610. return this.multiplyVectors(v, w);
  2611. }
  2612. this.x *= v.x;
  2613. this.y *= v.y;
  2614. this.z *= v.z;
  2615. return this;
  2616. }
  2617. multiplyScalar(scalar) {
  2618. this.x *= scalar;
  2619. this.y *= scalar;
  2620. this.z *= scalar;
  2621. return this;
  2622. }
  2623. multiplyVectors(a, b) {
  2624. this.x = a.x * b.x;
  2625. this.y = a.y * b.y;
  2626. this.z = a.z * b.z;
  2627. return this;
  2628. }
  2629. applyEuler(euler) {
  2630. if (!(euler && euler.isEuler)) {
  2631. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2632. }
  2633. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2634. }
  2635. applyAxisAngle(axis, angle) {
  2636. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2637. }
  2638. applyMatrix3(m) {
  2639. const x = this.x,
  2640. y = this.y,
  2641. z = this.z;
  2642. const e = m.elements;
  2643. this.x = e[0] * x + e[3] * y + e[6] * z;
  2644. this.y = e[1] * x + e[4] * y + e[7] * z;
  2645. this.z = e[2] * x + e[5] * y + e[8] * z;
  2646. return this;
  2647. }
  2648. applyNormalMatrix(m) {
  2649. return this.applyMatrix3(m).normalize();
  2650. }
  2651. applyMatrix4(m) {
  2652. const x = this.x,
  2653. y = this.y,
  2654. z = this.z;
  2655. const e = m.elements;
  2656. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2657. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2658. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2659. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2660. return this;
  2661. }
  2662. applyQuaternion(q) {
  2663. const x = this.x,
  2664. y = this.y,
  2665. z = this.z;
  2666. const qx = q.x,
  2667. qy = q.y,
  2668. qz = q.z,
  2669. qw = q.w; // calculate quat * vector
  2670. const ix = qw * x + qy * z - qz * y;
  2671. const iy = qw * y + qz * x - qx * z;
  2672. const iz = qw * z + qx * y - qy * x;
  2673. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2674. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2675. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2676. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2677. return this;
  2678. }
  2679. project(camera) {
  2680. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2681. }
  2682. unproject(camera) {
  2683. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2684. }
  2685. transformDirection(m) {
  2686. // input: THREE.Matrix4 affine matrix
  2687. // vector interpreted as a direction
  2688. const x = this.x,
  2689. y = this.y,
  2690. z = this.z;
  2691. const e = m.elements;
  2692. this.x = e[0] * x + e[4] * y + e[8] * z;
  2693. this.y = e[1] * x + e[5] * y + e[9] * z;
  2694. this.z = e[2] * x + e[6] * y + e[10] * z;
  2695. return this.normalize();
  2696. }
  2697. divide(v) {
  2698. this.x /= v.x;
  2699. this.y /= v.y;
  2700. this.z /= v.z;
  2701. return this;
  2702. }
  2703. divideScalar(scalar) {
  2704. return this.multiplyScalar(1 / scalar);
  2705. }
  2706. min(v) {
  2707. this.x = Math.min(this.x, v.x);
  2708. this.y = Math.min(this.y, v.y);
  2709. this.z = Math.min(this.z, v.z);
  2710. return this;
  2711. }
  2712. max(v) {
  2713. this.x = Math.max(this.x, v.x);
  2714. this.y = Math.max(this.y, v.y);
  2715. this.z = Math.max(this.z, v.z);
  2716. return this;
  2717. }
  2718. clamp(min, max) {
  2719. // assumes min < max, componentwise
  2720. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2721. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2722. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2723. return this;
  2724. }
  2725. clampScalar(minVal, maxVal) {
  2726. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2727. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2728. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2729. return this;
  2730. }
  2731. clampLength(min, max) {
  2732. const length = this.length();
  2733. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2734. }
  2735. floor() {
  2736. this.x = Math.floor(this.x);
  2737. this.y = Math.floor(this.y);
  2738. this.z = Math.floor(this.z);
  2739. return this;
  2740. }
  2741. ceil() {
  2742. this.x = Math.ceil(this.x);
  2743. this.y = Math.ceil(this.y);
  2744. this.z = Math.ceil(this.z);
  2745. return this;
  2746. }
  2747. round() {
  2748. this.x = Math.round(this.x);
  2749. this.y = Math.round(this.y);
  2750. this.z = Math.round(this.z);
  2751. return this;
  2752. }
  2753. roundToZero() {
  2754. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2755. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2756. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2757. return this;
  2758. }
  2759. negate() {
  2760. this.x = -this.x;
  2761. this.y = -this.y;
  2762. this.z = -this.z;
  2763. return this;
  2764. }
  2765. dot(v) {
  2766. return this.x * v.x + this.y * v.y + this.z * v.z;
  2767. } // TODO lengthSquared?
  2768. lengthSq() {
  2769. return this.x * this.x + this.y * this.y + this.z * this.z;
  2770. }
  2771. length() {
  2772. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2773. }
  2774. manhattanLength() {
  2775. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2776. }
  2777. normalize() {
  2778. return this.divideScalar(this.length() || 1);
  2779. }
  2780. setLength(length) {
  2781. return this.normalize().multiplyScalar(length);
  2782. }
  2783. lerp(v, alpha) {
  2784. this.x += (v.x - this.x) * alpha;
  2785. this.y += (v.y - this.y) * alpha;
  2786. this.z += (v.z - this.z) * alpha;
  2787. return this;
  2788. }
  2789. lerpVectors(v1, v2, alpha) {
  2790. this.x = v1.x + (v2.x - v1.x) * alpha;
  2791. this.y = v1.y + (v2.y - v1.y) * alpha;
  2792. this.z = v1.z + (v2.z - v1.z) * alpha;
  2793. return this;
  2794. }
  2795. cross(v, w) {
  2796. if (w !== undefined) {
  2797. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2798. return this.crossVectors(v, w);
  2799. }
  2800. return this.crossVectors(this, v);
  2801. }
  2802. crossVectors(a, b) {
  2803. const ax = a.x,
  2804. ay = a.y,
  2805. az = a.z;
  2806. const bx = b.x,
  2807. by = b.y,
  2808. bz = b.z;
  2809. this.x = ay * bz - az * by;
  2810. this.y = az * bx - ax * bz;
  2811. this.z = ax * by - ay * bx;
  2812. return this;
  2813. }
  2814. projectOnVector(v) {
  2815. const denominator = v.lengthSq();
  2816. if (denominator === 0) return this.set(0, 0, 0);
  2817. const scalar = v.dot(this) / denominator;
  2818. return this.copy(v).multiplyScalar(scalar);
  2819. }
  2820. projectOnPlane(planeNormal) {
  2821. _vector.copy(this).projectOnVector(planeNormal);
  2822. return this.sub(_vector);
  2823. }
  2824. reflect(normal) {
  2825. // reflect incident vector off plane orthogonal to normal
  2826. // normal is assumed to have unit length
  2827. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2828. }
  2829. angleTo(v) {
  2830. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2831. if (denominator === 0) return Math.PI / 2;
  2832. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2833. return Math.acos(MathUtils.clamp(theta, -1, 1));
  2834. }
  2835. distanceTo(v) {
  2836. return Math.sqrt(this.distanceToSquared(v));
  2837. }
  2838. distanceToSquared(v) {
  2839. const dx = this.x - v.x,
  2840. dy = this.y - v.y,
  2841. dz = this.z - v.z;
  2842. return dx * dx + dy * dy + dz * dz;
  2843. }
  2844. manhattanDistanceTo(v) {
  2845. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2846. }
  2847. setFromSpherical(s) {
  2848. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2849. }
  2850. setFromSphericalCoords(radius, phi, theta) {
  2851. const sinPhiRadius = Math.sin(phi) * radius;
  2852. this.x = sinPhiRadius * Math.sin(theta);
  2853. this.y = Math.cos(phi) * radius;
  2854. this.z = sinPhiRadius * Math.cos(theta);
  2855. return this;
  2856. }
  2857. setFromCylindrical(c) {
  2858. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2859. }
  2860. setFromCylindricalCoords(radius, theta, y) {
  2861. this.x = radius * Math.sin(theta);
  2862. this.y = y;
  2863. this.z = radius * Math.cos(theta);
  2864. return this;
  2865. }
  2866. setFromMatrixPosition(m) {
  2867. const e = m.elements;
  2868. this.x = e[12];
  2869. this.y = e[13];
  2870. this.z = e[14];
  2871. return this;
  2872. }
  2873. setFromMatrixScale(m) {
  2874. const sx = this.setFromMatrixColumn(m, 0).length();
  2875. const sy = this.setFromMatrixColumn(m, 1).length();
  2876. const sz = this.setFromMatrixColumn(m, 2).length();
  2877. this.x = sx;
  2878. this.y = sy;
  2879. this.z = sz;
  2880. return this;
  2881. }
  2882. setFromMatrixColumn(m, index) {
  2883. return this.fromArray(m.elements, index * 4);
  2884. }
  2885. setFromMatrix3Column(m, index) {
  2886. return this.fromArray(m.elements, index * 3);
  2887. }
  2888. equals(v) {
  2889. return v.x === this.x && v.y === this.y && v.z === this.z;
  2890. }
  2891. fromArray(array, offset = 0) {
  2892. this.x = array[offset];
  2893. this.y = array[offset + 1];
  2894. this.z = array[offset + 2];
  2895. return this;
  2896. }
  2897. toArray(array = [], offset = 0) {
  2898. array[offset] = this.x;
  2899. array[offset + 1] = this.y;
  2900. array[offset + 2] = this.z;
  2901. return array;
  2902. }
  2903. fromBufferAttribute(attribute, index, offset) {
  2904. if (offset !== undefined) {
  2905. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2906. }
  2907. this.x = attribute.getX(index);
  2908. this.y = attribute.getY(index);
  2909. this.z = attribute.getZ(index);
  2910. return this;
  2911. }
  2912. random() {
  2913. this.x = Math.random();
  2914. this.y = Math.random();
  2915. this.z = Math.random();
  2916. return this;
  2917. }
  2918. }
  2919. exports.Vector3 = Vector3;
  2920. const _vector =
  2921. /*@__PURE__*/
  2922. new Vector3();
  2923. const _quaternion =
  2924. /*@__PURE__*/
  2925. new Quaternion();
  2926. class Box3 {
  2927. constructor(min, max) {
  2928. Object.defineProperty(this, 'isBox3', {
  2929. value: true
  2930. });
  2931. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  2932. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  2933. }
  2934. set(min, max) {
  2935. this.min.copy(min);
  2936. this.max.copy(max);
  2937. return this;
  2938. }
  2939. setFromArray(array) {
  2940. let minX = +Infinity;
  2941. let minY = +Infinity;
  2942. let minZ = +Infinity;
  2943. let maxX = -Infinity;
  2944. let maxY = -Infinity;
  2945. let maxZ = -Infinity;
  2946. for (let i = 0, l = array.length; i < l; i += 3) {
  2947. const x = array[i];
  2948. const y = array[i + 1];
  2949. const z = array[i + 2];
  2950. if (x < minX) minX = x;
  2951. if (y < minY) minY = y;
  2952. if (z < minZ) minZ = z;
  2953. if (x > maxX) maxX = x;
  2954. if (y > maxY) maxY = y;
  2955. if (z > maxZ) maxZ = z;
  2956. }
  2957. this.min.set(minX, minY, minZ);
  2958. this.max.set(maxX, maxY, maxZ);
  2959. return this;
  2960. }
  2961. setFromBufferAttribute(attribute) {
  2962. let minX = +Infinity;
  2963. let minY = +Infinity;
  2964. let minZ = +Infinity;
  2965. let maxX = -Infinity;
  2966. let maxY = -Infinity;
  2967. let maxZ = -Infinity;
  2968. for (let i = 0, l = attribute.count; i < l; i++) {
  2969. const x = attribute.getX(i);
  2970. const y = attribute.getY(i);
  2971. const z = attribute.getZ(i);
  2972. if (x < minX) minX = x;
  2973. if (y < minY) minY = y;
  2974. if (z < minZ) minZ = z;
  2975. if (x > maxX) maxX = x;
  2976. if (y > maxY) maxY = y;
  2977. if (z > maxZ) maxZ = z;
  2978. }
  2979. this.min.set(minX, minY, minZ);
  2980. this.max.set(maxX, maxY, maxZ);
  2981. return this;
  2982. }
  2983. setFromPoints(points) {
  2984. this.makeEmpty();
  2985. for (let i = 0, il = points.length; i < il; i++) {
  2986. this.expandByPoint(points[i]);
  2987. }
  2988. return this;
  2989. }
  2990. setFromCenterAndSize(center, size) {
  2991. const halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  2992. this.min.copy(center).sub(halfSize);
  2993. this.max.copy(center).add(halfSize);
  2994. return this;
  2995. }
  2996. setFromObject(object) {
  2997. this.makeEmpty();
  2998. return this.expandByObject(object);
  2999. }
  3000. clone() {
  3001. return new this.constructor().copy(this);
  3002. }
  3003. copy(box) {
  3004. this.min.copy(box.min);
  3005. this.max.copy(box.max);
  3006. return this;
  3007. }
  3008. makeEmpty() {
  3009. this.min.x = this.min.y = this.min.z = +Infinity;
  3010. this.max.x = this.max.y = this.max.z = -Infinity;
  3011. return this;
  3012. }
  3013. isEmpty() {
  3014. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3015. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3016. }
  3017. getCenter(target) {
  3018. if (target === undefined) {
  3019. console.warn('THREE.Box3: .getCenter() target is now required');
  3020. target = new Vector3();
  3021. }
  3022. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3023. }
  3024. getSize(target) {
  3025. if (target === undefined) {
  3026. console.warn('THREE.Box3: .getSize() target is now required');
  3027. target = new Vector3();
  3028. }
  3029. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3030. }
  3031. expandByPoint(point) {
  3032. this.min.min(point);
  3033. this.max.max(point);
  3034. return this;
  3035. }
  3036. expandByVector(vector) {
  3037. this.min.sub(vector);
  3038. this.max.add(vector);
  3039. return this;
  3040. }
  3041. expandByScalar(scalar) {
  3042. this.min.addScalar(-scalar);
  3043. this.max.addScalar(scalar);
  3044. return this;
  3045. }
  3046. expandByObject(object) {
  3047. // Computes the world-axis-aligned bounding box of an object (including its children),
  3048. // accounting for both the object's, and children's, world transforms
  3049. object.updateWorldMatrix(false, false);
  3050. const geometry = object.geometry;
  3051. if (geometry !== undefined) {
  3052. if (geometry.boundingBox === null) {
  3053. geometry.computeBoundingBox();
  3054. }
  3055. _box.copy(geometry.boundingBox);
  3056. _box.applyMatrix4(object.matrixWorld);
  3057. this.union(_box);
  3058. }
  3059. const children = object.children;
  3060. for (let i = 0, l = children.length; i < l; i++) {
  3061. this.expandByObject(children[i]);
  3062. }
  3063. return this;
  3064. }
  3065. containsPoint(point) {
  3066. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  3067. }
  3068. containsBox(box) {
  3069. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  3070. }
  3071. getParameter(point, target) {
  3072. // This can potentially have a divide by zero if the box
  3073. // has a size dimension of 0.
  3074. if (target === undefined) {
  3075. console.warn('THREE.Box3: .getParameter() target is now required');
  3076. target = new Vector3();
  3077. }
  3078. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  3079. }
  3080. intersectsBox(box) {
  3081. // using 6 splitting planes to rule out intersections.
  3082. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3083. }
  3084. intersectsSphere(sphere) {
  3085. // Find the point on the AABB closest to the sphere center.
  3086. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  3087. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3088. }
  3089. intersectsPlane(plane) {
  3090. // We compute the minimum and maximum dot product values. If those values
  3091. // are on the same side (back or front) of the plane, then there is no intersection.
  3092. let min, max;
  3093. if (plane.normal.x > 0) {
  3094. min = plane.normal.x * this.min.x;
  3095. max = plane.normal.x * this.max.x;
  3096. } else {
  3097. min = plane.normal.x * this.max.x;
  3098. max = plane.normal.x * this.min.x;
  3099. }
  3100. if (plane.normal.y > 0) {
  3101. min += plane.normal.y * this.min.y;
  3102. max += plane.normal.y * this.max.y;
  3103. } else {
  3104. min += plane.normal.y * this.max.y;
  3105. max += plane.normal.y * this.min.y;
  3106. }
  3107. if (plane.normal.z > 0) {
  3108. min += plane.normal.z * this.min.z;
  3109. max += plane.normal.z * this.max.z;
  3110. } else {
  3111. min += plane.normal.z * this.max.z;
  3112. max += plane.normal.z * this.min.z;
  3113. }
  3114. return min <= -plane.constant && max >= -plane.constant;
  3115. }
  3116. intersectsTriangle(triangle) {
  3117. if (this.isEmpty()) {
  3118. return false;
  3119. } // compute box center and extents
  3120. this.getCenter(_center);
  3121. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3122. _v0.subVectors(triangle.a, _center);
  3123. _v1.subVectors(triangle.b, _center);
  3124. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3125. _f0.subVectors(_v1, _v0);
  3126. _f1.subVectors(_v2, _v1);
  3127. _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3128. // 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
  3129. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3130. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  3131. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  3132. return false;
  3133. } // test 3 face normals from the aabb
  3134. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3135. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  3136. return false;
  3137. } // finally testing the face normal of the triangle
  3138. // use already existing triangle edge vectors here
  3139. _triangleNormal.crossVectors(_f0, _f1);
  3140. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3141. return satForAxes(axes, _v0, _v1, _v2, _extents);
  3142. }
  3143. clampPoint(point, target) {
  3144. if (target === undefined) {
  3145. console.warn('THREE.Box3: .clampPoint() target is now required');
  3146. target = new Vector3();
  3147. }
  3148. return target.copy(point).clamp(this.min, this.max);
  3149. }
  3150. distanceToPoint(point) {
  3151. const clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  3152. return clampedPoint.sub(point).length();
  3153. }
  3154. getBoundingSphere(target) {
  3155. if (target === undefined) {
  3156. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  3157. }
  3158. this.getCenter(target.center);
  3159. target.radius = this.getSize(_vector$1).length() * 0.5;
  3160. return target;
  3161. }
  3162. intersect(box) {
  3163. this.min.max(box.min);
  3164. this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  3165. if (this.isEmpty()) this.makeEmpty();
  3166. return this;
  3167. }
  3168. union(box) {
  3169. this.min.min(box.min);
  3170. this.max.max(box.max);
  3171. return this;
  3172. }
  3173. applyMatrix4(matrix) {
  3174. // transform of empty box is an empty box.
  3175. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3176. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3177. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3178. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3179. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3180. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3181. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3182. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3183. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3184. this.setFromPoints(_points);
  3185. return this;
  3186. }
  3187. translate(offset) {
  3188. this.min.add(offset);
  3189. this.max.add(offset);
  3190. return this;
  3191. }
  3192. equals(box) {
  3193. return box.min.equals(this.min) && box.max.equals(this.max);
  3194. }
  3195. }
  3196. exports.Box3 = Box3;
  3197. function satForAxes(axes, v0, v1, v2, extents) {
  3198. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3199. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  3200. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  3201. const p0 = v0.dot(_testAxis);
  3202. const p1 = v1.dot(_testAxis);
  3203. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3204. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3205. // points of the projected triangle are outside the projected half-length of the aabb
  3206. // the axis is seperating and we can exit
  3207. return false;
  3208. }
  3209. }
  3210. return true;
  3211. }
  3212. const _points = [
  3213. /*@__PURE__*/
  3214. new Vector3(),
  3215. /*@__PURE__*/
  3216. new Vector3(),
  3217. /*@__PURE__*/
  3218. new Vector3(),
  3219. /*@__PURE__*/
  3220. new Vector3(),
  3221. /*@__PURE__*/
  3222. new Vector3(),
  3223. /*@__PURE__*/
  3224. new Vector3(),
  3225. /*@__PURE__*/
  3226. new Vector3(),
  3227. /*@__PURE__*/
  3228. new Vector3()];
  3229. const _vector$1 =
  3230. /*@__PURE__*/
  3231. new Vector3();
  3232. const _box =
  3233. /*@__PURE__*/
  3234. new Box3(); // triangle centered vertices
  3235. const _v0 =
  3236. /*@__PURE__*/
  3237. new Vector3();
  3238. const _v1 =
  3239. /*@__PURE__*/
  3240. new Vector3();
  3241. const _v2 =
  3242. /*@__PURE__*/
  3243. new Vector3(); // triangle edge vectors
  3244. const _f0 =
  3245. /*@__PURE__*/
  3246. new Vector3();
  3247. const _f1 =
  3248. /*@__PURE__*/
  3249. new Vector3();
  3250. const _f2 =
  3251. /*@__PURE__*/
  3252. new Vector3();
  3253. const _center =
  3254. /*@__PURE__*/
  3255. new Vector3();
  3256. const _extents =
  3257. /*@__PURE__*/
  3258. new Vector3();
  3259. const _triangleNormal =
  3260. /*@__PURE__*/
  3261. new Vector3();
  3262. const _testAxis =
  3263. /*@__PURE__*/
  3264. new Vector3();
  3265. const _box$1 =
  3266. /*@__PURE__*/
  3267. new Box3();
  3268. class Sphere {
  3269. constructor(center, radius) {
  3270. this.center = center !== undefined ? center : new Vector3();
  3271. this.radius = radius !== undefined ? radius : -1;
  3272. }
  3273. set(center, radius) {
  3274. this.center.copy(center);
  3275. this.radius = radius;
  3276. return this;
  3277. }
  3278. setFromPoints(points, optionalCenter) {
  3279. const center = this.center;
  3280. if (optionalCenter !== undefined) {
  3281. center.copy(optionalCenter);
  3282. } else {
  3283. _box$1.setFromPoints(points).getCenter(center);
  3284. }
  3285. let maxRadiusSq = 0;
  3286. for (let i = 0, il = points.length; i < il; i++) {
  3287. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3288. }
  3289. this.radius = Math.sqrt(maxRadiusSq);
  3290. return this;
  3291. }
  3292. clone() {
  3293. return new this.constructor().copy(this);
  3294. }
  3295. copy(sphere) {
  3296. this.center.copy(sphere.center);
  3297. this.radius = sphere.radius;
  3298. return this;
  3299. }
  3300. isEmpty() {
  3301. return this.radius < 0;
  3302. }
  3303. makeEmpty() {
  3304. this.center.set(0, 0, 0);
  3305. this.radius = -1;
  3306. return this;
  3307. }
  3308. containsPoint(point) {
  3309. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3310. }
  3311. distanceToPoint(point) {
  3312. return point.distanceTo(this.center) - this.radius;
  3313. }
  3314. intersectsSphere(sphere) {
  3315. const radiusSum = this.radius + sphere.radius;
  3316. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3317. }
  3318. intersectsBox(box) {
  3319. return box.intersectsSphere(this);
  3320. }
  3321. intersectsPlane(plane) {
  3322. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3323. }
  3324. clampPoint(point, target) {
  3325. const deltaLengthSq = this.center.distanceToSquared(point);
  3326. if (target === undefined) {
  3327. console.warn('THREE.Sphere: .clampPoint() target is now required');
  3328. target = new Vector3();
  3329. }
  3330. target.copy(point);
  3331. if (deltaLengthSq > this.radius * this.radius) {
  3332. target.sub(this.center).normalize();
  3333. target.multiplyScalar(this.radius).add(this.center);
  3334. }
  3335. return target;
  3336. }
  3337. getBoundingBox(target) {
  3338. if (target === undefined) {
  3339. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  3340. target = new Box3();
  3341. }
  3342. if (this.isEmpty()) {
  3343. // Empty sphere produces empty bounding box
  3344. target.makeEmpty();
  3345. return target;
  3346. }
  3347. target.set(this.center, this.center);
  3348. target.expandByScalar(this.radius);
  3349. return target;
  3350. }
  3351. applyMatrix4(matrix) {
  3352. this.center.applyMatrix4(matrix);
  3353. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3354. return this;
  3355. }
  3356. translate(offset) {
  3357. this.center.add(offset);
  3358. return this;
  3359. }
  3360. equals(sphere) {
  3361. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3362. }
  3363. }
  3364. exports.Sphere = Sphere;
  3365. const _vector$2 =
  3366. /*@__PURE__*/
  3367. new Vector3();
  3368. const _segCenter =
  3369. /*@__PURE__*/
  3370. new Vector3();
  3371. const _segDir =
  3372. /*@__PURE__*/
  3373. new Vector3();
  3374. const _diff =
  3375. /*@__PURE__*/
  3376. new Vector3();
  3377. const _edge1 =
  3378. /*@__PURE__*/
  3379. new Vector3();
  3380. const _edge2 =
  3381. /*@__PURE__*/
  3382. new Vector3();
  3383. const _normal =
  3384. /*@__PURE__*/
  3385. new Vector3();
  3386. class Ray {
  3387. constructor(origin, direction) {
  3388. this.origin = origin !== undefined ? origin : new Vector3();
  3389. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  3390. }
  3391. set(origin, direction) {
  3392. this.origin.copy(origin);
  3393. this.direction.copy(direction);
  3394. return this;
  3395. }
  3396. clone() {
  3397. return new this.constructor().copy(this);
  3398. }
  3399. copy(ray) {
  3400. this.origin.copy(ray.origin);
  3401. this.direction.copy(ray.direction);
  3402. return this;
  3403. }
  3404. at(t, target) {
  3405. if (target === undefined) {
  3406. console.warn('THREE.Ray: .at() target is now required');
  3407. target = new Vector3();
  3408. }
  3409. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3410. }
  3411. lookAt(v) {
  3412. this.direction.copy(v).sub(this.origin).normalize();
  3413. return this;
  3414. }
  3415. recast(t) {
  3416. this.origin.copy(this.at(t, _vector$2));
  3417. return this;
  3418. }
  3419. closestPointToPoint(point, target) {
  3420. if (target === undefined) {
  3421. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3422. target = new Vector3();
  3423. }
  3424. target.subVectors(point, this.origin);
  3425. const directionDistance = target.dot(this.direction);
  3426. if (directionDistance < 0) {
  3427. return target.copy(this.origin);
  3428. }
  3429. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3430. }
  3431. distanceToPoint(point) {
  3432. return Math.sqrt(this.distanceSqToPoint(point));
  3433. }
  3434. distanceSqToPoint(point) {
  3435. const directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3436. if (directionDistance < 0) {
  3437. return this.origin.distanceToSquared(point);
  3438. }
  3439. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3440. return _vector$2.distanceToSquared(point);
  3441. }
  3442. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3443. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3444. // It returns the min distance between the ray and the segment
  3445. // defined by v0 and v1
  3446. // It can also set two optional targets :
  3447. // - The closest point on the ray
  3448. // - The closest point on the segment
  3449. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3450. _segDir.copy(v1).sub(v0).normalize();
  3451. _diff.copy(this.origin).sub(_segCenter);
  3452. const segExtent = v0.distanceTo(v1) * 0.5;
  3453. const a01 = -this.direction.dot(_segDir);
  3454. const b0 = _diff.dot(this.direction);
  3455. const b1 = -_diff.dot(_segDir);
  3456. const c = _diff.lengthSq();
  3457. const det = Math.abs(1 - a01 * a01);
  3458. let s0, s1, sqrDist, extDet;
  3459. if (det > 0) {
  3460. // The ray and segment are not parallel.
  3461. s0 = a01 * b1 - b0;
  3462. s1 = a01 * b0 - b1;
  3463. extDet = segExtent * det;
  3464. if (s0 >= 0) {
  3465. if (s1 >= -extDet) {
  3466. if (s1 <= extDet) {
  3467. // region 0
  3468. // Minimum at interior points of ray and segment.
  3469. const invDet = 1 / det;
  3470. s0 *= invDet;
  3471. s1 *= invDet;
  3472. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3473. } else {
  3474. // region 1
  3475. s1 = segExtent;
  3476. s0 = Math.max(0, -(a01 * s1 + b0));
  3477. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3478. }
  3479. } else {
  3480. // region 5
  3481. s1 = -segExtent;
  3482. s0 = Math.max(0, -(a01 * s1 + b0));
  3483. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3484. }
  3485. } else {
  3486. if (s1 <= -extDet) {
  3487. // region 4
  3488. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3489. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3490. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3491. } else if (s1 <= extDet) {
  3492. // region 3
  3493. s0 = 0;
  3494. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3495. sqrDist = s1 * (s1 + 2 * b1) + c;
  3496. } else {
  3497. // region 2
  3498. s0 = Math.max(0, -(a01 * segExtent + b0));
  3499. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3500. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3501. }
  3502. }
  3503. } else {
  3504. // Ray and segment are parallel.
  3505. s1 = a01 > 0 ? -segExtent : segExtent;
  3506. s0 = Math.max(0, -(a01 * s1 + b0));
  3507. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3508. }
  3509. if (optionalPointOnRay) {
  3510. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3511. }
  3512. if (optionalPointOnSegment) {
  3513. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3514. }
  3515. return sqrDist;
  3516. }
  3517. intersectSphere(sphere, target) {
  3518. _vector$2.subVectors(sphere.center, this.origin);
  3519. const tca = _vector$2.dot(this.direction);
  3520. const d2 = _vector$2.dot(_vector$2) - tca * tca;
  3521. const radius2 = sphere.radius * sphere.radius;
  3522. if (d2 > radius2) return null;
  3523. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3524. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3525. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3526. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3527. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3528. // in order to always return an intersect point that is in front of the ray.
  3529. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3530. return this.at(t0, target);
  3531. }
  3532. intersectsSphere(sphere) {
  3533. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3534. }
  3535. distanceToPlane(plane) {
  3536. const denominator = plane.normal.dot(this.direction);
  3537. if (denominator === 0) {
  3538. // line is coplanar, return origin
  3539. if (plane.distanceToPoint(this.origin) === 0) {
  3540. return 0;
  3541. } // Null is preferable to undefined since undefined means.... it is undefined
  3542. return null;
  3543. }
  3544. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3545. return t >= 0 ? t : null;
  3546. }
  3547. intersectPlane(plane, target) {
  3548. const t = this.distanceToPlane(plane);
  3549. if (t === null) {
  3550. return null;
  3551. }
  3552. return this.at(t, target);
  3553. }
  3554. intersectsPlane(plane) {
  3555. // check if the ray lies on the plane first
  3556. const distToPoint = plane.distanceToPoint(this.origin);
  3557. if (distToPoint === 0) {
  3558. return true;
  3559. }
  3560. const denominator = plane.normal.dot(this.direction);
  3561. if (denominator * distToPoint < 0) {
  3562. return true;
  3563. } // ray origin is behind the plane (and is pointing behind it)
  3564. return false;
  3565. }
  3566. intersectBox(box, target) {
  3567. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3568. const invdirx = 1 / this.direction.x,
  3569. invdiry = 1 / this.direction.y,
  3570. invdirz = 1 / this.direction.z;
  3571. const origin = this.origin;
  3572. if (invdirx >= 0) {
  3573. tmin = (box.min.x - origin.x) * invdirx;
  3574. tmax = (box.max.x - origin.x) * invdirx;
  3575. } else {
  3576. tmin = (box.max.x - origin.x) * invdirx;
  3577. tmax = (box.min.x - origin.x) * invdirx;
  3578. }
  3579. if (invdiry >= 0) {
  3580. tymin = (box.min.y - origin.y) * invdiry;
  3581. tymax = (box.max.y - origin.y) * invdiry;
  3582. } else {
  3583. tymin = (box.max.y - origin.y) * invdiry;
  3584. tymax = (box.min.y - origin.y) * invdiry;
  3585. }
  3586. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3587. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3588. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3589. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3590. if (invdirz >= 0) {
  3591. tzmin = (box.min.z - origin.z) * invdirz;
  3592. tzmax = (box.max.z - origin.z) * invdirz;
  3593. } else {
  3594. tzmin = (box.max.z - origin.z) * invdirz;
  3595. tzmax = (box.min.z - origin.z) * invdirz;
  3596. }
  3597. if (tmin > tzmax || tzmin > tmax) return null;
  3598. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3599. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3600. if (tmax < 0) return null;
  3601. return this.at(tmin >= 0 ? tmin : tmax, target);
  3602. }
  3603. intersectsBox(box) {
  3604. return this.intersectBox(box, _vector$2) !== null;
  3605. }
  3606. intersectTriangle(a, b, c, backfaceCulling, target) {
  3607. // Compute the offset origin, edges, and normal.
  3608. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3609. _edge1.subVectors(b, a);
  3610. _edge2.subVectors(c, a);
  3611. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3612. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3613. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3614. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3615. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3616. let DdN = this.direction.dot(_normal);
  3617. let sign;
  3618. if (DdN > 0) {
  3619. if (backfaceCulling) return null;
  3620. sign = 1;
  3621. } else if (DdN < 0) {
  3622. sign = -1;
  3623. DdN = -DdN;
  3624. } else {
  3625. return null;
  3626. }
  3627. _diff.subVectors(this.origin, a);
  3628. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3629. if (DdQxE2 < 0) {
  3630. return null;
  3631. }
  3632. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3633. if (DdE1xQ < 0) {
  3634. return null;
  3635. } // b1+b2 > 1, no intersection
  3636. if (DdQxE2 + DdE1xQ > DdN) {
  3637. return null;
  3638. } // Line intersects triangle, check if ray does.
  3639. const QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  3640. if (QdN < 0) {
  3641. return null;
  3642. } // Ray intersects triangle.
  3643. return this.at(QdN / DdN, target);
  3644. }
  3645. applyMatrix4(matrix4) {
  3646. this.origin.applyMatrix4(matrix4);
  3647. this.direction.transformDirection(matrix4);
  3648. return this;
  3649. }
  3650. equals(ray) {
  3651. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3652. }
  3653. }
  3654. exports.Ray = Ray;
  3655. class Matrix4 {
  3656. constructor() {
  3657. Object.defineProperty(this, 'isMatrix4', {
  3658. value: true
  3659. });
  3660. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3661. if (arguments.length > 0) {
  3662. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3663. }
  3664. }
  3665. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3666. const te = this.elements;
  3667. te[0] = n11;
  3668. te[4] = n12;
  3669. te[8] = n13;
  3670. te[12] = n14;
  3671. te[1] = n21;
  3672. te[5] = n22;
  3673. te[9] = n23;
  3674. te[13] = n24;
  3675. te[2] = n31;
  3676. te[6] = n32;
  3677. te[10] = n33;
  3678. te[14] = n34;
  3679. te[3] = n41;
  3680. te[7] = n42;
  3681. te[11] = n43;
  3682. te[15] = n44;
  3683. return this;
  3684. }
  3685. identity() {
  3686. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3687. return this;
  3688. }
  3689. clone() {
  3690. return new Matrix4().fromArray(this.elements);
  3691. }
  3692. copy(m) {
  3693. const te = this.elements;
  3694. const me = m.elements;
  3695. te[0] = me[0];
  3696. te[1] = me[1];
  3697. te[2] = me[2];
  3698. te[3] = me[3];
  3699. te[4] = me[4];
  3700. te[5] = me[5];
  3701. te[6] = me[6];
  3702. te[7] = me[7];
  3703. te[8] = me[8];
  3704. te[9] = me[9];
  3705. te[10] = me[10];
  3706. te[11] = me[11];
  3707. te[12] = me[12];
  3708. te[13] = me[13];
  3709. te[14] = me[14];
  3710. te[15] = me[15];
  3711. return this;
  3712. }
  3713. copyPosition(m) {
  3714. const te = this.elements,
  3715. me = m.elements;
  3716. te[12] = me[12];
  3717. te[13] = me[13];
  3718. te[14] = me[14];
  3719. return this;
  3720. }
  3721. extractBasis(xAxis, yAxis, zAxis) {
  3722. xAxis.setFromMatrixColumn(this, 0);
  3723. yAxis.setFromMatrixColumn(this, 1);
  3724. zAxis.setFromMatrixColumn(this, 2);
  3725. return this;
  3726. }
  3727. makeBasis(xAxis, yAxis, zAxis) {
  3728. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  3729. return this;
  3730. }
  3731. extractRotation(m) {
  3732. // this method does not support reflection matrices
  3733. const te = this.elements;
  3734. const me = m.elements;
  3735. const scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
  3736. const scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
  3737. const scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
  3738. te[0] = me[0] * scaleX;
  3739. te[1] = me[1] * scaleX;
  3740. te[2] = me[2] * scaleX;
  3741. te[3] = 0;
  3742. te[4] = me[4] * scaleY;
  3743. te[5] = me[5] * scaleY;
  3744. te[6] = me[6] * scaleY;
  3745. te[7] = 0;
  3746. te[8] = me[8] * scaleZ;
  3747. te[9] = me[9] * scaleZ;
  3748. te[10] = me[10] * scaleZ;
  3749. te[11] = 0;
  3750. te[12] = 0;
  3751. te[13] = 0;
  3752. te[14] = 0;
  3753. te[15] = 1;
  3754. return this;
  3755. }
  3756. makeRotationFromEuler(euler) {
  3757. if (!(euler && euler.isEuler)) {
  3758. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3759. }
  3760. const te = this.elements;
  3761. const x = euler.x,
  3762. y = euler.y,
  3763. z = euler.z;
  3764. const a = Math.cos(x),
  3765. b = Math.sin(x);
  3766. const c = Math.cos(y),
  3767. d = Math.sin(y);
  3768. const e = Math.cos(z),
  3769. f = Math.sin(z);
  3770. if (euler.order === 'XYZ') {
  3771. const ae = a * e,
  3772. af = a * f,
  3773. be = b * e,
  3774. bf = b * f;
  3775. te[0] = c * e;
  3776. te[4] = -c * f;
  3777. te[8] = d;
  3778. te[1] = af + be * d;
  3779. te[5] = ae - bf * d;
  3780. te[9] = -b * c;
  3781. te[2] = bf - ae * d;
  3782. te[6] = be + af * d;
  3783. te[10] = a * c;
  3784. } else if (euler.order === 'YXZ') {
  3785. const ce = c * e,
  3786. cf = c * f,
  3787. de = d * e,
  3788. df = d * f;
  3789. te[0] = ce + df * b;
  3790. te[4] = de * b - cf;
  3791. te[8] = a * d;
  3792. te[1] = a * f;
  3793. te[5] = a * e;
  3794. te[9] = -b;
  3795. te[2] = cf * b - de;
  3796. te[6] = df + ce * b;
  3797. te[10] = a * c;
  3798. } else if (euler.order === 'ZXY') {
  3799. const ce = c * e,
  3800. cf = c * f,
  3801. de = d * e,
  3802. df = d * f;
  3803. te[0] = ce - df * b;
  3804. te[4] = -a * f;
  3805. te[8] = de + cf * b;
  3806. te[1] = cf + de * b;
  3807. te[5] = a * e;
  3808. te[9] = df - ce * b;
  3809. te[2] = -a * d;
  3810. te[6] = b;
  3811. te[10] = a * c;
  3812. } else if (euler.order === 'ZYX') {
  3813. const ae = a * e,
  3814. af = a * f,
  3815. be = b * e,
  3816. bf = b * f;
  3817. te[0] = c * e;
  3818. te[4] = be * d - af;
  3819. te[8] = ae * d + bf;
  3820. te[1] = c * f;
  3821. te[5] = bf * d + ae;
  3822. te[9] = af * d - be;
  3823. te[2] = -d;
  3824. te[6] = b * c;
  3825. te[10] = a * c;
  3826. } else if (euler.order === 'YZX') {
  3827. const ac = a * c,
  3828. ad = a * d,
  3829. bc = b * c,
  3830. bd = b * d;
  3831. te[0] = c * e;
  3832. te[4] = bd - ac * f;
  3833. te[8] = bc * f + ad;
  3834. te[1] = f;
  3835. te[5] = a * e;
  3836. te[9] = -b * e;
  3837. te[2] = -d * e;
  3838. te[6] = ad * f + bc;
  3839. te[10] = ac - bd * f;
  3840. } else if (euler.order === 'XZY') {
  3841. const ac = a * c,
  3842. ad = a * d,
  3843. bc = b * c,
  3844. bd = b * d;
  3845. te[0] = c * e;
  3846. te[4] = -f;
  3847. te[8] = d * e;
  3848. te[1] = ac * f + bd;
  3849. te[5] = a * e;
  3850. te[9] = ad * f - bc;
  3851. te[2] = bc * f - ad;
  3852. te[6] = b * e;
  3853. te[10] = bd * f + ac;
  3854. } // bottom row
  3855. te[3] = 0;
  3856. te[7] = 0;
  3857. te[11] = 0; // last column
  3858. te[12] = 0;
  3859. te[13] = 0;
  3860. te[14] = 0;
  3861. te[15] = 1;
  3862. return this;
  3863. }
  3864. makeRotationFromQuaternion(q) {
  3865. return this.compose(_zero, q, _one);
  3866. }
  3867. lookAt(eye, target, up) {
  3868. const te = this.elements;
  3869. _z.subVectors(eye, target);
  3870. if (_z.lengthSq() === 0) {
  3871. // eye and target are in the same position
  3872. _z.z = 1;
  3873. }
  3874. _z.normalize();
  3875. _x.crossVectors(up, _z);
  3876. if (_x.lengthSq() === 0) {
  3877. // up and z are parallel
  3878. if (Math.abs(up.z) === 1) {
  3879. _z.x += 0.0001;
  3880. } else {
  3881. _z.z += 0.0001;
  3882. }
  3883. _z.normalize();
  3884. _x.crossVectors(up, _z);
  3885. }
  3886. _x.normalize();
  3887. _y.crossVectors(_z, _x);
  3888. te[0] = _x.x;
  3889. te[4] = _y.x;
  3890. te[8] = _z.x;
  3891. te[1] = _x.y;
  3892. te[5] = _y.y;
  3893. te[9] = _z.y;
  3894. te[2] = _x.z;
  3895. te[6] = _y.z;
  3896. te[10] = _z.z;
  3897. return this;
  3898. }
  3899. multiply(m, n) {
  3900. if (n !== undefined) {
  3901. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3902. return this.multiplyMatrices(m, n);
  3903. }
  3904. return this.multiplyMatrices(this, m);
  3905. }
  3906. premultiply(m) {
  3907. return this.multiplyMatrices(m, this);
  3908. }
  3909. multiplyMatrices(a, b) {
  3910. const ae = a.elements;
  3911. const be = b.elements;
  3912. const te = this.elements;
  3913. const a11 = ae[0],
  3914. a12 = ae[4],
  3915. a13 = ae[8],
  3916. a14 = ae[12];
  3917. const a21 = ae[1],
  3918. a22 = ae[5],
  3919. a23 = ae[9],
  3920. a24 = ae[13];
  3921. const a31 = ae[2],
  3922. a32 = ae[6],
  3923. a33 = ae[10],
  3924. a34 = ae[14];
  3925. const a41 = ae[3],
  3926. a42 = ae[7],
  3927. a43 = ae[11],
  3928. a44 = ae[15];
  3929. const b11 = be[0],
  3930. b12 = be[4],
  3931. b13 = be[8],
  3932. b14 = be[12];
  3933. const b21 = be[1],
  3934. b22 = be[5],
  3935. b23 = be[9],
  3936. b24 = be[13];
  3937. const b31 = be[2],
  3938. b32 = be[6],
  3939. b33 = be[10],
  3940. b34 = be[14];
  3941. const b41 = be[3],
  3942. b42 = be[7],
  3943. b43 = be[11],
  3944. b44 = be[15];
  3945. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3946. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3947. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3948. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3949. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3950. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3951. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3952. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3953. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3954. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3955. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3956. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3957. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3958. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3959. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3960. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3961. return this;
  3962. }
  3963. multiplyScalar(s) {
  3964. const te = this.elements;
  3965. te[0] *= s;
  3966. te[4] *= s;
  3967. te[8] *= s;
  3968. te[12] *= s;
  3969. te[1] *= s;
  3970. te[5] *= s;
  3971. te[9] *= s;
  3972. te[13] *= s;
  3973. te[2] *= s;
  3974. te[6] *= s;
  3975. te[10] *= s;
  3976. te[14] *= s;
  3977. te[3] *= s;
  3978. te[7] *= s;
  3979. te[11] *= s;
  3980. te[15] *= s;
  3981. return this;
  3982. }
  3983. determinant() {
  3984. const te = this.elements;
  3985. const n11 = te[0],
  3986. n12 = te[4],
  3987. n13 = te[8],
  3988. n14 = te[12];
  3989. const n21 = te[1],
  3990. n22 = te[5],
  3991. n23 = te[9],
  3992. n24 = te[13];
  3993. const n31 = te[2],
  3994. n32 = te[6],
  3995. n33 = te[10],
  3996. n34 = te[14];
  3997. const n41 = te[3],
  3998. n42 = te[7],
  3999. n43 = te[11],
  4000. n44 = te[15]; //TODO: make this more efficient
  4001. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4002. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  4003. }
  4004. transpose() {
  4005. const te = this.elements;
  4006. let tmp;
  4007. tmp = te[1];
  4008. te[1] = te[4];
  4009. te[4] = tmp;
  4010. tmp = te[2];
  4011. te[2] = te[8];
  4012. te[8] = tmp;
  4013. tmp = te[6];
  4014. te[6] = te[9];
  4015. te[9] = tmp;
  4016. tmp = te[3];
  4017. te[3] = te[12];
  4018. te[12] = tmp;
  4019. tmp = te[7];
  4020. te[7] = te[13];
  4021. te[13] = tmp;
  4022. tmp = te[11];
  4023. te[11] = te[14];
  4024. te[14] = tmp;
  4025. return this;
  4026. }
  4027. setPosition(x, y, z) {
  4028. const te = this.elements;
  4029. if (x.isVector3) {
  4030. te[12] = x.x;
  4031. te[13] = x.y;
  4032. te[14] = x.z;
  4033. } else {
  4034. te[12] = x;
  4035. te[13] = y;
  4036. te[14] = z;
  4037. }
  4038. return this;
  4039. }
  4040. invert() {
  4041. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4042. const te = this.elements,
  4043. n11 = te[0],
  4044. n21 = te[1],
  4045. n31 = te[2],
  4046. n41 = te[3],
  4047. n12 = te[4],
  4048. n22 = te[5],
  4049. n32 = te[6],
  4050. n42 = te[7],
  4051. n13 = te[8],
  4052. n23 = te[9],
  4053. n33 = te[10],
  4054. n43 = te[11],
  4055. n14 = te[12],
  4056. n24 = te[13],
  4057. n34 = te[14],
  4058. n44 = te[15],
  4059. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4060. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4061. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4062. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4063. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4064. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4065. const detInv = 1 / det;
  4066. te[0] = t11 * detInv;
  4067. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4068. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4069. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4070. te[4] = t12 * detInv;
  4071. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4072. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4073. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4074. te[8] = t13 * detInv;
  4075. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4076. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4077. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4078. te[12] = t14 * detInv;
  4079. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4080. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4081. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4082. return this;
  4083. }
  4084. scale(v) {
  4085. const te = this.elements;
  4086. const x = v.x,
  4087. y = v.y,
  4088. z = v.z;
  4089. te[0] *= x;
  4090. te[4] *= y;
  4091. te[8] *= z;
  4092. te[1] *= x;
  4093. te[5] *= y;
  4094. te[9] *= z;
  4095. te[2] *= x;
  4096. te[6] *= y;
  4097. te[10] *= z;
  4098. te[3] *= x;
  4099. te[7] *= y;
  4100. te[11] *= z;
  4101. return this;
  4102. }
  4103. getMaxScaleOnAxis() {
  4104. const te = this.elements;
  4105. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4106. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4107. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4108. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4109. }
  4110. makeTranslation(x, y, z) {
  4111. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4112. return this;
  4113. }
  4114. makeRotationX(theta) {
  4115. const c = Math.cos(theta),
  4116. s = Math.sin(theta);
  4117. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4118. return this;
  4119. }
  4120. makeRotationY(theta) {
  4121. const c = Math.cos(theta),
  4122. s = Math.sin(theta);
  4123. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4124. return this;
  4125. }
  4126. makeRotationZ(theta) {
  4127. const c = Math.cos(theta),
  4128. s = Math.sin(theta);
  4129. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4130. return this;
  4131. }
  4132. makeRotationAxis(axis, angle) {
  4133. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4134. const c = Math.cos(angle);
  4135. const s = Math.sin(angle);
  4136. const t = 1 - c;
  4137. const x = axis.x,
  4138. y = axis.y,
  4139. z = axis.z;
  4140. const tx = t * x,
  4141. ty = t * y;
  4142. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  4143. return this;
  4144. }
  4145. makeScale(x, y, z) {
  4146. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4147. return this;
  4148. }
  4149. makeShear(x, y, z) {
  4150. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4151. return this;
  4152. }
  4153. compose(position, quaternion, scale) {
  4154. const te = this.elements;
  4155. const x = quaternion._x,
  4156. y = quaternion._y,
  4157. z = quaternion._z,
  4158. w = quaternion._w;
  4159. const x2 = x + x,
  4160. y2 = y + y,
  4161. z2 = z + z;
  4162. const xx = x * x2,
  4163. xy = x * y2,
  4164. xz = x * z2;
  4165. const yy = y * y2,
  4166. yz = y * z2,
  4167. zz = z * z2;
  4168. const wx = w * x2,
  4169. wy = w * y2,
  4170. wz = w * z2;
  4171. const sx = scale.x,
  4172. sy = scale.y,
  4173. sz = scale.z;
  4174. te[0] = (1 - (yy + zz)) * sx;
  4175. te[1] = (xy + wz) * sx;
  4176. te[2] = (xz - wy) * sx;
  4177. te[3] = 0;
  4178. te[4] = (xy - wz) * sy;
  4179. te[5] = (1 - (xx + zz)) * sy;
  4180. te[6] = (yz + wx) * sy;
  4181. te[7] = 0;
  4182. te[8] = (xz + wy) * sz;
  4183. te[9] = (yz - wx) * sz;
  4184. te[10] = (1 - (xx + yy)) * sz;
  4185. te[11] = 0;
  4186. te[12] = position.x;
  4187. te[13] = position.y;
  4188. te[14] = position.z;
  4189. te[15] = 1;
  4190. return this;
  4191. }
  4192. decompose(position, quaternion, scale) {
  4193. const te = this.elements;
  4194. let sx = _v1$1.set(te[0], te[1], te[2]).length();
  4195. const sy = _v1$1.set(te[4], te[5], te[6]).length();
  4196. const sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4197. const det = this.determinant();
  4198. if (det < 0) sx = -sx;
  4199. position.x = te[12];
  4200. position.y = te[13];
  4201. position.z = te[14]; // scale the rotation part
  4202. _m1.copy(this);
  4203. const invSX = 1 / sx;
  4204. const invSY = 1 / sy;
  4205. const invSZ = 1 / sz;
  4206. _m1.elements[0] *= invSX;
  4207. _m1.elements[1] *= invSX;
  4208. _m1.elements[2] *= invSX;
  4209. _m1.elements[4] *= invSY;
  4210. _m1.elements[5] *= invSY;
  4211. _m1.elements[6] *= invSY;
  4212. _m1.elements[8] *= invSZ;
  4213. _m1.elements[9] *= invSZ;
  4214. _m1.elements[10] *= invSZ;
  4215. quaternion.setFromRotationMatrix(_m1);
  4216. scale.x = sx;
  4217. scale.y = sy;
  4218. scale.z = sz;
  4219. return this;
  4220. }
  4221. makePerspective(left, right, top, bottom, near, far) {
  4222. if (far === undefined) {
  4223. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4224. }
  4225. const te = this.elements;
  4226. const x = 2 * near / (right - left);
  4227. const y = 2 * near / (top - bottom);
  4228. const a = (right + left) / (right - left);
  4229. const b = (top + bottom) / (top - bottom);
  4230. const c = -(far + near) / (far - near);
  4231. const d = -2 * far * near / (far - near);
  4232. te[0] = x;
  4233. te[4] = 0;
  4234. te[8] = a;
  4235. te[12] = 0;
  4236. te[1] = 0;
  4237. te[5] = y;
  4238. te[9] = b;
  4239. te[13] = 0;
  4240. te[2] = 0;
  4241. te[6] = 0;
  4242. te[10] = c;
  4243. te[14] = d;
  4244. te[3] = 0;
  4245. te[7] = 0;
  4246. te[11] = -1;
  4247. te[15] = 0;
  4248. return this;
  4249. }
  4250. makeOrthographic(left, right, top, bottom, near, far) {
  4251. const te = this.elements;
  4252. const w = 1.0 / (right - left);
  4253. const h = 1.0 / (top - bottom);
  4254. const p = 1.0 / (far - near);
  4255. const x = (right + left) * w;
  4256. const y = (top + bottom) * h;
  4257. const z = (far + near) * p;
  4258. te[0] = 2 * w;
  4259. te[4] = 0;
  4260. te[8] = 0;
  4261. te[12] = -x;
  4262. te[1] = 0;
  4263. te[5] = 2 * h;
  4264. te[9] = 0;
  4265. te[13] = -y;
  4266. te[2] = 0;
  4267. te[6] = 0;
  4268. te[10] = -2 * p;
  4269. te[14] = -z;
  4270. te[3] = 0;
  4271. te[7] = 0;
  4272. te[11] = 0;
  4273. te[15] = 1;
  4274. return this;
  4275. }
  4276. equals(matrix) {
  4277. const te = this.elements;
  4278. const me = matrix.elements;
  4279. for (let i = 0; i < 16; i++) {
  4280. if (te[i] !== me[i]) return false;
  4281. }
  4282. return true;
  4283. }
  4284. fromArray(array, offset = 0) {
  4285. for (let i = 0; i < 16; i++) {
  4286. this.elements[i] = array[i + offset];
  4287. }
  4288. return this;
  4289. }
  4290. toArray(array = [], offset = 0) {
  4291. const te = this.elements;
  4292. array[offset] = te[0];
  4293. array[offset + 1] = te[1];
  4294. array[offset + 2] = te[2];
  4295. array[offset + 3] = te[3];
  4296. array[offset + 4] = te[4];
  4297. array[offset + 5] = te[5];
  4298. array[offset + 6] = te[6];
  4299. array[offset + 7] = te[7];
  4300. array[offset + 8] = te[8];
  4301. array[offset + 9] = te[9];
  4302. array[offset + 10] = te[10];
  4303. array[offset + 11] = te[11];
  4304. array[offset + 12] = te[12];
  4305. array[offset + 13] = te[13];
  4306. array[offset + 14] = te[14];
  4307. array[offset + 15] = te[15];
  4308. return array;
  4309. }
  4310. }
  4311. exports.Matrix4 = Matrix4;
  4312. const _v1$1 =
  4313. /*@__PURE__*/
  4314. new Vector3();
  4315. const _m1 =
  4316. /*@__PURE__*/
  4317. new Matrix4();
  4318. const _zero =
  4319. /*@__PURE__*/
  4320. new Vector3(0, 0, 0);
  4321. const _one =
  4322. /*@__PURE__*/
  4323. new Vector3(1, 1, 1);
  4324. const _x =
  4325. /*@__PURE__*/
  4326. new Vector3();
  4327. const _y =
  4328. /*@__PURE__*/
  4329. new Vector3();
  4330. const _z =
  4331. /*@__PURE__*/
  4332. new Vector3();
  4333. class Euler {
  4334. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4335. Object.defineProperty(this, 'isEuler', {
  4336. value: true
  4337. });
  4338. this._x = x;
  4339. this._y = y;
  4340. this._z = z;
  4341. this._order = order;
  4342. }
  4343. get x() {
  4344. return this._x;
  4345. }
  4346. set x(value) {
  4347. this._x = value;
  4348. this._onChangeCallback();
  4349. }
  4350. get y() {
  4351. return this._y;
  4352. }
  4353. set y(value) {
  4354. this._y = value;
  4355. this._onChangeCallback();
  4356. }
  4357. get z() {
  4358. return this._z;
  4359. }
  4360. set z(value) {
  4361. this._z = value;
  4362. this._onChangeCallback();
  4363. }
  4364. get order() {
  4365. return this._order;
  4366. }
  4367. set order(value) {
  4368. this._order = value;
  4369. this._onChangeCallback();
  4370. }
  4371. set(x, y, z, order) {
  4372. this._x = x;
  4373. this._y = y;
  4374. this._z = z;
  4375. this._order = order || this._order;
  4376. this._onChangeCallback();
  4377. return this;
  4378. }
  4379. clone() {
  4380. return new this.constructor(this._x, this._y, this._z, this._order);
  4381. }
  4382. copy(euler) {
  4383. this._x = euler._x;
  4384. this._y = euler._y;
  4385. this._z = euler._z;
  4386. this._order = euler._order;
  4387. this._onChangeCallback();
  4388. return this;
  4389. }
  4390. setFromRotationMatrix(m, order, update) {
  4391. const clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4392. const te = m.elements;
  4393. const m11 = te[0],
  4394. m12 = te[4],
  4395. m13 = te[8];
  4396. const m21 = te[1],
  4397. m22 = te[5],
  4398. m23 = te[9];
  4399. const m31 = te[2],
  4400. m32 = te[6],
  4401. m33 = te[10];
  4402. order = order || this._order;
  4403. switch (order) {
  4404. case 'XYZ':
  4405. this._y = Math.asin(clamp(m13, -1, 1));
  4406. if (Math.abs(m13) < 0.9999999) {
  4407. this._x = Math.atan2(-m23, m33);
  4408. this._z = Math.atan2(-m12, m11);
  4409. } else {
  4410. this._x = Math.atan2(m32, m22);
  4411. this._z = 0;
  4412. }
  4413. break;
  4414. case 'YXZ':
  4415. this._x = Math.asin(-clamp(m23, -1, 1));
  4416. if (Math.abs(m23) < 0.9999999) {
  4417. this._y = Math.atan2(m13, m33);
  4418. this._z = Math.atan2(m21, m22);
  4419. } else {
  4420. this._y = Math.atan2(-m31, m11);
  4421. this._z = 0;
  4422. }
  4423. break;
  4424. case 'ZXY':
  4425. this._x = Math.asin(clamp(m32, -1, 1));
  4426. if (Math.abs(m32) < 0.9999999) {
  4427. this._y = Math.atan2(-m31, m33);
  4428. this._z = Math.atan2(-m12, m22);
  4429. } else {
  4430. this._y = 0;
  4431. this._z = Math.atan2(m21, m11);
  4432. }
  4433. break;
  4434. case 'ZYX':
  4435. this._y = Math.asin(-clamp(m31, -1, 1));
  4436. if (Math.abs(m31) < 0.9999999) {
  4437. this._x = Math.atan2(m32, m33);
  4438. this._z = Math.atan2(m21, m11);
  4439. } else {
  4440. this._x = 0;
  4441. this._z = Math.atan2(-m12, m22);
  4442. }
  4443. break;
  4444. case 'YZX':
  4445. this._z = Math.asin(clamp(m21, -1, 1));
  4446. if (Math.abs(m21) < 0.9999999) {
  4447. this._x = Math.atan2(-m23, m22);
  4448. this._y = Math.atan2(-m31, m11);
  4449. } else {
  4450. this._x = 0;
  4451. this._y = Math.atan2(m13, m33);
  4452. }
  4453. break;
  4454. case 'XZY':
  4455. this._z = Math.asin(-clamp(m12, -1, 1));
  4456. if (Math.abs(m12) < 0.9999999) {
  4457. this._x = Math.atan2(m32, m22);
  4458. this._y = Math.atan2(m13, m11);
  4459. } else {
  4460. this._x = Math.atan2(-m23, m33);
  4461. this._y = 0;
  4462. }
  4463. break;
  4464. default:
  4465. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4466. }
  4467. this._order = order;
  4468. if (update !== false) this._onChangeCallback();
  4469. return this;
  4470. }
  4471. setFromQuaternion(q, order, update) {
  4472. _matrix.makeRotationFromQuaternion(q);
  4473. return this.setFromRotationMatrix(_matrix, order, update);
  4474. }
  4475. setFromVector3(v, order) {
  4476. return this.set(v.x, v.y, v.z, order || this._order);
  4477. }
  4478. reorder(newOrder) {
  4479. // WARNING: this discards revolution information -bhouston
  4480. _quaternion$1.setFromEuler(this);
  4481. return this.setFromQuaternion(_quaternion$1, newOrder);
  4482. }
  4483. equals(euler) {
  4484. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4485. }
  4486. fromArray(array) {
  4487. this._x = array[0];
  4488. this._y = array[1];
  4489. this._z = array[2];
  4490. if (array[3] !== undefined) this._order = array[3];
  4491. this._onChangeCallback();
  4492. return this;
  4493. }
  4494. toArray(array = [], offset = 0) {
  4495. array[offset] = this._x;
  4496. array[offset + 1] = this._y;
  4497. array[offset + 2] = this._z;
  4498. array[offset + 3] = this._order;
  4499. return array;
  4500. }
  4501. toVector3(optionalResult) {
  4502. if (optionalResult) {
  4503. return optionalResult.set(this._x, this._y, this._z);
  4504. } else {
  4505. return new Vector3(this._x, this._y, this._z);
  4506. }
  4507. }
  4508. _onChange(callback) {
  4509. this._onChangeCallback = callback;
  4510. return this;
  4511. }
  4512. _onChangeCallback() {}
  4513. }
  4514. exports.Euler = Euler;
  4515. Euler.DefaultOrder = 'XYZ';
  4516. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4517. const _matrix =
  4518. /*@__PURE__*/
  4519. new Matrix4();
  4520. const _quaternion$1 =
  4521. /*@__PURE__*/
  4522. new Quaternion();
  4523. class Layers {
  4524. constructor() {
  4525. this.mask = 1 | 0;
  4526. }
  4527. set(channel) {
  4528. this.mask = 1 << channel | 0;
  4529. }
  4530. enable(channel) {
  4531. this.mask |= 1 << channel | 0;
  4532. }
  4533. enableAll() {
  4534. this.mask = 0xffffffff | 0;
  4535. }
  4536. toggle(channel) {
  4537. this.mask ^= 1 << channel | 0;
  4538. }
  4539. disable(channel) {
  4540. this.mask &= ~(1 << channel | 0);
  4541. }
  4542. disableAll() {
  4543. this.mask = 0;
  4544. }
  4545. test(layers) {
  4546. return (this.mask & layers.mask) !== 0;
  4547. }
  4548. }
  4549. exports.Layers = Layers;
  4550. let _object3DId = 0;
  4551. const _v1$2 = new Vector3();
  4552. const _q1 = new Quaternion();
  4553. const _m1$1 = new Matrix4();
  4554. const _target = new Vector3();
  4555. const _position = new Vector3();
  4556. const _scale = new Vector3();
  4557. const _quaternion$2 = new Quaternion();
  4558. const _xAxis = new Vector3(1, 0, 0);
  4559. const _yAxis = new Vector3(0, 1, 0);
  4560. const _zAxis = new Vector3(0, 0, 1);
  4561. const _addedEvent = {
  4562. type: 'added'
  4563. };
  4564. const _removedEvent = {
  4565. type: 'removed'
  4566. };
  4567. function Object3D() {
  4568. Object.defineProperty(this, 'id', {
  4569. value: _object3DId++
  4570. });
  4571. this.uuid = MathUtils.generateUUID();
  4572. this.name = '';
  4573. this.type = 'Object3D';
  4574. this.parent = null;
  4575. this.children = [];
  4576. this.up = Object3D.DefaultUp.clone();
  4577. const position = new Vector3();
  4578. const rotation = new Euler();
  4579. const quaternion = new Quaternion();
  4580. const scale = new Vector3(1, 1, 1);
  4581. function onRotationChange() {
  4582. quaternion.setFromEuler(rotation, false);
  4583. }
  4584. function onQuaternionChange() {
  4585. rotation.setFromQuaternion(quaternion, undefined, false);
  4586. }
  4587. rotation._onChange(onRotationChange);
  4588. quaternion._onChange(onQuaternionChange);
  4589. Object.defineProperties(this, {
  4590. position: {
  4591. configurable: true,
  4592. enumerable: true,
  4593. value: position
  4594. },
  4595. rotation: {
  4596. configurable: true,
  4597. enumerable: true,
  4598. value: rotation
  4599. },
  4600. quaternion: {
  4601. configurable: true,
  4602. enumerable: true,
  4603. value: quaternion
  4604. },
  4605. scale: {
  4606. configurable: true,
  4607. enumerable: true,
  4608. value: scale
  4609. },
  4610. modelViewMatrix: {
  4611. value: new Matrix4()
  4612. },
  4613. normalMatrix: {
  4614. value: new Matrix3()
  4615. }
  4616. });
  4617. this.matrix = new Matrix4();
  4618. this.matrixWorld = new Matrix4();
  4619. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4620. this.matrixWorldNeedsUpdate = false;
  4621. this.layers = new Layers();
  4622. this.visible = true;
  4623. this.castShadow = false;
  4624. this.receiveShadow = false;
  4625. this.frustumCulled = true;
  4626. this.renderOrder = 0;
  4627. this.animations = [];
  4628. this.userData = {};
  4629. }
  4630. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4631. Object3D.DefaultMatrixAutoUpdate = true;
  4632. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4633. constructor: Object3D,
  4634. isObject3D: true,
  4635. onBeforeRender: function () {},
  4636. onAfterRender: function () {},
  4637. applyMatrix4: function (matrix) {
  4638. if (this.matrixAutoUpdate) this.updateMatrix();
  4639. this.matrix.premultiply(matrix);
  4640. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4641. },
  4642. applyQuaternion: function (q) {
  4643. this.quaternion.premultiply(q);
  4644. return this;
  4645. },
  4646. setRotationFromAxisAngle: function (axis, angle) {
  4647. // assumes axis is normalized
  4648. this.quaternion.setFromAxisAngle(axis, angle);
  4649. },
  4650. setRotationFromEuler: function (euler) {
  4651. this.quaternion.setFromEuler(euler, true);
  4652. },
  4653. setRotationFromMatrix: function (m) {
  4654. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4655. this.quaternion.setFromRotationMatrix(m);
  4656. },
  4657. setRotationFromQuaternion: function (q) {
  4658. // assumes q is normalized
  4659. this.quaternion.copy(q);
  4660. },
  4661. rotateOnAxis: function (axis, angle) {
  4662. // rotate object on axis in object space
  4663. // axis is assumed to be normalized
  4664. _q1.setFromAxisAngle(axis, angle);
  4665. this.quaternion.multiply(_q1);
  4666. return this;
  4667. },
  4668. rotateOnWorldAxis: function (axis, angle) {
  4669. // rotate object on axis in world space
  4670. // axis is assumed to be normalized
  4671. // method assumes no rotated parent
  4672. _q1.setFromAxisAngle(axis, angle);
  4673. this.quaternion.premultiply(_q1);
  4674. return this;
  4675. },
  4676. rotateX: function (angle) {
  4677. return this.rotateOnAxis(_xAxis, angle);
  4678. },
  4679. rotateY: function (angle) {
  4680. return this.rotateOnAxis(_yAxis, angle);
  4681. },
  4682. rotateZ: function (angle) {
  4683. return this.rotateOnAxis(_zAxis, angle);
  4684. },
  4685. translateOnAxis: function (axis, distance) {
  4686. // translate object by distance along axis in object space
  4687. // axis is assumed to be normalized
  4688. _v1$2.copy(axis).applyQuaternion(this.quaternion);
  4689. this.position.add(_v1$2.multiplyScalar(distance));
  4690. return this;
  4691. },
  4692. translateX: function (distance) {
  4693. return this.translateOnAxis(_xAxis, distance);
  4694. },
  4695. translateY: function (distance) {
  4696. return this.translateOnAxis(_yAxis, distance);
  4697. },
  4698. translateZ: function (distance) {
  4699. return this.translateOnAxis(_zAxis, distance);
  4700. },
  4701. localToWorld: function (vector) {
  4702. return vector.applyMatrix4(this.matrixWorld);
  4703. },
  4704. worldToLocal: function (vector) {
  4705. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4706. },
  4707. lookAt: function (x, y, z) {
  4708. // This method does not support objects having non-uniformly-scaled parent(s)
  4709. if (x.isVector3) {
  4710. _target.copy(x);
  4711. } else {
  4712. _target.set(x, y, z);
  4713. }
  4714. const parent = this.parent;
  4715. this.updateWorldMatrix(true, false);
  4716. _position.setFromMatrixPosition(this.matrixWorld);
  4717. if (this.isCamera || this.isLight) {
  4718. _m1$1.lookAt(_position, _target, this.up);
  4719. } else {
  4720. _m1$1.lookAt(_target, _position, this.up);
  4721. }
  4722. this.quaternion.setFromRotationMatrix(_m1$1);
  4723. if (parent) {
  4724. _m1$1.extractRotation(parent.matrixWorld);
  4725. _q1.setFromRotationMatrix(_m1$1);
  4726. this.quaternion.premultiply(_q1.invert());
  4727. }
  4728. },
  4729. add: function (object) {
  4730. if (arguments.length > 1) {
  4731. for (let i = 0; i < arguments.length; i++) {
  4732. this.add(arguments[i]);
  4733. }
  4734. return this;
  4735. }
  4736. if (object === this) {
  4737. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4738. return this;
  4739. }
  4740. if (object && object.isObject3D) {
  4741. if (object.parent !== null) {
  4742. object.parent.remove(object);
  4743. }
  4744. object.parent = this;
  4745. this.children.push(object);
  4746. object.dispatchEvent(_addedEvent);
  4747. } else {
  4748. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4749. }
  4750. return this;
  4751. },
  4752. remove: function (object) {
  4753. if (arguments.length > 1) {
  4754. for (let i = 0; i < arguments.length; i++) {
  4755. this.remove(arguments[i]);
  4756. }
  4757. return this;
  4758. }
  4759. const index = this.children.indexOf(object);
  4760. if (index !== -1) {
  4761. object.parent = null;
  4762. this.children.splice(index, 1);
  4763. object.dispatchEvent(_removedEvent);
  4764. }
  4765. return this;
  4766. },
  4767. clear: function () {
  4768. for (let i = 0; i < this.children.length; i++) {
  4769. const object = this.children[i];
  4770. object.parent = null;
  4771. object.dispatchEvent(_removedEvent);
  4772. }
  4773. this.children.length = 0;
  4774. return this;
  4775. },
  4776. attach: function (object) {
  4777. // adds object as a child of this, while maintaining the object's world transform
  4778. this.updateWorldMatrix(true, false);
  4779. _m1$1.copy(this.matrixWorld).invert();
  4780. if (object.parent !== null) {
  4781. object.parent.updateWorldMatrix(true, false);
  4782. _m1$1.multiply(object.parent.matrixWorld);
  4783. }
  4784. object.applyMatrix4(_m1$1);
  4785. object.updateWorldMatrix(false, false);
  4786. this.add(object);
  4787. return this;
  4788. },
  4789. getObjectById: function (id) {
  4790. return this.getObjectByProperty('id', id);
  4791. },
  4792. getObjectByName: function (name) {
  4793. return this.getObjectByProperty('name', name);
  4794. },
  4795. getObjectByProperty: function (name, value) {
  4796. if (this[name] === value) return this;
  4797. for (let i = 0, l = this.children.length; i < l; i++) {
  4798. const child = this.children[i];
  4799. const object = child.getObjectByProperty(name, value);
  4800. if (object !== undefined) {
  4801. return object;
  4802. }
  4803. }
  4804. return undefined;
  4805. },
  4806. getWorldPosition: function (target) {
  4807. if (target === undefined) {
  4808. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4809. target = new Vector3();
  4810. }
  4811. this.updateWorldMatrix(true, false);
  4812. return target.setFromMatrixPosition(this.matrixWorld);
  4813. },
  4814. getWorldQuaternion: function (target) {
  4815. if (target === undefined) {
  4816. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4817. target = new Quaternion();
  4818. }
  4819. this.updateWorldMatrix(true, false);
  4820. this.matrixWorld.decompose(_position, target, _scale);
  4821. return target;
  4822. },
  4823. getWorldScale: function (target) {
  4824. if (target === undefined) {
  4825. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4826. target = new Vector3();
  4827. }
  4828. this.updateWorldMatrix(true, false);
  4829. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4830. return target;
  4831. },
  4832. getWorldDirection: function (target) {
  4833. if (target === undefined) {
  4834. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4835. target = new Vector3();
  4836. }
  4837. this.updateWorldMatrix(true, false);
  4838. const e = this.matrixWorld.elements;
  4839. return target.set(e[8], e[9], e[10]).normalize();
  4840. },
  4841. raycast: function () {},
  4842. traverse: function (callback) {
  4843. callback(this);
  4844. const children = this.children;
  4845. for (let i = 0, l = children.length; i < l; i++) {
  4846. children[i].traverse(callback);
  4847. }
  4848. },
  4849. traverseVisible: function (callback) {
  4850. if (this.visible === false) return;
  4851. callback(this);
  4852. const children = this.children;
  4853. for (let i = 0, l = children.length; i < l; i++) {
  4854. children[i].traverseVisible(callback);
  4855. }
  4856. },
  4857. traverseAncestors: function (callback) {
  4858. const parent = this.parent;
  4859. if (parent !== null) {
  4860. callback(parent);
  4861. parent.traverseAncestors(callback);
  4862. }
  4863. },
  4864. updateMatrix: function () {
  4865. this.matrix.compose(this.position, this.quaternion, this.scale);
  4866. this.matrixWorldNeedsUpdate = true;
  4867. },
  4868. updateMatrixWorld: function (force) {
  4869. if (this.matrixAutoUpdate) this.updateMatrix();
  4870. if (this.matrixWorldNeedsUpdate || force) {
  4871. if (this.parent === null) {
  4872. this.matrixWorld.copy(this.matrix);
  4873. } else {
  4874. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4875. }
  4876. this.matrixWorldNeedsUpdate = false;
  4877. force = true;
  4878. } // update children
  4879. const children = this.children;
  4880. for (let i = 0, l = children.length; i < l; i++) {
  4881. children[i].updateMatrixWorld(force);
  4882. }
  4883. },
  4884. updateWorldMatrix: function (updateParents, updateChildren) {
  4885. const parent = this.parent;
  4886. if (updateParents === true && parent !== null) {
  4887. parent.updateWorldMatrix(true, false);
  4888. }
  4889. if (this.matrixAutoUpdate) this.updateMatrix();
  4890. if (this.parent === null) {
  4891. this.matrixWorld.copy(this.matrix);
  4892. } else {
  4893. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4894. } // update children
  4895. if (updateChildren === true) {
  4896. const children = this.children;
  4897. for (let i = 0, l = children.length; i < l; i++) {
  4898. children[i].updateWorldMatrix(false, true);
  4899. }
  4900. }
  4901. },
  4902. toJSON: function (meta) {
  4903. // meta is a string when called from JSON.stringify
  4904. const isRootObject = meta === undefined || typeof meta === 'string';
  4905. const output = {}; // meta is a hash used to collect geometries, materials.
  4906. // not providing it implies that this is the root object
  4907. // being serialized.
  4908. if (isRootObject) {
  4909. // initialize meta obj
  4910. meta = {
  4911. geometries: {},
  4912. materials: {},
  4913. textures: {},
  4914. images: {},
  4915. shapes: {},
  4916. skeletons: {},
  4917. animations: {}
  4918. };
  4919. output.metadata = {
  4920. version: 4.5,
  4921. type: 'Object',
  4922. generator: 'Object3D.toJSON'
  4923. };
  4924. } // standard Object3D serialization
  4925. const object = {};
  4926. object.uuid = this.uuid;
  4927. object.type = this.type;
  4928. if (this.name !== '') object.name = this.name;
  4929. if (this.castShadow === true) object.castShadow = true;
  4930. if (this.receiveShadow === true) object.receiveShadow = true;
  4931. if (this.visible === false) object.visible = false;
  4932. if (this.frustumCulled === false) object.frustumCulled = false;
  4933. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4934. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4935. object.layers = this.layers.mask;
  4936. object.matrix = this.matrix.toArray();
  4937. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4938. if (this.isInstancedMesh) {
  4939. object.type = 'InstancedMesh';
  4940. object.count = this.count;
  4941. object.instanceMatrix = this.instanceMatrix.toJSON();
  4942. } //
  4943. function serialize(library, element) {
  4944. if (library[element.uuid] === undefined) {
  4945. library[element.uuid] = element.toJSON(meta);
  4946. }
  4947. return element.uuid;
  4948. }
  4949. if (this.isMesh || this.isLine || this.isPoints) {
  4950. object.geometry = serialize(meta.geometries, this.geometry);
  4951. const parameters = this.geometry.parameters;
  4952. if (parameters !== undefined && parameters.shapes !== undefined) {
  4953. const shapes = parameters.shapes;
  4954. if (Array.isArray(shapes)) {
  4955. for (let i = 0, l = shapes.length; i < l; i++) {
  4956. const shape = shapes[i];
  4957. serialize(meta.shapes, shape);
  4958. }
  4959. } else {
  4960. serialize(meta.shapes, shapes);
  4961. }
  4962. }
  4963. }
  4964. if (this.isSkinnedMesh) {
  4965. object.bindMode = this.bindMode;
  4966. object.bindMatrix = this.bindMatrix.toArray();
  4967. if (this.skeleton !== undefined) {
  4968. serialize(meta.skeletons, this.skeleton);
  4969. object.skeleton = this.skeleton.uuid;
  4970. }
  4971. }
  4972. if (this.material !== undefined) {
  4973. if (Array.isArray(this.material)) {
  4974. const uuids = [];
  4975. for (let i = 0, l = this.material.length; i < l; i++) {
  4976. uuids.push(serialize(meta.materials, this.material[i]));
  4977. }
  4978. object.material = uuids;
  4979. } else {
  4980. object.material = serialize(meta.materials, this.material);
  4981. }
  4982. } //
  4983. if (this.children.length > 0) {
  4984. object.children = [];
  4985. for (let i = 0; i < this.children.length; i++) {
  4986. object.children.push(this.children[i].toJSON(meta).object);
  4987. }
  4988. } //
  4989. if (this.animations.length > 0) {
  4990. object.animations = [];
  4991. for (let i = 0; i < this.animations.length; i++) {
  4992. const animation = this.animations[i];
  4993. object.animations.push(serialize(meta.animations, animation));
  4994. }
  4995. }
  4996. if (isRootObject) {
  4997. const geometries = extractFromCache(meta.geometries);
  4998. const materials = extractFromCache(meta.materials);
  4999. const textures = extractFromCache(meta.textures);
  5000. const images = extractFromCache(meta.images);
  5001. const shapes = extractFromCache(meta.shapes);
  5002. const skeletons = extractFromCache(meta.skeletons);
  5003. const animations = extractFromCache(meta.animations);
  5004. if (geometries.length > 0) output.geometries = geometries;
  5005. if (materials.length > 0) output.materials = materials;
  5006. if (textures.length > 0) output.textures = textures;
  5007. if (images.length > 0) output.images = images;
  5008. if (shapes.length > 0) output.shapes = shapes;
  5009. if (skeletons.length > 0) output.skeletons = skeletons;
  5010. if (animations.length > 0) output.animations = animations;
  5011. }
  5012. output.object = object;
  5013. return output; // extract data from the cache hash
  5014. // remove metadata on each item
  5015. // and return as array
  5016. function extractFromCache(cache) {
  5017. const values = [];
  5018. for (const key in cache) {
  5019. const data = cache[key];
  5020. delete data.metadata;
  5021. values.push(data);
  5022. }
  5023. return values;
  5024. }
  5025. },
  5026. clone: function (recursive) {
  5027. return new this.constructor().copy(this, recursive);
  5028. },
  5029. copy: function (source, recursive = true) {
  5030. this.name = source.name;
  5031. this.up.copy(source.up);
  5032. this.position.copy(source.position);
  5033. this.rotation.order = source.rotation.order;
  5034. this.quaternion.copy(source.quaternion);
  5035. this.scale.copy(source.scale);
  5036. this.matrix.copy(source.matrix);
  5037. this.matrixWorld.copy(source.matrixWorld);
  5038. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5039. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5040. this.layers.mask = source.layers.mask;
  5041. this.visible = source.visible;
  5042. this.castShadow = source.castShadow;
  5043. this.receiveShadow = source.receiveShadow;
  5044. this.frustumCulled = source.frustumCulled;
  5045. this.renderOrder = source.renderOrder;
  5046. this.userData = JSON.parse(JSON.stringify(source.userData));
  5047. if (recursive === true) {
  5048. for (let i = 0; i < source.children.length; i++) {
  5049. const child = source.children[i];
  5050. this.add(child.clone());
  5051. }
  5052. }
  5053. return this;
  5054. }
  5055. });
  5056. const _vector1 =
  5057. /*@__PURE__*/
  5058. new Vector3();
  5059. const _vector2 =
  5060. /*@__PURE__*/
  5061. new Vector3();
  5062. const _normalMatrix =
  5063. /*@__PURE__*/
  5064. new Matrix3();
  5065. class Plane {
  5066. constructor(normal, constant) {
  5067. Object.defineProperty(this, 'isPlane', {
  5068. value: true
  5069. }); // normal is assumed to be normalized
  5070. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  5071. this.constant = constant !== undefined ? constant : 0;
  5072. }
  5073. set(normal, constant) {
  5074. this.normal.copy(normal);
  5075. this.constant = constant;
  5076. return this;
  5077. }
  5078. setComponents(x, y, z, w) {
  5079. this.normal.set(x, y, z);
  5080. this.constant = w;
  5081. return this;
  5082. }
  5083. setFromNormalAndCoplanarPoint(normal, point) {
  5084. this.normal.copy(normal);
  5085. this.constant = -point.dot(this.normal);
  5086. return this;
  5087. }
  5088. setFromCoplanarPoints(a, b, c) {
  5089. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5090. this.setFromNormalAndCoplanarPoint(normal, a);
  5091. return this;
  5092. }
  5093. clone() {
  5094. return new this.constructor().copy(this);
  5095. }
  5096. copy(plane) {
  5097. this.normal.copy(plane.normal);
  5098. this.constant = plane.constant;
  5099. return this;
  5100. }
  5101. normalize() {
  5102. // Note: will lead to a divide by zero if the plane is invalid.
  5103. const inverseNormalLength = 1.0 / this.normal.length();
  5104. this.normal.multiplyScalar(inverseNormalLength);
  5105. this.constant *= inverseNormalLength;
  5106. return this;
  5107. }
  5108. negate() {
  5109. this.constant *= -1;
  5110. this.normal.negate();
  5111. return this;
  5112. }
  5113. distanceToPoint(point) {
  5114. return this.normal.dot(point) + this.constant;
  5115. }
  5116. distanceToSphere(sphere) {
  5117. return this.distanceToPoint(sphere.center) - sphere.radius;
  5118. }
  5119. projectPoint(point, target) {
  5120. if (target === undefined) {
  5121. console.warn('THREE.Plane: .projectPoint() target is now required');
  5122. target = new Vector3();
  5123. }
  5124. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  5125. }
  5126. intersectLine(line, target) {
  5127. if (target === undefined) {
  5128. console.warn('THREE.Plane: .intersectLine() target is now required');
  5129. target = new Vector3();
  5130. }
  5131. const direction = line.delta(_vector1);
  5132. const denominator = this.normal.dot(direction);
  5133. if (denominator === 0) {
  5134. // line is coplanar, return origin
  5135. if (this.distanceToPoint(line.start) === 0) {
  5136. return target.copy(line.start);
  5137. } // Unsure if this is the correct method to handle this case.
  5138. return undefined;
  5139. }
  5140. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  5141. if (t < 0 || t > 1) {
  5142. return undefined;
  5143. }
  5144. return target.copy(direction).multiplyScalar(t).add(line.start);
  5145. }
  5146. intersectsLine(line) {
  5147. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5148. const startSign = this.distanceToPoint(line.start);
  5149. const endSign = this.distanceToPoint(line.end);
  5150. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  5151. }
  5152. intersectsBox(box) {
  5153. return box.intersectsPlane(this);
  5154. }
  5155. intersectsSphere(sphere) {
  5156. return sphere.intersectsPlane(this);
  5157. }
  5158. coplanarPoint(target) {
  5159. if (target === undefined) {
  5160. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  5161. target = new Vector3();
  5162. }
  5163. return target.copy(this.normal).multiplyScalar(-this.constant);
  5164. }
  5165. applyMatrix4(matrix, optionalNormalMatrix) {
  5166. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  5167. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  5168. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  5169. this.constant = -referencePoint.dot(normal);
  5170. return this;
  5171. }
  5172. translate(offset) {
  5173. this.constant -= offset.dot(this.normal);
  5174. return this;
  5175. }
  5176. equals(plane) {
  5177. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  5178. }
  5179. }
  5180. exports.Plane = Plane;
  5181. const _v0$1 =
  5182. /*@__PURE__*/
  5183. new Vector3();
  5184. const _v1$3 =
  5185. /*@__PURE__*/
  5186. new Vector3();
  5187. const _v2$1 =
  5188. /*@__PURE__*/
  5189. new Vector3();
  5190. const _v3 =
  5191. /*@__PURE__*/
  5192. new Vector3();
  5193. const _vab =
  5194. /*@__PURE__*/
  5195. new Vector3();
  5196. const _vac =
  5197. /*@__PURE__*/
  5198. new Vector3();
  5199. const _vbc =
  5200. /*@__PURE__*/
  5201. new Vector3();
  5202. const _vap =
  5203. /*@__PURE__*/
  5204. new Vector3();
  5205. const _vbp =
  5206. /*@__PURE__*/
  5207. new Vector3();
  5208. const _vcp =
  5209. /*@__PURE__*/
  5210. new Vector3();
  5211. class Triangle {
  5212. constructor(a, b, c) {
  5213. this.a = a !== undefined ? a : new Vector3();
  5214. this.b = b !== undefined ? b : new Vector3();
  5215. this.c = c !== undefined ? c : new Vector3();
  5216. }
  5217. static getNormal(a, b, c, target) {
  5218. if (target === undefined) {
  5219. console.warn('THREE.Triangle: .getNormal() target is now required');
  5220. target = new Vector3();
  5221. }
  5222. target.subVectors(c, b);
  5223. _v0$1.subVectors(a, b);
  5224. target.cross(_v0$1);
  5225. const targetLengthSq = target.lengthSq();
  5226. if (targetLengthSq > 0) {
  5227. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5228. }
  5229. return target.set(0, 0, 0);
  5230. } // static/instance method to calculate barycentric coordinates
  5231. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5232. static getBarycoord(point, a, b, c, target) {
  5233. _v0$1.subVectors(c, a);
  5234. _v1$3.subVectors(b, a);
  5235. _v2$1.subVectors(point, a);
  5236. const dot00 = _v0$1.dot(_v0$1);
  5237. const dot01 = _v0$1.dot(_v1$3);
  5238. const dot02 = _v0$1.dot(_v2$1);
  5239. const dot11 = _v1$3.dot(_v1$3);
  5240. const dot12 = _v1$3.dot(_v2$1);
  5241. const denom = dot00 * dot11 - dot01 * dot01;
  5242. if (target === undefined) {
  5243. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5244. target = new Vector3();
  5245. } // collinear or singular triangle
  5246. if (denom === 0) {
  5247. // arbitrary location outside of triangle?
  5248. // not sure if this is the best idea, maybe should be returning undefined
  5249. return target.set(-2, -1, -1);
  5250. }
  5251. const invDenom = 1 / denom;
  5252. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5253. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5254. return target.set(1 - u - v, v, u);
  5255. }
  5256. static containsPoint(point, a, b, c) {
  5257. this.getBarycoord(point, a, b, c, _v3);
  5258. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5259. }
  5260. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5261. this.getBarycoord(point, p1, p2, p3, _v3);
  5262. target.set(0, 0);
  5263. target.addScaledVector(uv1, _v3.x);
  5264. target.addScaledVector(uv2, _v3.y);
  5265. target.addScaledVector(uv3, _v3.z);
  5266. return target;
  5267. }
  5268. static isFrontFacing(a, b, c, direction) {
  5269. _v0$1.subVectors(c, b);
  5270. _v1$3.subVectors(a, b); // strictly front facing
  5271. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5272. }
  5273. set(a, b, c) {
  5274. this.a.copy(a);
  5275. this.b.copy(b);
  5276. this.c.copy(c);
  5277. return this;
  5278. }
  5279. setFromPointsAndIndices(points, i0, i1, i2) {
  5280. this.a.copy(points[i0]);
  5281. this.b.copy(points[i1]);
  5282. this.c.copy(points[i2]);
  5283. return this;
  5284. }
  5285. clone() {
  5286. return new this.constructor().copy(this);
  5287. }
  5288. copy(triangle) {
  5289. this.a.copy(triangle.a);
  5290. this.b.copy(triangle.b);
  5291. this.c.copy(triangle.c);
  5292. return this;
  5293. }
  5294. getArea() {
  5295. _v0$1.subVectors(this.c, this.b);
  5296. _v1$3.subVectors(this.a, this.b);
  5297. return _v0$1.cross(_v1$3).length() * 0.5;
  5298. }
  5299. getMidpoint(target) {
  5300. if (target === undefined) {
  5301. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5302. target = new Vector3();
  5303. }
  5304. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5305. }
  5306. getNormal(target) {
  5307. return Triangle.getNormal(this.a, this.b, this.c, target);
  5308. }
  5309. getPlane(target) {
  5310. if (target === undefined) {
  5311. console.warn('THREE.Triangle: .getPlane() target is now required');
  5312. target = new Plane();
  5313. }
  5314. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5315. }
  5316. getBarycoord(point, target) {
  5317. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5318. }
  5319. getUV(point, uv1, uv2, uv3, target) {
  5320. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5321. }
  5322. containsPoint(point) {
  5323. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5324. }
  5325. isFrontFacing(direction) {
  5326. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5327. }
  5328. intersectsBox(box) {
  5329. return box.intersectsTriangle(this);
  5330. }
  5331. closestPointToPoint(p, target) {
  5332. if (target === undefined) {
  5333. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5334. target = new Vector3();
  5335. }
  5336. const a = this.a,
  5337. b = this.b,
  5338. c = this.c;
  5339. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5340. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5341. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5342. // basically, we're distinguishing which of the voronoi regions of the triangle
  5343. // the point lies in with the minimum amount of redundant computation.
  5344. _vab.subVectors(b, a);
  5345. _vac.subVectors(c, a);
  5346. _vap.subVectors(p, a);
  5347. const d1 = _vab.dot(_vap);
  5348. const d2 = _vac.dot(_vap);
  5349. if (d1 <= 0 && d2 <= 0) {
  5350. // vertex region of A; barycentric coords (1, 0, 0)
  5351. return target.copy(a);
  5352. }
  5353. _vbp.subVectors(p, b);
  5354. const d3 = _vab.dot(_vbp);
  5355. const d4 = _vac.dot(_vbp);
  5356. if (d3 >= 0 && d4 <= d3) {
  5357. // vertex region of B; barycentric coords (0, 1, 0)
  5358. return target.copy(b);
  5359. }
  5360. const vc = d1 * d4 - d3 * d2;
  5361. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5362. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5363. return target.copy(a).addScaledVector(_vab, v);
  5364. }
  5365. _vcp.subVectors(p, c);
  5366. const d5 = _vab.dot(_vcp);
  5367. const d6 = _vac.dot(_vcp);
  5368. if (d6 >= 0 && d5 <= d6) {
  5369. // vertex region of C; barycentric coords (0, 0, 1)
  5370. return target.copy(c);
  5371. }
  5372. const vb = d5 * d2 - d1 * d6;
  5373. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5374. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5375. return target.copy(a).addScaledVector(_vac, w);
  5376. }
  5377. const va = d3 * d6 - d5 * d4;
  5378. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5379. _vbc.subVectors(c, b);
  5380. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5381. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5382. } // face region
  5383. const denom = 1 / (va + vb + vc); // u = va * denom
  5384. v = vb * denom;
  5385. w = vc * denom;
  5386. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5387. }
  5388. equals(triangle) {
  5389. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5390. }
  5391. }
  5392. exports.Triangle = Triangle;
  5393. const _colorKeywords = {
  5394. 'aliceblue': 0xF0F8FF,
  5395. 'antiquewhite': 0xFAEBD7,
  5396. 'aqua': 0x00FFFF,
  5397. 'aquamarine': 0x7FFFD4,
  5398. 'azure': 0xF0FFFF,
  5399. 'beige': 0xF5F5DC,
  5400. 'bisque': 0xFFE4C4,
  5401. 'black': 0x000000,
  5402. 'blanchedalmond': 0xFFEBCD,
  5403. 'blue': 0x0000FF,
  5404. 'blueviolet': 0x8A2BE2,
  5405. 'brown': 0xA52A2A,
  5406. 'burlywood': 0xDEB887,
  5407. 'cadetblue': 0x5F9EA0,
  5408. 'chartreuse': 0x7FFF00,
  5409. 'chocolate': 0xD2691E,
  5410. 'coral': 0xFF7F50,
  5411. 'cornflowerblue': 0x6495ED,
  5412. 'cornsilk': 0xFFF8DC,
  5413. 'crimson': 0xDC143C,
  5414. 'cyan': 0x00FFFF,
  5415. 'darkblue': 0x00008B,
  5416. 'darkcyan': 0x008B8B,
  5417. 'darkgoldenrod': 0xB8860B,
  5418. 'darkgray': 0xA9A9A9,
  5419. 'darkgreen': 0x006400,
  5420. 'darkgrey': 0xA9A9A9,
  5421. 'darkkhaki': 0xBDB76B,
  5422. 'darkmagenta': 0x8B008B,
  5423. 'darkolivegreen': 0x556B2F,
  5424. 'darkorange': 0xFF8C00,
  5425. 'darkorchid': 0x9932CC,
  5426. 'darkred': 0x8B0000,
  5427. 'darksalmon': 0xE9967A,
  5428. 'darkseagreen': 0x8FBC8F,
  5429. 'darkslateblue': 0x483D8B,
  5430. 'darkslategray': 0x2F4F4F,
  5431. 'darkslategrey': 0x2F4F4F,
  5432. 'darkturquoise': 0x00CED1,
  5433. 'darkviolet': 0x9400D3,
  5434. 'deeppink': 0xFF1493,
  5435. 'deepskyblue': 0x00BFFF,
  5436. 'dimgray': 0x696969,
  5437. 'dimgrey': 0x696969,
  5438. 'dodgerblue': 0x1E90FF,
  5439. 'firebrick': 0xB22222,
  5440. 'floralwhite': 0xFFFAF0,
  5441. 'forestgreen': 0x228B22,
  5442. 'fuchsia': 0xFF00FF,
  5443. 'gainsboro': 0xDCDCDC,
  5444. 'ghostwhite': 0xF8F8FF,
  5445. 'gold': 0xFFD700,
  5446. 'goldenrod': 0xDAA520,
  5447. 'gray': 0x808080,
  5448. 'green': 0x008000,
  5449. 'greenyellow': 0xADFF2F,
  5450. 'grey': 0x808080,
  5451. 'honeydew': 0xF0FFF0,
  5452. 'hotpink': 0xFF69B4,
  5453. 'indianred': 0xCD5C5C,
  5454. 'indigo': 0x4B0082,
  5455. 'ivory': 0xFFFFF0,
  5456. 'khaki': 0xF0E68C,
  5457. 'lavender': 0xE6E6FA,
  5458. 'lavenderblush': 0xFFF0F5,
  5459. 'lawngreen': 0x7CFC00,
  5460. 'lemonchiffon': 0xFFFACD,
  5461. 'lightblue': 0xADD8E6,
  5462. 'lightcoral': 0xF08080,
  5463. 'lightcyan': 0xE0FFFF,
  5464. 'lightgoldenrodyellow': 0xFAFAD2,
  5465. 'lightgray': 0xD3D3D3,
  5466. 'lightgreen': 0x90EE90,
  5467. 'lightgrey': 0xD3D3D3,
  5468. 'lightpink': 0xFFB6C1,
  5469. 'lightsalmon': 0xFFA07A,
  5470. 'lightseagreen': 0x20B2AA,
  5471. 'lightskyblue': 0x87CEFA,
  5472. 'lightslategray': 0x778899,
  5473. 'lightslategrey': 0x778899,
  5474. 'lightsteelblue': 0xB0C4DE,
  5475. 'lightyellow': 0xFFFFE0,
  5476. 'lime': 0x00FF00,
  5477. 'limegreen': 0x32CD32,
  5478. 'linen': 0xFAF0E6,
  5479. 'magenta': 0xFF00FF,
  5480. 'maroon': 0x800000,
  5481. 'mediumaquamarine': 0x66CDAA,
  5482. 'mediumblue': 0x0000CD,
  5483. 'mediumorchid': 0xBA55D3,
  5484. 'mediumpurple': 0x9370DB,
  5485. 'mediumseagreen': 0x3CB371,
  5486. 'mediumslateblue': 0x7B68EE,
  5487. 'mediumspringgreen': 0x00FA9A,
  5488. 'mediumturquoise': 0x48D1CC,
  5489. 'mediumvioletred': 0xC71585,
  5490. 'midnightblue': 0x191970,
  5491. 'mintcream': 0xF5FFFA,
  5492. 'mistyrose': 0xFFE4E1,
  5493. 'moccasin': 0xFFE4B5,
  5494. 'navajowhite': 0xFFDEAD,
  5495. 'navy': 0x000080,
  5496. 'oldlace': 0xFDF5E6,
  5497. 'olive': 0x808000,
  5498. 'olivedrab': 0x6B8E23,
  5499. 'orange': 0xFFA500,
  5500. 'orangered': 0xFF4500,
  5501. 'orchid': 0xDA70D6,
  5502. 'palegoldenrod': 0xEEE8AA,
  5503. 'palegreen': 0x98FB98,
  5504. 'paleturquoise': 0xAFEEEE,
  5505. 'palevioletred': 0xDB7093,
  5506. 'papayawhip': 0xFFEFD5,
  5507. 'peachpuff': 0xFFDAB9,
  5508. 'peru': 0xCD853F,
  5509. 'pink': 0xFFC0CB,
  5510. 'plum': 0xDDA0DD,
  5511. 'powderblue': 0xB0E0E6,
  5512. 'purple': 0x800080,
  5513. 'rebeccapurple': 0x663399,
  5514. 'red': 0xFF0000,
  5515. 'rosybrown': 0xBC8F8F,
  5516. 'royalblue': 0x4169E1,
  5517. 'saddlebrown': 0x8B4513,
  5518. 'salmon': 0xFA8072,
  5519. 'sandybrown': 0xF4A460,
  5520. 'seagreen': 0x2E8B57,
  5521. 'seashell': 0xFFF5EE,
  5522. 'sienna': 0xA0522D,
  5523. 'silver': 0xC0C0C0,
  5524. 'skyblue': 0x87CEEB,
  5525. 'slateblue': 0x6A5ACD,
  5526. 'slategray': 0x708090,
  5527. 'slategrey': 0x708090,
  5528. 'snow': 0xFFFAFA,
  5529. 'springgreen': 0x00FF7F,
  5530. 'steelblue': 0x4682B4,
  5531. 'tan': 0xD2B48C,
  5532. 'teal': 0x008080,
  5533. 'thistle': 0xD8BFD8,
  5534. 'tomato': 0xFF6347,
  5535. 'turquoise': 0x40E0D0,
  5536. 'violet': 0xEE82EE,
  5537. 'wheat': 0xF5DEB3,
  5538. 'white': 0xFFFFFF,
  5539. 'whitesmoke': 0xF5F5F5,
  5540. 'yellow': 0xFFFF00,
  5541. 'yellowgreen': 0x9ACD32
  5542. };
  5543. const _hslA = {
  5544. h: 0,
  5545. s: 0,
  5546. l: 0
  5547. };
  5548. const _hslB = {
  5549. h: 0,
  5550. s: 0,
  5551. l: 0
  5552. };
  5553. function hue2rgb(p, q, t) {
  5554. if (t < 0) t += 1;
  5555. if (t > 1) t -= 1;
  5556. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5557. if (t < 1 / 2) return q;
  5558. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5559. return p;
  5560. }
  5561. function SRGBToLinear(c) {
  5562. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5563. }
  5564. function LinearToSRGB(c) {
  5565. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5566. }
  5567. class Color {
  5568. constructor(r, g, b) {
  5569. Object.defineProperty(this, 'isColor', {
  5570. value: true
  5571. });
  5572. if (g === undefined && b === undefined) {
  5573. // r is THREE.Color, hex or string
  5574. return this.set(r);
  5575. }
  5576. return this.setRGB(r, g, b);
  5577. }
  5578. set(value) {
  5579. if (value && value.isColor) {
  5580. this.copy(value);
  5581. } else if (typeof value === 'number') {
  5582. this.setHex(value);
  5583. } else if (typeof value === 'string') {
  5584. this.setStyle(value);
  5585. }
  5586. return this;
  5587. }
  5588. setScalar(scalar) {
  5589. this.r = scalar;
  5590. this.g = scalar;
  5591. this.b = scalar;
  5592. return this;
  5593. }
  5594. setHex(hex) {
  5595. hex = Math.floor(hex);
  5596. this.r = (hex >> 16 & 255) / 255;
  5597. this.g = (hex >> 8 & 255) / 255;
  5598. this.b = (hex & 255) / 255;
  5599. return this;
  5600. }
  5601. setRGB(r, g, b) {
  5602. this.r = r;
  5603. this.g = g;
  5604. this.b = b;
  5605. return this;
  5606. }
  5607. setHSL(h, s, l) {
  5608. // h,s,l ranges are in 0.0 - 1.0
  5609. h = MathUtils.euclideanModulo(h, 1);
  5610. s = MathUtils.clamp(s, 0, 1);
  5611. l = MathUtils.clamp(l, 0, 1);
  5612. if (s === 0) {
  5613. this.r = this.g = this.b = l;
  5614. } else {
  5615. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5616. const q = 2 * l - p;
  5617. this.r = hue2rgb(q, p, h + 1 / 3);
  5618. this.g = hue2rgb(q, p, h);
  5619. this.b = hue2rgb(q, p, h - 1 / 3);
  5620. }
  5621. return this;
  5622. }
  5623. setStyle(style) {
  5624. function handleAlpha(string) {
  5625. if (string === undefined) return;
  5626. if (parseFloat(string) < 1) {
  5627. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5628. }
  5629. }
  5630. let m;
  5631. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5632. // rgb / hsl
  5633. let color;
  5634. const name = m[1];
  5635. const components = m[2];
  5636. switch (name) {
  5637. case 'rgb':
  5638. case 'rgba':
  5639. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5640. // rgb(255,0,0) rgba(255,0,0,0.5)
  5641. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5642. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5643. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5644. handleAlpha(color[5]);
  5645. return this;
  5646. }
  5647. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5648. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5649. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5650. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5651. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5652. handleAlpha(color[5]);
  5653. return this;
  5654. }
  5655. break;
  5656. case 'hsl':
  5657. case 'hsla':
  5658. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5659. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5660. const h = parseFloat(color[1]) / 360;
  5661. const s = parseInt(color[2], 10) / 100;
  5662. const l = parseInt(color[3], 10) / 100;
  5663. handleAlpha(color[5]);
  5664. return this.setHSL(h, s, l);
  5665. }
  5666. break;
  5667. }
  5668. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5669. // hex color
  5670. const hex = m[1];
  5671. const size = hex.length;
  5672. if (size === 3) {
  5673. // #ff0
  5674. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5675. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5676. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5677. return this;
  5678. } else if (size === 6) {
  5679. // #ff0000
  5680. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5681. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5682. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5683. return this;
  5684. }
  5685. }
  5686. if (style && style.length > 0) {
  5687. return this.setColorName(style);
  5688. }
  5689. return this;
  5690. }
  5691. setColorName(style) {
  5692. // color keywords
  5693. const hex = _colorKeywords[style];
  5694. if (hex !== undefined) {
  5695. // red
  5696. this.setHex(hex);
  5697. } else {
  5698. // unknown color
  5699. console.warn('THREE.Color: Unknown color ' + style);
  5700. }
  5701. return this;
  5702. }
  5703. clone() {
  5704. return new this.constructor(this.r, this.g, this.b);
  5705. }
  5706. copy(color) {
  5707. this.r = color.r;
  5708. this.g = color.g;
  5709. this.b = color.b;
  5710. return this;
  5711. }
  5712. copyGammaToLinear(color, gammaFactor = 2.0) {
  5713. this.r = Math.pow(color.r, gammaFactor);
  5714. this.g = Math.pow(color.g, gammaFactor);
  5715. this.b = Math.pow(color.b, gammaFactor);
  5716. return this;
  5717. }
  5718. copyLinearToGamma(color, gammaFactor = 2.0) {
  5719. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5720. this.r = Math.pow(color.r, safeInverse);
  5721. this.g = Math.pow(color.g, safeInverse);
  5722. this.b = Math.pow(color.b, safeInverse);
  5723. return this;
  5724. }
  5725. convertGammaToLinear(gammaFactor) {
  5726. this.copyGammaToLinear(this, gammaFactor);
  5727. return this;
  5728. }
  5729. convertLinearToGamma(gammaFactor) {
  5730. this.copyLinearToGamma(this, gammaFactor);
  5731. return this;
  5732. }
  5733. copySRGBToLinear(color) {
  5734. this.r = SRGBToLinear(color.r);
  5735. this.g = SRGBToLinear(color.g);
  5736. this.b = SRGBToLinear(color.b);
  5737. return this;
  5738. }
  5739. copyLinearToSRGB(color) {
  5740. this.r = LinearToSRGB(color.r);
  5741. this.g = LinearToSRGB(color.g);
  5742. this.b = LinearToSRGB(color.b);
  5743. return this;
  5744. }
  5745. convertSRGBToLinear() {
  5746. this.copySRGBToLinear(this);
  5747. return this;
  5748. }
  5749. convertLinearToSRGB() {
  5750. this.copyLinearToSRGB(this);
  5751. return this;
  5752. }
  5753. getHex() {
  5754. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5755. }
  5756. getHexString() {
  5757. return ('000000' + this.getHex().toString(16)).slice(-6);
  5758. }
  5759. getHSL(target) {
  5760. // h,s,l ranges are in 0.0 - 1.0
  5761. if (target === undefined) {
  5762. console.warn('THREE.Color: .getHSL() target is now required');
  5763. target = {
  5764. h: 0,
  5765. s: 0,
  5766. l: 0
  5767. };
  5768. }
  5769. const r = this.r,
  5770. g = this.g,
  5771. b = this.b;
  5772. const max = Math.max(r, g, b);
  5773. const min = Math.min(r, g, b);
  5774. let hue, saturation;
  5775. const lightness = (min + max) / 2.0;
  5776. if (min === max) {
  5777. hue = 0;
  5778. saturation = 0;
  5779. } else {
  5780. const delta = max - min;
  5781. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5782. switch (max) {
  5783. case r:
  5784. hue = (g - b) / delta + (g < b ? 6 : 0);
  5785. break;
  5786. case g:
  5787. hue = (b - r) / delta + 2;
  5788. break;
  5789. case b:
  5790. hue = (r - g) / delta + 4;
  5791. break;
  5792. }
  5793. hue /= 6;
  5794. }
  5795. target.h = hue;
  5796. target.s = saturation;
  5797. target.l = lightness;
  5798. return target;
  5799. }
  5800. getStyle() {
  5801. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5802. }
  5803. offsetHSL(h, s, l) {
  5804. this.getHSL(_hslA);
  5805. _hslA.h += h;
  5806. _hslA.s += s;
  5807. _hslA.l += l;
  5808. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5809. return this;
  5810. }
  5811. add(color) {
  5812. this.r += color.r;
  5813. this.g += color.g;
  5814. this.b += color.b;
  5815. return this;
  5816. }
  5817. addColors(color1, color2) {
  5818. this.r = color1.r + color2.r;
  5819. this.g = color1.g + color2.g;
  5820. this.b = color1.b + color2.b;
  5821. return this;
  5822. }
  5823. addScalar(s) {
  5824. this.r += s;
  5825. this.g += s;
  5826. this.b += s;
  5827. return this;
  5828. }
  5829. sub(color) {
  5830. this.r = Math.max(0, this.r - color.r);
  5831. this.g = Math.max(0, this.g - color.g);
  5832. this.b = Math.max(0, this.b - color.b);
  5833. return this;
  5834. }
  5835. multiply(color) {
  5836. this.r *= color.r;
  5837. this.g *= color.g;
  5838. this.b *= color.b;
  5839. return this;
  5840. }
  5841. multiplyScalar(s) {
  5842. this.r *= s;
  5843. this.g *= s;
  5844. this.b *= s;
  5845. return this;
  5846. }
  5847. lerp(color, alpha) {
  5848. this.r += (color.r - this.r) * alpha;
  5849. this.g += (color.g - this.g) * alpha;
  5850. this.b += (color.b - this.b) * alpha;
  5851. return this;
  5852. }
  5853. lerpHSL(color, alpha) {
  5854. this.getHSL(_hslA);
  5855. color.getHSL(_hslB);
  5856. const h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  5857. const s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  5858. const l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  5859. this.setHSL(h, s, l);
  5860. return this;
  5861. }
  5862. equals(c) {
  5863. return c.r === this.r && c.g === this.g && c.b === this.b;
  5864. }
  5865. fromArray(array, offset = 0) {
  5866. this.r = array[offset];
  5867. this.g = array[offset + 1];
  5868. this.b = array[offset + 2];
  5869. return this;
  5870. }
  5871. toArray(array = [], offset = 0) {
  5872. array[offset] = this.r;
  5873. array[offset + 1] = this.g;
  5874. array[offset + 2] = this.b;
  5875. return array;
  5876. }
  5877. fromBufferAttribute(attribute, index) {
  5878. this.r = attribute.getX(index);
  5879. this.g = attribute.getY(index);
  5880. this.b = attribute.getZ(index);
  5881. if (attribute.normalized === true) {
  5882. // assuming Uint8Array
  5883. this.r /= 255;
  5884. this.g /= 255;
  5885. this.b /= 255;
  5886. }
  5887. return this;
  5888. }
  5889. toJSON() {
  5890. return this.getHex();
  5891. }
  5892. }
  5893. exports.Color = Color;
  5894. Color.NAMES = _colorKeywords;
  5895. Color.prototype.r = 1;
  5896. Color.prototype.g = 1;
  5897. Color.prototype.b = 1;
  5898. class Face3 {
  5899. constructor(a, b, c, normal, color, materialIndex = 0) {
  5900. this.a = a;
  5901. this.b = b;
  5902. this.c = c;
  5903. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5904. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5905. this.color = color && color.isColor ? color : new Color();
  5906. this.vertexColors = Array.isArray(color) ? color : [];
  5907. this.materialIndex = materialIndex;
  5908. }
  5909. clone() {
  5910. return new this.constructor().copy(this);
  5911. }
  5912. copy(source) {
  5913. this.a = source.a;
  5914. this.b = source.b;
  5915. this.c = source.c;
  5916. this.normal.copy(source.normal);
  5917. this.color.copy(source.color);
  5918. this.materialIndex = source.materialIndex;
  5919. for (let i = 0, il = source.vertexNormals.length; i < il; i++) {
  5920. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5921. }
  5922. for (let i = 0, il = source.vertexColors.length; i < il; i++) {
  5923. this.vertexColors[i] = source.vertexColors[i].clone();
  5924. }
  5925. return this;
  5926. }
  5927. }
  5928. exports.Face3 = Face3;
  5929. let materialId = 0;
  5930. function Material() {
  5931. Object.defineProperty(this, 'id', {
  5932. value: materialId++
  5933. });
  5934. this.uuid = MathUtils.generateUUID();
  5935. this.name = '';
  5936. this.type = 'Material';
  5937. this.fog = true;
  5938. this.blending = NormalBlending;
  5939. this.side = FrontSide;
  5940. this.flatShading = false;
  5941. this.vertexColors = false;
  5942. this.opacity = 1;
  5943. this.transparent = false;
  5944. this.blendSrc = SrcAlphaFactor;
  5945. this.blendDst = OneMinusSrcAlphaFactor;
  5946. this.blendEquation = AddEquation;
  5947. this.blendSrcAlpha = null;
  5948. this.blendDstAlpha = null;
  5949. this.blendEquationAlpha = null;
  5950. this.depthFunc = LessEqualDepth;
  5951. this.depthTest = true;
  5952. this.depthWrite = true;
  5953. this.stencilWriteMask = 0xff;
  5954. this.stencilFunc = AlwaysStencilFunc;
  5955. this.stencilRef = 0;
  5956. this.stencilFuncMask = 0xff;
  5957. this.stencilFail = KeepStencilOp;
  5958. this.stencilZFail = KeepStencilOp;
  5959. this.stencilZPass = KeepStencilOp;
  5960. this.stencilWrite = false;
  5961. this.clippingPlanes = null;
  5962. this.clipIntersection = false;
  5963. this.clipShadows = false;
  5964. this.shadowSide = null;
  5965. this.colorWrite = true;
  5966. this.precision = null; // override the renderer's default precision for this material
  5967. this.polygonOffset = false;
  5968. this.polygonOffsetFactor = 0;
  5969. this.polygonOffsetUnits = 0;
  5970. this.dithering = false;
  5971. this.alphaTest = 0;
  5972. this.premultipliedAlpha = false;
  5973. this.visible = true;
  5974. this.toneMapped = true;
  5975. this.userData = {};
  5976. this.version = 0;
  5977. }
  5978. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5979. constructor: Material,
  5980. isMaterial: true,
  5981. onBeforeCompile: function ()
  5982. /* shaderobject, renderer */
  5983. {},
  5984. customProgramCacheKey: function () {
  5985. return this.onBeforeCompile.toString();
  5986. },
  5987. setValues: function (values) {
  5988. if (values === undefined) return;
  5989. for (const key in values) {
  5990. const newValue = values[key];
  5991. if (newValue === undefined) {
  5992. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  5993. continue;
  5994. } // for backward compatability if shading is set in the constructor
  5995. if (key === 'shading') {
  5996. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5997. this.flatShading = newValue === FlatShading ? true : false;
  5998. continue;
  5999. }
  6000. const currentValue = this[key];
  6001. if (currentValue === undefined) {
  6002. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6003. continue;
  6004. }
  6005. if (currentValue && currentValue.isColor) {
  6006. currentValue.set(newValue);
  6007. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6008. currentValue.copy(newValue);
  6009. } else {
  6010. this[key] = newValue;
  6011. }
  6012. }
  6013. },
  6014. toJSON: function (meta) {
  6015. const isRoot = meta === undefined || typeof meta === 'string';
  6016. if (isRoot) {
  6017. meta = {
  6018. textures: {},
  6019. images: {}
  6020. };
  6021. }
  6022. const data = {
  6023. metadata: {
  6024. version: 4.5,
  6025. type: 'Material',
  6026. generator: 'Material.toJSON'
  6027. }
  6028. }; // standard Material serialization
  6029. data.uuid = this.uuid;
  6030. data.type = this.type;
  6031. if (this.name !== '') data.name = this.name;
  6032. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6033. if (this.roughness !== undefined) data.roughness = this.roughness;
  6034. if (this.metalness !== undefined) data.metalness = this.metalness;
  6035. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6036. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6037. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6038. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6039. if (this.shininess !== undefined) data.shininess = this.shininess;
  6040. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6041. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6042. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  6043. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  6044. }
  6045. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  6046. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  6047. }
  6048. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6049. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  6050. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6051. }
  6052. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  6053. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  6054. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  6055. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  6056. if (this.aoMap && this.aoMap.isTexture) {
  6057. data.aoMap = this.aoMap.toJSON(meta).uuid;
  6058. data.aoMapIntensity = this.aoMapIntensity;
  6059. }
  6060. if (this.bumpMap && this.bumpMap.isTexture) {
  6061. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  6062. data.bumpScale = this.bumpScale;
  6063. }
  6064. if (this.normalMap && this.normalMap.isTexture) {
  6065. data.normalMap = this.normalMap.toJSON(meta).uuid;
  6066. data.normalMapType = this.normalMapType;
  6067. data.normalScale = this.normalScale.toArray();
  6068. }
  6069. if (this.displacementMap && this.displacementMap.isTexture) {
  6070. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  6071. data.displacementScale = this.displacementScale;
  6072. data.displacementBias = this.displacementBias;
  6073. }
  6074. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  6075. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  6076. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  6077. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  6078. if (this.envMap && this.envMap.isTexture) {
  6079. data.envMap = this.envMap.toJSON(meta).uuid;
  6080. data.reflectivity = this.reflectivity; // Scale behind envMap
  6081. data.refractionRatio = this.refractionRatio;
  6082. if (this.combine !== undefined) data.combine = this.combine;
  6083. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  6084. }
  6085. if (this.gradientMap && this.gradientMap.isTexture) {
  6086. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  6087. }
  6088. if (this.size !== undefined) data.size = this.size;
  6089. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  6090. if (this.blending !== NormalBlending) data.blending = this.blending;
  6091. if (this.flatShading === true) data.flatShading = this.flatShading;
  6092. if (this.side !== FrontSide) data.side = this.side;
  6093. if (this.vertexColors) data.vertexColors = true;
  6094. if (this.opacity < 1) data.opacity = this.opacity;
  6095. if (this.transparent === true) data.transparent = this.transparent;
  6096. data.depthFunc = this.depthFunc;
  6097. data.depthTest = this.depthTest;
  6098. data.depthWrite = this.depthWrite;
  6099. data.stencilWrite = this.stencilWrite;
  6100. data.stencilWriteMask = this.stencilWriteMask;
  6101. data.stencilFunc = this.stencilFunc;
  6102. data.stencilRef = this.stencilRef;
  6103. data.stencilFuncMask = this.stencilFuncMask;
  6104. data.stencilFail = this.stencilFail;
  6105. data.stencilZFail = this.stencilZFail;
  6106. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  6107. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  6108. if (this.polygonOffset === true) data.polygonOffset = true;
  6109. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6110. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6111. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  6112. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  6113. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  6114. if (this.scale !== undefined) data.scale = this.scale;
  6115. if (this.dithering === true) data.dithering = true;
  6116. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  6117. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  6118. if (this.wireframe === true) data.wireframe = this.wireframe;
  6119. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  6120. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  6121. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  6122. if (this.morphTargets === true) data.morphTargets = true;
  6123. if (this.morphNormals === true) data.morphNormals = true;
  6124. if (this.skinning === true) data.skinning = true;
  6125. if (this.visible === false) data.visible = false;
  6126. if (this.toneMapped === false) data.toneMapped = false;
  6127. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  6128. function extractFromCache(cache) {
  6129. const values = [];
  6130. for (const key in cache) {
  6131. const data = cache[key];
  6132. delete data.metadata;
  6133. values.push(data);
  6134. }
  6135. return values;
  6136. }
  6137. if (isRoot) {
  6138. const textures = extractFromCache(meta.textures);
  6139. const images = extractFromCache(meta.images);
  6140. if (textures.length > 0) data.textures = textures;
  6141. if (images.length > 0) data.images = images;
  6142. }
  6143. return data;
  6144. },
  6145. clone: function () {
  6146. return new this.constructor().copy(this);
  6147. },
  6148. copy: function (source) {
  6149. this.name = source.name;
  6150. this.fog = source.fog;
  6151. this.blending = source.blending;
  6152. this.side = source.side;
  6153. this.flatShading = source.flatShading;
  6154. this.vertexColors = source.vertexColors;
  6155. this.opacity = source.opacity;
  6156. this.transparent = source.transparent;
  6157. this.blendSrc = source.blendSrc;
  6158. this.blendDst = source.blendDst;
  6159. this.blendEquation = source.blendEquation;
  6160. this.blendSrcAlpha = source.blendSrcAlpha;
  6161. this.blendDstAlpha = source.blendDstAlpha;
  6162. this.blendEquationAlpha = source.blendEquationAlpha;
  6163. this.depthFunc = source.depthFunc;
  6164. this.depthTest = source.depthTest;
  6165. this.depthWrite = source.depthWrite;
  6166. this.stencilWriteMask = source.stencilWriteMask;
  6167. this.stencilFunc = source.stencilFunc;
  6168. this.stencilRef = source.stencilRef;
  6169. this.stencilFuncMask = source.stencilFuncMask;
  6170. this.stencilFail = source.stencilFail;
  6171. this.stencilZFail = source.stencilZFail;
  6172. this.stencilZPass = source.stencilZPass;
  6173. this.stencilWrite = source.stencilWrite;
  6174. const srcPlanes = source.clippingPlanes;
  6175. let dstPlanes = null;
  6176. if (srcPlanes !== null) {
  6177. const n = srcPlanes.length;
  6178. dstPlanes = new Array(n);
  6179. for (let i = 0; i !== n; ++i) {
  6180. dstPlanes[i] = srcPlanes[i].clone();
  6181. }
  6182. }
  6183. this.clippingPlanes = dstPlanes;
  6184. this.clipIntersection = source.clipIntersection;
  6185. this.clipShadows = source.clipShadows;
  6186. this.shadowSide = source.shadowSide;
  6187. this.colorWrite = source.colorWrite;
  6188. this.precision = source.precision;
  6189. this.polygonOffset = source.polygonOffset;
  6190. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6191. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6192. this.dithering = source.dithering;
  6193. this.alphaTest = source.alphaTest;
  6194. this.premultipliedAlpha = source.premultipliedAlpha;
  6195. this.visible = source.visible;
  6196. this.toneMapped = source.toneMapped;
  6197. this.userData = JSON.parse(JSON.stringify(source.userData));
  6198. return this;
  6199. },
  6200. dispose: function () {
  6201. this.dispatchEvent({
  6202. type: 'dispose'
  6203. });
  6204. }
  6205. });
  6206. Object.defineProperty(Material.prototype, 'needsUpdate', {
  6207. set: function (value) {
  6208. if (value === true) this.version++;
  6209. }
  6210. });
  6211. /**
  6212. * parameters = {
  6213. * color: <hex>,
  6214. * opacity: <float>,
  6215. * map: new THREE.Texture( <Image> ),
  6216. *
  6217. * lightMap: new THREE.Texture( <Image> ),
  6218. * lightMapIntensity: <float>
  6219. *
  6220. * aoMap: new THREE.Texture( <Image> ),
  6221. * aoMapIntensity: <float>
  6222. *
  6223. * specularMap: new THREE.Texture( <Image> ),
  6224. *
  6225. * alphaMap: new THREE.Texture( <Image> ),
  6226. *
  6227. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6228. * combine: THREE.Multiply,
  6229. * reflectivity: <float>,
  6230. * refractionRatio: <float>,
  6231. *
  6232. * depthTest: <bool>,
  6233. * depthWrite: <bool>,
  6234. *
  6235. * wireframe: <boolean>,
  6236. * wireframeLinewidth: <float>,
  6237. *
  6238. * skinning: <bool>,
  6239. * morphTargets: <bool>
  6240. * }
  6241. */
  6242. function MeshBasicMaterial(parameters) {
  6243. Material.call(this);
  6244. this.type = 'MeshBasicMaterial';
  6245. this.color = new Color(0xffffff); // emissive
  6246. this.map = null;
  6247. this.lightMap = null;
  6248. this.lightMapIntensity = 1.0;
  6249. this.aoMap = null;
  6250. this.aoMapIntensity = 1.0;
  6251. this.specularMap = null;
  6252. this.alphaMap = null;
  6253. this.envMap = null;
  6254. this.combine = MultiplyOperation;
  6255. this.reflectivity = 1;
  6256. this.refractionRatio = 0.98;
  6257. this.wireframe = false;
  6258. this.wireframeLinewidth = 1;
  6259. this.wireframeLinecap = 'round';
  6260. this.wireframeLinejoin = 'round';
  6261. this.skinning = false;
  6262. this.morphTargets = false;
  6263. this.setValues(parameters);
  6264. }
  6265. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6266. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6267. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6268. MeshBasicMaterial.prototype.copy = function (source) {
  6269. Material.prototype.copy.call(this, source);
  6270. this.color.copy(source.color);
  6271. this.map = source.map;
  6272. this.lightMap = source.lightMap;
  6273. this.lightMapIntensity = source.lightMapIntensity;
  6274. this.aoMap = source.aoMap;
  6275. this.aoMapIntensity = source.aoMapIntensity;
  6276. this.specularMap = source.specularMap;
  6277. this.alphaMap = source.alphaMap;
  6278. this.envMap = source.envMap;
  6279. this.combine = source.combine;
  6280. this.reflectivity = source.reflectivity;
  6281. this.refractionRatio = source.refractionRatio;
  6282. this.wireframe = source.wireframe;
  6283. this.wireframeLinewidth = source.wireframeLinewidth;
  6284. this.wireframeLinecap = source.wireframeLinecap;
  6285. this.wireframeLinejoin = source.wireframeLinejoin;
  6286. this.skinning = source.skinning;
  6287. this.morphTargets = source.morphTargets;
  6288. return this;
  6289. };
  6290. const _vector$3 = new Vector3();
  6291. const _vector2$1 = new Vector2();
  6292. function BufferAttribute(array, itemSize, normalized) {
  6293. if (Array.isArray(array)) {
  6294. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6295. }
  6296. this.name = '';
  6297. this.array = array;
  6298. this.itemSize = itemSize;
  6299. this.count = array !== undefined ? array.length / itemSize : 0;
  6300. this.normalized = normalized === true;
  6301. this.usage = StaticDrawUsage;
  6302. this.updateRange = {
  6303. offset: 0,
  6304. count: -1
  6305. };
  6306. this.version = 0;
  6307. }
  6308. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6309. set: function (value) {
  6310. if (value === true) this.version++;
  6311. }
  6312. });
  6313. Object.assign(BufferAttribute.prototype, {
  6314. isBufferAttribute: true,
  6315. onUploadCallback: function () {},
  6316. setUsage: function (value) {
  6317. this.usage = value;
  6318. return this;
  6319. },
  6320. copy: function (source) {
  6321. this.name = source.name;
  6322. this.array = new source.array.constructor(source.array);
  6323. this.itemSize = source.itemSize;
  6324. this.count = source.count;
  6325. this.normalized = source.normalized;
  6326. this.usage = source.usage;
  6327. return this;
  6328. },
  6329. copyAt: function (index1, attribute, index2) {
  6330. index1 *= this.itemSize;
  6331. index2 *= attribute.itemSize;
  6332. for (let i = 0, l = this.itemSize; i < l; i++) {
  6333. this.array[index1 + i] = attribute.array[index2 + i];
  6334. }
  6335. return this;
  6336. },
  6337. copyArray: function (array) {
  6338. this.array.set(array);
  6339. return this;
  6340. },
  6341. copyColorsArray: function (colors) {
  6342. const array = this.array;
  6343. let offset = 0;
  6344. for (let i = 0, l = colors.length; i < l; i++) {
  6345. let color = colors[i];
  6346. if (color === undefined) {
  6347. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6348. color = new Color();
  6349. }
  6350. array[offset++] = color.r;
  6351. array[offset++] = color.g;
  6352. array[offset++] = color.b;
  6353. }
  6354. return this;
  6355. },
  6356. copyVector2sArray: function (vectors) {
  6357. const array = this.array;
  6358. let offset = 0;
  6359. for (let i = 0, l = vectors.length; i < l; i++) {
  6360. let vector = vectors[i];
  6361. if (vector === undefined) {
  6362. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6363. vector = new Vector2();
  6364. }
  6365. array[offset++] = vector.x;
  6366. array[offset++] = vector.y;
  6367. }
  6368. return this;
  6369. },
  6370. copyVector3sArray: function (vectors) {
  6371. const array = this.array;
  6372. let offset = 0;
  6373. for (let i = 0, l = vectors.length; i < l; i++) {
  6374. let vector = vectors[i];
  6375. if (vector === undefined) {
  6376. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6377. vector = new Vector3();
  6378. }
  6379. array[offset++] = vector.x;
  6380. array[offset++] = vector.y;
  6381. array[offset++] = vector.z;
  6382. }
  6383. return this;
  6384. },
  6385. copyVector4sArray: function (vectors) {
  6386. const array = this.array;
  6387. let offset = 0;
  6388. for (let i = 0, l = vectors.length; i < l; i++) {
  6389. let vector = vectors[i];
  6390. if (vector === undefined) {
  6391. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6392. vector = new Vector4();
  6393. }
  6394. array[offset++] = vector.x;
  6395. array[offset++] = vector.y;
  6396. array[offset++] = vector.z;
  6397. array[offset++] = vector.w;
  6398. }
  6399. return this;
  6400. },
  6401. applyMatrix3: function (m) {
  6402. if (this.itemSize === 2) {
  6403. for (let i = 0, l = this.count; i < l; i++) {
  6404. _vector2$1.fromBufferAttribute(this, i);
  6405. _vector2$1.applyMatrix3(m);
  6406. this.setXY(i, _vector2$1.x, _vector2$1.y);
  6407. }
  6408. } else if (this.itemSize === 3) {
  6409. for (let i = 0, l = this.count; i < l; i++) {
  6410. _vector$3.fromBufferAttribute(this, i);
  6411. _vector$3.applyMatrix3(m);
  6412. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6413. }
  6414. }
  6415. return this;
  6416. },
  6417. applyMatrix4: function (m) {
  6418. for (let i = 0, l = this.count; i < l; i++) {
  6419. _vector$3.x = this.getX(i);
  6420. _vector$3.y = this.getY(i);
  6421. _vector$3.z = this.getZ(i);
  6422. _vector$3.applyMatrix4(m);
  6423. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6424. }
  6425. return this;
  6426. },
  6427. applyNormalMatrix: function (m) {
  6428. for (let i = 0, l = this.count; i < l; i++) {
  6429. _vector$3.x = this.getX(i);
  6430. _vector$3.y = this.getY(i);
  6431. _vector$3.z = this.getZ(i);
  6432. _vector$3.applyNormalMatrix(m);
  6433. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6434. }
  6435. return this;
  6436. },
  6437. transformDirection: function (m) {
  6438. for (let i = 0, l = this.count; i < l; i++) {
  6439. _vector$3.x = this.getX(i);
  6440. _vector$3.y = this.getY(i);
  6441. _vector$3.z = this.getZ(i);
  6442. _vector$3.transformDirection(m);
  6443. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6444. }
  6445. return this;
  6446. },
  6447. set: function (value, offset = 0) {
  6448. this.array.set(value, offset);
  6449. return this;
  6450. },
  6451. getX: function (index) {
  6452. return this.array[index * this.itemSize];
  6453. },
  6454. setX: function (index, x) {
  6455. this.array[index * this.itemSize] = x;
  6456. return this;
  6457. },
  6458. getY: function (index) {
  6459. return this.array[index * this.itemSize + 1];
  6460. },
  6461. setY: function (index, y) {
  6462. this.array[index * this.itemSize + 1] = y;
  6463. return this;
  6464. },
  6465. getZ: function (index) {
  6466. return this.array[index * this.itemSize + 2];
  6467. },
  6468. setZ: function (index, z) {
  6469. this.array[index * this.itemSize + 2] = z;
  6470. return this;
  6471. },
  6472. getW: function (index) {
  6473. return this.array[index * this.itemSize + 3];
  6474. },
  6475. setW: function (index, w) {
  6476. this.array[index * this.itemSize + 3] = w;
  6477. return this;
  6478. },
  6479. setXY: function (index, x, y) {
  6480. index *= this.itemSize;
  6481. this.array[index + 0] = x;
  6482. this.array[index + 1] = y;
  6483. return this;
  6484. },
  6485. setXYZ: function (index, x, y, z) {
  6486. index *= this.itemSize;
  6487. this.array[index + 0] = x;
  6488. this.array[index + 1] = y;
  6489. this.array[index + 2] = z;
  6490. return this;
  6491. },
  6492. setXYZW: function (index, x, y, z, w) {
  6493. index *= this.itemSize;
  6494. this.array[index + 0] = x;
  6495. this.array[index + 1] = y;
  6496. this.array[index + 2] = z;
  6497. this.array[index + 3] = w;
  6498. return this;
  6499. },
  6500. onUpload: function (callback) {
  6501. this.onUploadCallback = callback;
  6502. return this;
  6503. },
  6504. clone: function () {
  6505. return new this.constructor(this.array, this.itemSize).copy(this);
  6506. },
  6507. toJSON: function () {
  6508. return {
  6509. itemSize: this.itemSize,
  6510. type: this.array.constructor.name,
  6511. array: Array.prototype.slice.call(this.array),
  6512. normalized: this.normalized
  6513. };
  6514. }
  6515. }); //
  6516. function Int8BufferAttribute(array, itemSize, normalized) {
  6517. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6518. }
  6519. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6520. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6521. function Uint8BufferAttribute(array, itemSize, normalized) {
  6522. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6523. }
  6524. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6525. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6526. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6527. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6528. }
  6529. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6530. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6531. function Int16BufferAttribute(array, itemSize, normalized) {
  6532. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6533. }
  6534. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6535. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6536. function Uint16BufferAttribute(array, itemSize, normalized) {
  6537. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6538. }
  6539. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6540. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6541. function Int32BufferAttribute(array, itemSize, normalized) {
  6542. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6543. }
  6544. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6545. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6546. function Uint32BufferAttribute(array, itemSize, normalized) {
  6547. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6548. }
  6549. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6550. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6551. function Float16BufferAttribute(array, itemSize, normalized) {
  6552. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6553. }
  6554. Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6555. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  6556. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6557. function Float32BufferAttribute(array, itemSize, normalized) {
  6558. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6559. }
  6560. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6561. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6562. function Float64BufferAttribute(array, itemSize, normalized) {
  6563. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6564. }
  6565. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6566. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6567. class DirectGeometry {
  6568. constructor() {
  6569. this.vertices = [];
  6570. this.normals = [];
  6571. this.colors = [];
  6572. this.uvs = [];
  6573. this.uvs2 = [];
  6574. this.groups = [];
  6575. this.morphTargets = {};
  6576. this.skinWeights = [];
  6577. this.skinIndices = []; // this.lineDistances = [];
  6578. this.boundingBox = null;
  6579. this.boundingSphere = null; // update flags
  6580. this.verticesNeedUpdate = false;
  6581. this.normalsNeedUpdate = false;
  6582. this.colorsNeedUpdate = false;
  6583. this.uvsNeedUpdate = false;
  6584. this.groupsNeedUpdate = false;
  6585. }
  6586. computeGroups(geometry) {
  6587. const groups = [];
  6588. let group, i;
  6589. let materialIndex = undefined;
  6590. const faces = geometry.faces;
  6591. for (i = 0; i < faces.length; i++) {
  6592. const face = faces[i]; // materials
  6593. if (face.materialIndex !== materialIndex) {
  6594. materialIndex = face.materialIndex;
  6595. if (group !== undefined) {
  6596. group.count = i * 3 - group.start;
  6597. groups.push(group);
  6598. }
  6599. group = {
  6600. start: i * 3,
  6601. materialIndex: materialIndex
  6602. };
  6603. }
  6604. }
  6605. if (group !== undefined) {
  6606. group.count = i * 3 - group.start;
  6607. groups.push(group);
  6608. }
  6609. this.groups = groups;
  6610. }
  6611. fromGeometry(geometry) {
  6612. const faces = geometry.faces;
  6613. const vertices = geometry.vertices;
  6614. const faceVertexUvs = geometry.faceVertexUvs;
  6615. const hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6616. const hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6617. const morphTargets = geometry.morphTargets;
  6618. const morphTargetsLength = morphTargets.length;
  6619. let morphTargetsPosition;
  6620. if (morphTargetsLength > 0) {
  6621. morphTargetsPosition = [];
  6622. for (let i = 0; i < morphTargetsLength; i++) {
  6623. morphTargetsPosition[i] = {
  6624. name: morphTargets[i].name,
  6625. data: []
  6626. };
  6627. }
  6628. this.morphTargets.position = morphTargetsPosition;
  6629. }
  6630. const morphNormals = geometry.morphNormals;
  6631. const morphNormalsLength = morphNormals.length;
  6632. let morphTargetsNormal;
  6633. if (morphNormalsLength > 0) {
  6634. morphTargetsNormal = [];
  6635. for (let i = 0; i < morphNormalsLength; i++) {
  6636. morphTargetsNormal[i] = {
  6637. name: morphNormals[i].name,
  6638. data: []
  6639. };
  6640. }
  6641. this.morphTargets.normal = morphTargetsNormal;
  6642. } // skins
  6643. const skinIndices = geometry.skinIndices;
  6644. const skinWeights = geometry.skinWeights;
  6645. const hasSkinIndices = skinIndices.length === vertices.length;
  6646. const hasSkinWeights = skinWeights.length === vertices.length; //
  6647. if (vertices.length > 0 && faces.length === 0) {
  6648. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6649. }
  6650. for (let i = 0; i < faces.length; i++) {
  6651. const face = faces[i];
  6652. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6653. const vertexNormals = face.vertexNormals;
  6654. if (vertexNormals.length === 3) {
  6655. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6656. } else {
  6657. const normal = face.normal;
  6658. this.normals.push(normal, normal, normal);
  6659. }
  6660. const vertexColors = face.vertexColors;
  6661. if (vertexColors.length === 3) {
  6662. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6663. } else {
  6664. const color = face.color;
  6665. this.colors.push(color, color, color);
  6666. }
  6667. if (hasFaceVertexUv === true) {
  6668. const vertexUvs = faceVertexUvs[0][i];
  6669. if (vertexUvs !== undefined) {
  6670. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6671. } else {
  6672. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6673. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6674. }
  6675. }
  6676. if (hasFaceVertexUv2 === true) {
  6677. const vertexUvs = faceVertexUvs[1][i];
  6678. if (vertexUvs !== undefined) {
  6679. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6680. } else {
  6681. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6682. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6683. }
  6684. } // morphs
  6685. for (let j = 0; j < morphTargetsLength; j++) {
  6686. const morphTarget = morphTargets[j].vertices;
  6687. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6688. }
  6689. for (let j = 0; j < morphNormalsLength; j++) {
  6690. const morphNormal = morphNormals[j].vertexNormals[i];
  6691. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6692. } // skins
  6693. if (hasSkinIndices) {
  6694. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6695. }
  6696. if (hasSkinWeights) {
  6697. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6698. }
  6699. }
  6700. this.computeGroups(geometry);
  6701. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6702. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6703. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6704. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6705. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6706. if (geometry.boundingSphere !== null) {
  6707. this.boundingSphere = geometry.boundingSphere.clone();
  6708. }
  6709. if (geometry.boundingBox !== null) {
  6710. this.boundingBox = geometry.boundingBox.clone();
  6711. }
  6712. return this;
  6713. }
  6714. }
  6715. function arrayMax(array) {
  6716. if (array.length === 0) return -Infinity;
  6717. let max = array[0];
  6718. for (let i = 1, l = array.length; i < l; ++i) {
  6719. if (array[i] > max) max = array[i];
  6720. }
  6721. return max;
  6722. }
  6723. const TYPED_ARRAYS = {
  6724. Int8Array: Int8Array,
  6725. Uint8Array: Uint8Array,
  6726. // Workaround for IE11 pre KB2929437. See #11440
  6727. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  6728. Int16Array: Int16Array,
  6729. Uint16Array: Uint16Array,
  6730. Int32Array: Int32Array,
  6731. Uint32Array: Uint32Array,
  6732. Float32Array: Float32Array,
  6733. Float64Array: Float64Array
  6734. };
  6735. function getTypedArray(type, buffer) {
  6736. return new TYPED_ARRAYS[type](buffer);
  6737. }
  6738. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6739. const _m1$2 = new Matrix4();
  6740. const _obj = new Object3D();
  6741. const _offset = new Vector3();
  6742. const _box$2 = new Box3();
  6743. const _boxMorphTargets = new Box3();
  6744. const _vector$4 = new Vector3();
  6745. function BufferGeometry() {
  6746. Object.defineProperty(this, 'id', {
  6747. value: _bufferGeometryId += 2
  6748. });
  6749. this.uuid = MathUtils.generateUUID();
  6750. this.name = '';
  6751. this.type = 'BufferGeometry';
  6752. this.index = null;
  6753. this.attributes = {};
  6754. this.morphAttributes = {};
  6755. this.morphTargetsRelative = false;
  6756. this.groups = [];
  6757. this.boundingBox = null;
  6758. this.boundingSphere = null;
  6759. this.drawRange = {
  6760. start: 0,
  6761. count: Infinity
  6762. };
  6763. this.userData = {};
  6764. }
  6765. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6766. constructor: BufferGeometry,
  6767. isBufferGeometry: true,
  6768. getIndex: function () {
  6769. return this.index;
  6770. },
  6771. setIndex: function (index) {
  6772. if (Array.isArray(index)) {
  6773. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6774. } else {
  6775. this.index = index;
  6776. }
  6777. return this;
  6778. },
  6779. getAttribute: function (name) {
  6780. return this.attributes[name];
  6781. },
  6782. setAttribute: function (name, attribute) {
  6783. this.attributes[name] = attribute;
  6784. return this;
  6785. },
  6786. deleteAttribute: function (name) {
  6787. delete this.attributes[name];
  6788. return this;
  6789. },
  6790. hasAttribute: function (name) {
  6791. return this.attributes[name] !== undefined;
  6792. },
  6793. addGroup: function (start, count, materialIndex = 0) {
  6794. this.groups.push({
  6795. start: start,
  6796. count: count,
  6797. materialIndex: materialIndex
  6798. });
  6799. },
  6800. clearGroups: function () {
  6801. this.groups = [];
  6802. },
  6803. setDrawRange: function (start, count) {
  6804. this.drawRange.start = start;
  6805. this.drawRange.count = count;
  6806. },
  6807. applyMatrix4: function (matrix) {
  6808. const position = this.attributes.position;
  6809. if (position !== undefined) {
  6810. position.applyMatrix4(matrix);
  6811. position.needsUpdate = true;
  6812. }
  6813. const normal = this.attributes.normal;
  6814. if (normal !== undefined) {
  6815. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6816. normal.applyNormalMatrix(normalMatrix);
  6817. normal.needsUpdate = true;
  6818. }
  6819. const tangent = this.attributes.tangent;
  6820. if (tangent !== undefined) {
  6821. tangent.transformDirection(matrix);
  6822. tangent.needsUpdate = true;
  6823. }
  6824. if (this.boundingBox !== null) {
  6825. this.computeBoundingBox();
  6826. }
  6827. if (this.boundingSphere !== null) {
  6828. this.computeBoundingSphere();
  6829. }
  6830. return this;
  6831. },
  6832. rotateX: function (angle) {
  6833. // rotate geometry around world x-axis
  6834. _m1$2.makeRotationX(angle);
  6835. this.applyMatrix4(_m1$2);
  6836. return this;
  6837. },
  6838. rotateY: function (angle) {
  6839. // rotate geometry around world y-axis
  6840. _m1$2.makeRotationY(angle);
  6841. this.applyMatrix4(_m1$2);
  6842. return this;
  6843. },
  6844. rotateZ: function (angle) {
  6845. // rotate geometry around world z-axis
  6846. _m1$2.makeRotationZ(angle);
  6847. this.applyMatrix4(_m1$2);
  6848. return this;
  6849. },
  6850. translate: function (x, y, z) {
  6851. // translate geometry
  6852. _m1$2.makeTranslation(x, y, z);
  6853. this.applyMatrix4(_m1$2);
  6854. return this;
  6855. },
  6856. scale: function (x, y, z) {
  6857. // scale geometry
  6858. _m1$2.makeScale(x, y, z);
  6859. this.applyMatrix4(_m1$2);
  6860. return this;
  6861. },
  6862. lookAt: function (vector) {
  6863. _obj.lookAt(vector);
  6864. _obj.updateMatrix();
  6865. this.applyMatrix4(_obj.matrix);
  6866. return this;
  6867. },
  6868. center: function () {
  6869. this.computeBoundingBox();
  6870. this.boundingBox.getCenter(_offset).negate();
  6871. this.translate(_offset.x, _offset.y, _offset.z);
  6872. return this;
  6873. },
  6874. setFromObject: function (object) {
  6875. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6876. const geometry = object.geometry;
  6877. if (object.isPoints || object.isLine) {
  6878. const positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6879. const colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6880. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6881. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  6882. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6883. const lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6884. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6885. }
  6886. if (geometry.boundingSphere !== null) {
  6887. this.boundingSphere = geometry.boundingSphere.clone();
  6888. }
  6889. if (geometry.boundingBox !== null) {
  6890. this.boundingBox = geometry.boundingBox.clone();
  6891. }
  6892. } else if (object.isMesh) {
  6893. if (geometry && geometry.isGeometry) {
  6894. this.fromGeometry(geometry);
  6895. }
  6896. }
  6897. return this;
  6898. },
  6899. setFromPoints: function (points) {
  6900. const position = [];
  6901. for (let i = 0, l = points.length; i < l; i++) {
  6902. const point = points[i];
  6903. position.push(point.x, point.y, point.z || 0);
  6904. }
  6905. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6906. return this;
  6907. },
  6908. updateFromObject: function (object) {
  6909. let geometry = object.geometry;
  6910. if (object.isMesh) {
  6911. let direct = geometry.__directGeometry;
  6912. if (geometry.elementsNeedUpdate === true) {
  6913. direct = undefined;
  6914. geometry.elementsNeedUpdate = false;
  6915. }
  6916. if (direct === undefined) {
  6917. return this.fromGeometry(geometry);
  6918. }
  6919. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6920. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6921. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6922. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6923. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6924. geometry.verticesNeedUpdate = false;
  6925. geometry.normalsNeedUpdate = false;
  6926. geometry.colorsNeedUpdate = false;
  6927. geometry.uvsNeedUpdate = false;
  6928. geometry.groupsNeedUpdate = false;
  6929. geometry = direct;
  6930. }
  6931. if (geometry.verticesNeedUpdate === true) {
  6932. const attribute = this.attributes.position;
  6933. if (attribute !== undefined) {
  6934. attribute.copyVector3sArray(geometry.vertices);
  6935. attribute.needsUpdate = true;
  6936. }
  6937. geometry.verticesNeedUpdate = false;
  6938. }
  6939. if (geometry.normalsNeedUpdate === true) {
  6940. const attribute = this.attributes.normal;
  6941. if (attribute !== undefined) {
  6942. attribute.copyVector3sArray(geometry.normals);
  6943. attribute.needsUpdate = true;
  6944. }
  6945. geometry.normalsNeedUpdate = false;
  6946. }
  6947. if (geometry.colorsNeedUpdate === true) {
  6948. const attribute = this.attributes.color;
  6949. if (attribute !== undefined) {
  6950. attribute.copyColorsArray(geometry.colors);
  6951. attribute.needsUpdate = true;
  6952. }
  6953. geometry.colorsNeedUpdate = false;
  6954. }
  6955. if (geometry.uvsNeedUpdate) {
  6956. const attribute = this.attributes.uv;
  6957. if (attribute !== undefined) {
  6958. attribute.copyVector2sArray(geometry.uvs);
  6959. attribute.needsUpdate = true;
  6960. }
  6961. geometry.uvsNeedUpdate = false;
  6962. }
  6963. if (geometry.lineDistancesNeedUpdate) {
  6964. const attribute = this.attributes.lineDistance;
  6965. if (attribute !== undefined) {
  6966. attribute.copyArray(geometry.lineDistances);
  6967. attribute.needsUpdate = true;
  6968. }
  6969. geometry.lineDistancesNeedUpdate = false;
  6970. }
  6971. if (geometry.groupsNeedUpdate) {
  6972. geometry.computeGroups(object.geometry);
  6973. this.groups = geometry.groups;
  6974. geometry.groupsNeedUpdate = false;
  6975. }
  6976. return this;
  6977. },
  6978. fromGeometry: function (geometry) {
  6979. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  6980. return this.fromDirectGeometry(geometry.__directGeometry);
  6981. },
  6982. fromDirectGeometry: function (geometry) {
  6983. const positions = new Float32Array(geometry.vertices.length * 3);
  6984. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  6985. if (geometry.normals.length > 0) {
  6986. const normals = new Float32Array(geometry.normals.length * 3);
  6987. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  6988. }
  6989. if (geometry.colors.length > 0) {
  6990. const colors = new Float32Array(geometry.colors.length * 3);
  6991. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  6992. }
  6993. if (geometry.uvs.length > 0) {
  6994. const uvs = new Float32Array(geometry.uvs.length * 2);
  6995. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  6996. }
  6997. if (geometry.uvs2.length > 0) {
  6998. const uvs2 = new Float32Array(geometry.uvs2.length * 2);
  6999. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7000. } // groups
  7001. this.groups = geometry.groups; // morphs
  7002. for (const name in geometry.morphTargets) {
  7003. const array = [];
  7004. const morphTargets = geometry.morphTargets[name];
  7005. for (let i = 0, l = morphTargets.length; i < l; i++) {
  7006. const morphTarget = morphTargets[i];
  7007. const attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7008. attribute.name = morphTarget.name;
  7009. array.push(attribute.copyVector3sArray(morphTarget.data));
  7010. }
  7011. this.morphAttributes[name] = array;
  7012. } // skinning
  7013. if (geometry.skinIndices.length > 0) {
  7014. const skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7015. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7016. }
  7017. if (geometry.skinWeights.length > 0) {
  7018. const skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7019. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7020. } //
  7021. if (geometry.boundingSphere !== null) {
  7022. this.boundingSphere = geometry.boundingSphere.clone();
  7023. }
  7024. if (geometry.boundingBox !== null) {
  7025. this.boundingBox = geometry.boundingBox.clone();
  7026. }
  7027. return this;
  7028. },
  7029. computeBoundingBox: function () {
  7030. if (this.boundingBox === null) {
  7031. this.boundingBox = new Box3();
  7032. }
  7033. const position = this.attributes.position;
  7034. const morphAttributesPosition = this.morphAttributes.position;
  7035. if (position && position.isGLBufferAttribute) {
  7036. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  7037. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  7038. return;
  7039. }
  7040. if (position !== undefined) {
  7041. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7042. if (morphAttributesPosition) {
  7043. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7044. const morphAttribute = morphAttributesPosition[i];
  7045. _box$2.setFromBufferAttribute(morphAttribute);
  7046. if (this.morphTargetsRelative) {
  7047. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  7048. this.boundingBox.expandByPoint(_vector$4);
  7049. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  7050. this.boundingBox.expandByPoint(_vector$4);
  7051. } else {
  7052. this.boundingBox.expandByPoint(_box$2.min);
  7053. this.boundingBox.expandByPoint(_box$2.max);
  7054. }
  7055. }
  7056. }
  7057. } else {
  7058. this.boundingBox.makeEmpty();
  7059. }
  7060. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7061. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7062. }
  7063. },
  7064. computeBoundingSphere: function () {
  7065. if (this.boundingSphere === null) {
  7066. this.boundingSphere = new Sphere();
  7067. }
  7068. const position = this.attributes.position;
  7069. const morphAttributesPosition = this.morphAttributes.position;
  7070. if (position && position.isGLBufferAttribute) {
  7071. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  7072. this.boundingSphere.set(new Vector3(), Infinity);
  7073. return;
  7074. }
  7075. if (position) {
  7076. // first, find the center of the bounding sphere
  7077. const center = this.boundingSphere.center;
  7078. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  7079. if (morphAttributesPosition) {
  7080. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7081. const morphAttribute = morphAttributesPosition[i];
  7082. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7083. if (this.morphTargetsRelative) {
  7084. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  7085. _box$2.expandByPoint(_vector$4);
  7086. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  7087. _box$2.expandByPoint(_vector$4);
  7088. } else {
  7089. _box$2.expandByPoint(_boxMorphTargets.min);
  7090. _box$2.expandByPoint(_boxMorphTargets.max);
  7091. }
  7092. }
  7093. }
  7094. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7095. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7096. let maxRadiusSq = 0;
  7097. for (let i = 0, il = position.count; i < il; i++) {
  7098. _vector$4.fromBufferAttribute(position, i);
  7099. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7100. } // process morph attributes if present
  7101. if (morphAttributesPosition) {
  7102. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7103. const morphAttribute = morphAttributesPosition[i];
  7104. const morphTargetsRelative = this.morphTargetsRelative;
  7105. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  7106. _vector$4.fromBufferAttribute(morphAttribute, j);
  7107. if (morphTargetsRelative) {
  7108. _offset.fromBufferAttribute(position, j);
  7109. _vector$4.add(_offset);
  7110. }
  7111. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7112. }
  7113. }
  7114. }
  7115. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7116. if (isNaN(this.boundingSphere.radius)) {
  7117. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7118. }
  7119. }
  7120. },
  7121. computeFaceNormals: function () {// backwards compatibility
  7122. },
  7123. computeVertexNormals: function () {
  7124. const index = this.index;
  7125. const positionAttribute = this.getAttribute('position');
  7126. if (positionAttribute !== undefined) {
  7127. let normalAttribute = this.getAttribute('normal');
  7128. if (normalAttribute === undefined) {
  7129. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  7130. this.setAttribute('normal', normalAttribute);
  7131. } else {
  7132. // reset existing normals to zero
  7133. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  7134. normalAttribute.setXYZ(i, 0, 0, 0);
  7135. }
  7136. }
  7137. const pA = new Vector3(),
  7138. pB = new Vector3(),
  7139. pC = new Vector3();
  7140. const nA = new Vector3(),
  7141. nB = new Vector3(),
  7142. nC = new Vector3();
  7143. const cb = new Vector3(),
  7144. ab = new Vector3(); // indexed elements
  7145. if (index) {
  7146. for (let i = 0, il = index.count; i < il; i += 3) {
  7147. const vA = index.getX(i + 0);
  7148. const vB = index.getX(i + 1);
  7149. const vC = index.getX(i + 2);
  7150. pA.fromBufferAttribute(positionAttribute, vA);
  7151. pB.fromBufferAttribute(positionAttribute, vB);
  7152. pC.fromBufferAttribute(positionAttribute, vC);
  7153. cb.subVectors(pC, pB);
  7154. ab.subVectors(pA, pB);
  7155. cb.cross(ab);
  7156. nA.fromBufferAttribute(normalAttribute, vA);
  7157. nB.fromBufferAttribute(normalAttribute, vB);
  7158. nC.fromBufferAttribute(normalAttribute, vC);
  7159. nA.add(cb);
  7160. nB.add(cb);
  7161. nC.add(cb);
  7162. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  7163. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  7164. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  7165. }
  7166. } else {
  7167. // non-indexed elements (unconnected triangle soup)
  7168. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  7169. pA.fromBufferAttribute(positionAttribute, i + 0);
  7170. pB.fromBufferAttribute(positionAttribute, i + 1);
  7171. pC.fromBufferAttribute(positionAttribute, i + 2);
  7172. cb.subVectors(pC, pB);
  7173. ab.subVectors(pA, pB);
  7174. cb.cross(ab);
  7175. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  7176. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  7177. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  7178. }
  7179. }
  7180. this.normalizeNormals();
  7181. normalAttribute.needsUpdate = true;
  7182. }
  7183. },
  7184. merge: function (geometry, offset) {
  7185. if (!(geometry && geometry.isBufferGeometry)) {
  7186. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  7187. return;
  7188. }
  7189. if (offset === undefined) {
  7190. offset = 0;
  7191. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  7192. }
  7193. const attributes = this.attributes;
  7194. for (const key in attributes) {
  7195. if (geometry.attributes[key] === undefined) continue;
  7196. const attribute1 = attributes[key];
  7197. const attributeArray1 = attribute1.array;
  7198. const attribute2 = geometry.attributes[key];
  7199. const attributeArray2 = attribute2.array;
  7200. const attributeOffset = attribute2.itemSize * offset;
  7201. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  7202. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  7203. attributeArray1[j] = attributeArray2[i];
  7204. }
  7205. }
  7206. return this;
  7207. },
  7208. normalizeNormals: function () {
  7209. const normals = this.attributes.normal;
  7210. for (let i = 0, il = normals.count; i < il; i++) {
  7211. _vector$4.fromBufferAttribute(normals, i);
  7212. _vector$4.normalize();
  7213. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7214. }
  7215. },
  7216. toNonIndexed: function () {
  7217. function convertBufferAttribute(attribute, indices) {
  7218. const array = attribute.array;
  7219. const itemSize = attribute.itemSize;
  7220. const normalized = attribute.normalized;
  7221. const array2 = new array.constructor(indices.length * itemSize);
  7222. let index = 0,
  7223. index2 = 0;
  7224. for (let i = 0, l = indices.length; i < l; i++) {
  7225. index = indices[i] * itemSize;
  7226. for (let j = 0; j < itemSize; j++) {
  7227. array2[index2++] = array[index++];
  7228. }
  7229. }
  7230. return new BufferAttribute(array2, itemSize, normalized);
  7231. } //
  7232. if (this.index === null) {
  7233. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7234. return this;
  7235. }
  7236. const geometry2 = new BufferGeometry();
  7237. const indices = this.index.array;
  7238. const attributes = this.attributes; // attributes
  7239. for (const name in attributes) {
  7240. const attribute = attributes[name];
  7241. const newAttribute = convertBufferAttribute(attribute, indices);
  7242. geometry2.setAttribute(name, newAttribute);
  7243. } // morph attributes
  7244. const morphAttributes = this.morphAttributes;
  7245. for (const name in morphAttributes) {
  7246. const morphArray = [];
  7247. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7248. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  7249. const attribute = morphAttribute[i];
  7250. const newAttribute = convertBufferAttribute(attribute, indices);
  7251. morphArray.push(newAttribute);
  7252. }
  7253. geometry2.morphAttributes[name] = morphArray;
  7254. }
  7255. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  7256. const groups = this.groups;
  7257. for (let i = 0, l = groups.length; i < l; i++) {
  7258. const group = groups[i];
  7259. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7260. }
  7261. return geometry2;
  7262. },
  7263. toJSON: function () {
  7264. const data = {
  7265. metadata: {
  7266. version: 4.5,
  7267. type: 'BufferGeometry',
  7268. generator: 'BufferGeometry.toJSON'
  7269. }
  7270. }; // standard BufferGeometry serialization
  7271. data.uuid = this.uuid;
  7272. data.type = this.type;
  7273. if (this.name !== '') data.name = this.name;
  7274. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7275. if (this.parameters !== undefined) {
  7276. const parameters = this.parameters;
  7277. for (const key in parameters) {
  7278. if (parameters[key] !== undefined) data[key] = parameters[key];
  7279. }
  7280. return data;
  7281. }
  7282. data.data = {
  7283. attributes: {}
  7284. };
  7285. const index = this.index;
  7286. if (index !== null) {
  7287. data.data.index = {
  7288. type: index.array.constructor.name,
  7289. array: Array.prototype.slice.call(index.array)
  7290. };
  7291. }
  7292. const attributes = this.attributes;
  7293. for (const key in attributes) {
  7294. const attribute = attributes[key];
  7295. const attributeData = attribute.toJSON(data.data);
  7296. if (attribute.name !== '') attributeData.name = attribute.name;
  7297. data.data.attributes[key] = attributeData;
  7298. }
  7299. const morphAttributes = {};
  7300. let hasMorphAttributes = false;
  7301. for (const key in this.morphAttributes) {
  7302. const attributeArray = this.morphAttributes[key];
  7303. const array = [];
  7304. for (let i = 0, il = attributeArray.length; i < il; i++) {
  7305. const attribute = attributeArray[i];
  7306. const attributeData = attribute.toJSON(data.data);
  7307. if (attribute.name !== '') attributeData.name = attribute.name;
  7308. array.push(attributeData);
  7309. }
  7310. if (array.length > 0) {
  7311. morphAttributes[key] = array;
  7312. hasMorphAttributes = true;
  7313. }
  7314. }
  7315. if (hasMorphAttributes) {
  7316. data.data.morphAttributes = morphAttributes;
  7317. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7318. }
  7319. const groups = this.groups;
  7320. if (groups.length > 0) {
  7321. data.data.groups = JSON.parse(JSON.stringify(groups));
  7322. }
  7323. const boundingSphere = this.boundingSphere;
  7324. if (boundingSphere !== null) {
  7325. data.data.boundingSphere = {
  7326. center: boundingSphere.center.toArray(),
  7327. radius: boundingSphere.radius
  7328. };
  7329. }
  7330. return data;
  7331. },
  7332. clone: function () {
  7333. /*
  7334. // Handle primitives
  7335. const parameters = this.parameters;
  7336. if ( parameters !== undefined ) {
  7337. const values = [];
  7338. for ( const key in parameters ) {
  7339. values.push( parameters[ key ] );
  7340. }
  7341. const geometry = Object.create( this.constructor.prototype );
  7342. this.constructor.apply( geometry, values );
  7343. return geometry;
  7344. }
  7345. return new this.constructor().copy( this );
  7346. */
  7347. return new BufferGeometry().copy(this);
  7348. },
  7349. copy: function (source) {
  7350. // reset
  7351. this.index = null;
  7352. this.attributes = {};
  7353. this.morphAttributes = {};
  7354. this.groups = [];
  7355. this.boundingBox = null;
  7356. this.boundingSphere = null; // used for storing cloned, shared data
  7357. const data = {}; // name
  7358. this.name = source.name; // index
  7359. const index = source.index;
  7360. if (index !== null) {
  7361. this.setIndex(index.clone(data));
  7362. } // attributes
  7363. const attributes = source.attributes;
  7364. for (const name in attributes) {
  7365. const attribute = attributes[name];
  7366. this.setAttribute(name, attribute.clone(data));
  7367. } // morph attributes
  7368. const morphAttributes = source.morphAttributes;
  7369. for (const name in morphAttributes) {
  7370. const array = [];
  7371. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7372. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  7373. array.push(morphAttribute[i].clone(data));
  7374. }
  7375. this.morphAttributes[name] = array;
  7376. }
  7377. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  7378. const groups = source.groups;
  7379. for (let i = 0, l = groups.length; i < l; i++) {
  7380. const group = groups[i];
  7381. this.addGroup(group.start, group.count, group.materialIndex);
  7382. } // bounding box
  7383. const boundingBox = source.boundingBox;
  7384. if (boundingBox !== null) {
  7385. this.boundingBox = boundingBox.clone();
  7386. } // bounding sphere
  7387. const boundingSphere = source.boundingSphere;
  7388. if (boundingSphere !== null) {
  7389. this.boundingSphere = boundingSphere.clone();
  7390. } // draw range
  7391. this.drawRange.start = source.drawRange.start;
  7392. this.drawRange.count = source.drawRange.count; // user data
  7393. this.userData = source.userData;
  7394. return this;
  7395. },
  7396. dispose: function () {
  7397. this.dispatchEvent({
  7398. type: 'dispose'
  7399. });
  7400. }
  7401. });
  7402. const _inverseMatrix = new Matrix4();
  7403. const _ray = new Ray();
  7404. const _sphere = new Sphere();
  7405. const _vA = new Vector3();
  7406. const _vB = new Vector3();
  7407. const _vC = new Vector3();
  7408. const _tempA = new Vector3();
  7409. const _tempB = new Vector3();
  7410. const _tempC = new Vector3();
  7411. const _morphA = new Vector3();
  7412. const _morphB = new Vector3();
  7413. const _morphC = new Vector3();
  7414. const _uvA = new Vector2();
  7415. const _uvB = new Vector2();
  7416. const _uvC = new Vector2();
  7417. const _intersectionPoint = new Vector3();
  7418. const _intersectionPointWorld = new Vector3();
  7419. function Mesh(geometry, material) {
  7420. Object3D.call(this);
  7421. this.type = 'Mesh';
  7422. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7423. this.material = material !== undefined ? material : new MeshBasicMaterial();
  7424. this.updateMorphTargets();
  7425. }
  7426. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7427. constructor: Mesh,
  7428. isMesh: true,
  7429. copy: function (source) {
  7430. Object3D.prototype.copy.call(this, source);
  7431. if (source.morphTargetInfluences !== undefined) {
  7432. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7433. }
  7434. if (source.morphTargetDictionary !== undefined) {
  7435. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7436. }
  7437. this.material = source.material;
  7438. this.geometry = source.geometry;
  7439. return this;
  7440. },
  7441. updateMorphTargets: function () {
  7442. const geometry = this.geometry;
  7443. if (geometry.isBufferGeometry) {
  7444. const morphAttributes = geometry.morphAttributes;
  7445. const keys = Object.keys(morphAttributes);
  7446. if (keys.length > 0) {
  7447. const morphAttribute = morphAttributes[keys[0]];
  7448. if (morphAttribute !== undefined) {
  7449. this.morphTargetInfluences = [];
  7450. this.morphTargetDictionary = {};
  7451. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  7452. const name = morphAttribute[m].name || String(m);
  7453. this.morphTargetInfluences.push(0);
  7454. this.morphTargetDictionary[name] = m;
  7455. }
  7456. }
  7457. }
  7458. } else {
  7459. const morphTargets = geometry.morphTargets;
  7460. if (morphTargets !== undefined && morphTargets.length > 0) {
  7461. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7462. }
  7463. }
  7464. },
  7465. raycast: function (raycaster, intersects) {
  7466. const geometry = this.geometry;
  7467. const material = this.material;
  7468. const matrixWorld = this.matrixWorld;
  7469. if (material === undefined) return; // Checking boundingSphere distance to ray
  7470. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7471. _sphere.copy(geometry.boundingSphere);
  7472. _sphere.applyMatrix4(matrixWorld);
  7473. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7474. _inverseMatrix.copy(matrixWorld).invert();
  7475. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7476. if (geometry.boundingBox !== null) {
  7477. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7478. }
  7479. let intersection;
  7480. if (geometry.isBufferGeometry) {
  7481. const index = geometry.index;
  7482. const position = geometry.attributes.position;
  7483. const morphPosition = geometry.morphAttributes.position;
  7484. const morphTargetsRelative = geometry.morphTargetsRelative;
  7485. const uv = geometry.attributes.uv;
  7486. const uv2 = geometry.attributes.uv2;
  7487. const groups = geometry.groups;
  7488. const drawRange = geometry.drawRange;
  7489. if (index !== null) {
  7490. // indexed buffer geometry
  7491. if (Array.isArray(material)) {
  7492. for (let i = 0, il = groups.length; i < il; i++) {
  7493. const group = groups[i];
  7494. const groupMaterial = material[group.materialIndex];
  7495. const start = Math.max(group.start, drawRange.start);
  7496. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7497. for (let j = start, jl = end; j < jl; j += 3) {
  7498. const a = index.getX(j);
  7499. const b = index.getX(j + 1);
  7500. const c = index.getX(j + 2);
  7501. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7502. if (intersection) {
  7503. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7504. intersection.face.materialIndex = group.materialIndex;
  7505. intersects.push(intersection);
  7506. }
  7507. }
  7508. }
  7509. } else {
  7510. const start = Math.max(0, drawRange.start);
  7511. const end = Math.min(index.count, drawRange.start + drawRange.count);
  7512. for (let i = start, il = end; i < il; i += 3) {
  7513. const a = index.getX(i);
  7514. const b = index.getX(i + 1);
  7515. const c = index.getX(i + 2);
  7516. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7517. if (intersection) {
  7518. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7519. intersects.push(intersection);
  7520. }
  7521. }
  7522. }
  7523. } else if (position !== undefined) {
  7524. // non-indexed buffer geometry
  7525. if (Array.isArray(material)) {
  7526. for (let i = 0, il = groups.length; i < il; i++) {
  7527. const group = groups[i];
  7528. const groupMaterial = material[group.materialIndex];
  7529. const start = Math.max(group.start, drawRange.start);
  7530. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7531. for (let j = start, jl = end; j < jl; j += 3) {
  7532. const a = j;
  7533. const b = j + 1;
  7534. const c = j + 2;
  7535. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7536. if (intersection) {
  7537. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7538. intersection.face.materialIndex = group.materialIndex;
  7539. intersects.push(intersection);
  7540. }
  7541. }
  7542. }
  7543. } else {
  7544. const start = Math.max(0, drawRange.start);
  7545. const end = Math.min(position.count, drawRange.start + drawRange.count);
  7546. for (let i = start, il = end; i < il; i += 3) {
  7547. const a = i;
  7548. const b = i + 1;
  7549. const c = i + 2;
  7550. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7551. if (intersection) {
  7552. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7553. intersects.push(intersection);
  7554. }
  7555. }
  7556. }
  7557. }
  7558. } else if (geometry.isGeometry) {
  7559. const isMultiMaterial = Array.isArray(material);
  7560. const vertices = geometry.vertices;
  7561. const faces = geometry.faces;
  7562. let uvs;
  7563. const faceVertexUvs = geometry.faceVertexUvs[0];
  7564. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7565. for (let f = 0, fl = faces.length; f < fl; f++) {
  7566. const face = faces[f];
  7567. const faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7568. if (faceMaterial === undefined) continue;
  7569. const fvA = vertices[face.a];
  7570. const fvB = vertices[face.b];
  7571. const fvC = vertices[face.c];
  7572. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7573. if (intersection) {
  7574. if (uvs && uvs[f]) {
  7575. const uvs_f = uvs[f];
  7576. _uvA.copy(uvs_f[0]);
  7577. _uvB.copy(uvs_f[1]);
  7578. _uvC.copy(uvs_f[2]);
  7579. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7580. }
  7581. intersection.face = face;
  7582. intersection.faceIndex = f;
  7583. intersects.push(intersection);
  7584. }
  7585. }
  7586. }
  7587. }
  7588. });
  7589. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7590. let intersect;
  7591. if (material.side === BackSide) {
  7592. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7593. } else {
  7594. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7595. }
  7596. if (intersect === null) return null;
  7597. _intersectionPointWorld.copy(point);
  7598. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7599. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7600. if (distance < raycaster.near || distance > raycaster.far) return null;
  7601. return {
  7602. distance: distance,
  7603. point: _intersectionPointWorld.clone(),
  7604. object: object
  7605. };
  7606. }
  7607. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  7608. _vA.fromBufferAttribute(position, a);
  7609. _vB.fromBufferAttribute(position, b);
  7610. _vC.fromBufferAttribute(position, c);
  7611. const morphInfluences = object.morphTargetInfluences;
  7612. if (material.morphTargets && morphPosition && morphInfluences) {
  7613. _morphA.set(0, 0, 0);
  7614. _morphB.set(0, 0, 0);
  7615. _morphC.set(0, 0, 0);
  7616. for (let i = 0, il = morphPosition.length; i < il; i++) {
  7617. const influence = morphInfluences[i];
  7618. const morphAttribute = morphPosition[i];
  7619. if (influence === 0) continue;
  7620. _tempA.fromBufferAttribute(morphAttribute, a);
  7621. _tempB.fromBufferAttribute(morphAttribute, b);
  7622. _tempC.fromBufferAttribute(morphAttribute, c);
  7623. if (morphTargetsRelative) {
  7624. _morphA.addScaledVector(_tempA, influence);
  7625. _morphB.addScaledVector(_tempB, influence);
  7626. _morphC.addScaledVector(_tempC, influence);
  7627. } else {
  7628. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7629. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7630. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7631. }
  7632. }
  7633. _vA.add(_morphA);
  7634. _vB.add(_morphB);
  7635. _vC.add(_morphC);
  7636. }
  7637. if (object.isSkinnedMesh) {
  7638. object.boneTransform(a, _vA);
  7639. object.boneTransform(b, _vB);
  7640. object.boneTransform(c, _vC);
  7641. }
  7642. const intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7643. if (intersection) {
  7644. if (uv) {
  7645. _uvA.fromBufferAttribute(uv, a);
  7646. _uvB.fromBufferAttribute(uv, b);
  7647. _uvC.fromBufferAttribute(uv, c);
  7648. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7649. }
  7650. if (uv2) {
  7651. _uvA.fromBufferAttribute(uv2, a);
  7652. _uvB.fromBufferAttribute(uv2, b);
  7653. _uvC.fromBufferAttribute(uv2, c);
  7654. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7655. }
  7656. const face = new Face3(a, b, c);
  7657. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7658. intersection.face = face;
  7659. }
  7660. return intersection;
  7661. }
  7662. class BoxBufferGeometry extends BufferGeometry {
  7663. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  7664. super();
  7665. this.type = 'BoxBufferGeometry';
  7666. this.parameters = {
  7667. width: width,
  7668. height: height,
  7669. depth: depth,
  7670. widthSegments: widthSegments,
  7671. heightSegments: heightSegments,
  7672. depthSegments: depthSegments
  7673. };
  7674. const scope = this; // segments
  7675. widthSegments = Math.floor(widthSegments);
  7676. heightSegments = Math.floor(heightSegments);
  7677. depthSegments = Math.floor(depthSegments); // buffers
  7678. const indices = [];
  7679. const vertices = [];
  7680. const normals = [];
  7681. const uvs = []; // helper variables
  7682. let numberOfVertices = 0;
  7683. let groupStart = 0; // build each side of the box geometry
  7684. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7685. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7686. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7687. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7688. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7689. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7690. // build geometry
  7691. this.setIndex(indices);
  7692. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7693. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7694. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7695. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7696. const segmentWidth = width / gridX;
  7697. const segmentHeight = height / gridY;
  7698. const widthHalf = width / 2;
  7699. const heightHalf = height / 2;
  7700. const depthHalf = depth / 2;
  7701. const gridX1 = gridX + 1;
  7702. const gridY1 = gridY + 1;
  7703. let vertexCounter = 0;
  7704. let groupCount = 0;
  7705. const vector = new Vector3(); // generate vertices, normals and uvs
  7706. for (let iy = 0; iy < gridY1; iy++) {
  7707. const y = iy * segmentHeight - heightHalf;
  7708. for (let ix = 0; ix < gridX1; ix++) {
  7709. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7710. vector[u] = x * udir;
  7711. vector[v] = y * vdir;
  7712. vector[w] = depthHalf; // now apply vector to vertex buffer
  7713. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7714. vector[u] = 0;
  7715. vector[v] = 0;
  7716. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7717. normals.push(vector.x, vector.y, vector.z); // uvs
  7718. uvs.push(ix / gridX);
  7719. uvs.push(1 - iy / gridY); // counters
  7720. vertexCounter += 1;
  7721. }
  7722. } // indices
  7723. // 1. you need three indices to draw a single face
  7724. // 2. a single segment consists of two faces
  7725. // 3. so we need to generate six (2*3) indices per segment
  7726. for (let iy = 0; iy < gridY; iy++) {
  7727. for (let ix = 0; ix < gridX; ix++) {
  7728. const a = numberOfVertices + ix + gridX1 * iy;
  7729. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7730. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7731. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7732. indices.push(a, b, d);
  7733. indices.push(b, c, d); // increase counter
  7734. groupCount += 6;
  7735. }
  7736. } // add a group to the geometry. this will ensure multi material support
  7737. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7738. groupStart += groupCount; // update total number of vertices
  7739. numberOfVertices += vertexCounter;
  7740. }
  7741. }
  7742. }
  7743. /**
  7744. * Uniform Utilities
  7745. */
  7746. exports.BoxBufferGeometry = BoxBufferGeometry;
  7747. function cloneUniforms(src) {
  7748. const dst = {};
  7749. for (const u in src) {
  7750. dst[u] = {};
  7751. for (const p in src[u]) {
  7752. const property = src[u][p];
  7753. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  7754. dst[u][p] = property.clone();
  7755. } else if (Array.isArray(property)) {
  7756. dst[u][p] = property.slice();
  7757. } else {
  7758. dst[u][p] = property;
  7759. }
  7760. }
  7761. }
  7762. return dst;
  7763. }
  7764. function mergeUniforms(uniforms) {
  7765. const merged = {};
  7766. for (let u = 0; u < uniforms.length; u++) {
  7767. const tmp = cloneUniforms(uniforms[u]);
  7768. for (const p in tmp) {
  7769. merged[p] = tmp[p];
  7770. }
  7771. }
  7772. return merged;
  7773. } // Legacy
  7774. const UniformsUtils = {
  7775. clone: cloneUniforms,
  7776. merge: mergeUniforms
  7777. };
  7778. exports.UniformsUtils = UniformsUtils;
  7779. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7780. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7781. /**
  7782. * parameters = {
  7783. * defines: { "label" : "value" },
  7784. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7785. *
  7786. * fragmentShader: <string>,
  7787. * vertexShader: <string>,
  7788. *
  7789. * wireframe: <boolean>,
  7790. * wireframeLinewidth: <float>,
  7791. *
  7792. * lights: <bool>,
  7793. *
  7794. * skinning: <bool>,
  7795. * morphTargets: <bool>,
  7796. * morphNormals: <bool>
  7797. * }
  7798. */
  7799. function ShaderMaterial(parameters) {
  7800. Material.call(this);
  7801. this.type = 'ShaderMaterial';
  7802. this.defines = {};
  7803. this.uniforms = {};
  7804. this.vertexShader = default_vertex;
  7805. this.fragmentShader = default_fragment;
  7806. this.linewidth = 1;
  7807. this.wireframe = false;
  7808. this.wireframeLinewidth = 1;
  7809. this.fog = false; // set to use scene fog
  7810. this.lights = false; // set to use scene lights
  7811. this.clipping = false; // set to use user-defined clipping planes
  7812. this.skinning = false; // set to use skinning attribute streams
  7813. this.morphTargets = false; // set to use morph targets
  7814. this.morphNormals = false; // set to use morph normals
  7815. this.extensions = {
  7816. derivatives: false,
  7817. // set to use derivatives
  7818. fragDepth: false,
  7819. // set to use fragment depth values
  7820. drawBuffers: false,
  7821. // set to use draw buffers
  7822. shaderTextureLOD: false // set to use shader texture LOD
  7823. }; // When rendered geometry doesn't include these attributes but the material does,
  7824. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7825. this.defaultAttributeValues = {
  7826. 'color': [1, 1, 1],
  7827. 'uv': [0, 0],
  7828. 'uv2': [0, 0]
  7829. };
  7830. this.index0AttributeName = undefined;
  7831. this.uniformsNeedUpdate = false;
  7832. this.glslVersion = null;
  7833. if (parameters !== undefined) {
  7834. if (parameters.attributes !== undefined) {
  7835. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7836. }
  7837. this.setValues(parameters);
  7838. }
  7839. }
  7840. ShaderMaterial.prototype = Object.create(Material.prototype);
  7841. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7842. ShaderMaterial.prototype.isShaderMaterial = true;
  7843. ShaderMaterial.prototype.copy = function (source) {
  7844. Material.prototype.copy.call(this, source);
  7845. this.fragmentShader = source.fragmentShader;
  7846. this.vertexShader = source.vertexShader;
  7847. this.uniforms = cloneUniforms(source.uniforms);
  7848. this.defines = Object.assign({}, source.defines);
  7849. this.wireframe = source.wireframe;
  7850. this.wireframeLinewidth = source.wireframeLinewidth;
  7851. this.lights = source.lights;
  7852. this.clipping = source.clipping;
  7853. this.skinning = source.skinning;
  7854. this.morphTargets = source.morphTargets;
  7855. this.morphNormals = source.morphNormals;
  7856. this.extensions = Object.assign({}, source.extensions);
  7857. this.glslVersion = source.glslVersion;
  7858. return this;
  7859. };
  7860. ShaderMaterial.prototype.toJSON = function (meta) {
  7861. const data = Material.prototype.toJSON.call(this, meta);
  7862. data.glslVersion = this.glslVersion;
  7863. data.uniforms = {};
  7864. for (const name in this.uniforms) {
  7865. const uniform = this.uniforms[name];
  7866. const value = uniform.value;
  7867. if (value && value.isTexture) {
  7868. data.uniforms[name] = {
  7869. type: 't',
  7870. value: value.toJSON(meta).uuid
  7871. };
  7872. } else if (value && value.isColor) {
  7873. data.uniforms[name] = {
  7874. type: 'c',
  7875. value: value.getHex()
  7876. };
  7877. } else if (value && value.isVector2) {
  7878. data.uniforms[name] = {
  7879. type: 'v2',
  7880. value: value.toArray()
  7881. };
  7882. } else if (value && value.isVector3) {
  7883. data.uniforms[name] = {
  7884. type: 'v3',
  7885. value: value.toArray()
  7886. };
  7887. } else if (value && value.isVector4) {
  7888. data.uniforms[name] = {
  7889. type: 'v4',
  7890. value: value.toArray()
  7891. };
  7892. } else if (value && value.isMatrix3) {
  7893. data.uniforms[name] = {
  7894. type: 'm3',
  7895. value: value.toArray()
  7896. };
  7897. } else if (value && value.isMatrix4) {
  7898. data.uniforms[name] = {
  7899. type: 'm4',
  7900. value: value.toArray()
  7901. };
  7902. } else {
  7903. data.uniforms[name] = {
  7904. value: value
  7905. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7906. }
  7907. }
  7908. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7909. data.vertexShader = this.vertexShader;
  7910. data.fragmentShader = this.fragmentShader;
  7911. const extensions = {};
  7912. for (const key in this.extensions) {
  7913. if (this.extensions[key] === true) extensions[key] = true;
  7914. }
  7915. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7916. return data;
  7917. };
  7918. function Camera() {
  7919. Object3D.call(this);
  7920. this.type = 'Camera';
  7921. this.matrixWorldInverse = new Matrix4();
  7922. this.projectionMatrix = new Matrix4();
  7923. this.projectionMatrixInverse = new Matrix4();
  7924. }
  7925. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  7926. constructor: Camera,
  7927. isCamera: true,
  7928. copy: function (source, recursive) {
  7929. Object3D.prototype.copy.call(this, source, recursive);
  7930. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7931. this.projectionMatrix.copy(source.projectionMatrix);
  7932. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7933. return this;
  7934. },
  7935. getWorldDirection: function (target) {
  7936. if (target === undefined) {
  7937. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7938. target = new Vector3();
  7939. }
  7940. this.updateWorldMatrix(true, false);
  7941. const e = this.matrixWorld.elements;
  7942. return target.set(-e[8], -e[9], -e[10]).normalize();
  7943. },
  7944. updateMatrixWorld: function (force) {
  7945. Object3D.prototype.updateMatrixWorld.call(this, force);
  7946. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7947. },
  7948. updateWorldMatrix: function (updateParents, updateChildren) {
  7949. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  7950. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7951. },
  7952. clone: function () {
  7953. return new this.constructor().copy(this);
  7954. }
  7955. });
  7956. function PerspectiveCamera(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7957. Camera.call(this);
  7958. this.type = 'PerspectiveCamera';
  7959. this.fov = fov;
  7960. this.zoom = 1;
  7961. this.near = near;
  7962. this.far = far;
  7963. this.focus = 10;
  7964. this.aspect = aspect;
  7965. this.view = null;
  7966. this.filmGauge = 35; // width of the film (default in millimeters)
  7967. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7968. this.updateProjectionMatrix();
  7969. }
  7970. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  7971. constructor: PerspectiveCamera,
  7972. isPerspectiveCamera: true,
  7973. copy: function (source, recursive) {
  7974. Camera.prototype.copy.call(this, source, recursive);
  7975. this.fov = source.fov;
  7976. this.zoom = source.zoom;
  7977. this.near = source.near;
  7978. this.far = source.far;
  7979. this.focus = source.focus;
  7980. this.aspect = source.aspect;
  7981. this.view = source.view === null ? null : Object.assign({}, source.view);
  7982. this.filmGauge = source.filmGauge;
  7983. this.filmOffset = source.filmOffset;
  7984. return this;
  7985. },
  7986. /**
  7987. * Sets the FOV by focal length in respect to the current .filmGauge.
  7988. *
  7989. * The default film gauge is 35, so that the focal length can be specified for
  7990. * a 35mm (full frame) camera.
  7991. *
  7992. * Values for focal length and film gauge must have the same unit.
  7993. */
  7994. setFocalLength: function (focalLength) {
  7995. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7996. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7997. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  7998. this.updateProjectionMatrix();
  7999. },
  8000. /**
  8001. * Calculates the focal length from the current .fov and .filmGauge.
  8002. */
  8003. getFocalLength: function () {
  8004. const vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  8005. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8006. },
  8007. getEffectiveFOV: function () {
  8008. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8009. },
  8010. getFilmWidth: function () {
  8011. // film not completely covered in portrait format (aspect < 1)
  8012. return this.filmGauge * Math.min(this.aspect, 1);
  8013. },
  8014. getFilmHeight: function () {
  8015. // film not completely covered in landscape format (aspect > 1)
  8016. return this.filmGauge / Math.max(this.aspect, 1);
  8017. },
  8018. /**
  8019. * Sets an offset in a larger frustum. This is useful for multi-window or
  8020. * multi-monitor/multi-machine setups.
  8021. *
  8022. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8023. * the monitors are in grid like this
  8024. *
  8025. * +---+---+---+
  8026. * | A | B | C |
  8027. * +---+---+---+
  8028. * | D | E | F |
  8029. * +---+---+---+
  8030. *
  8031. * then for each monitor you would call it like this
  8032. *
  8033. * const w = 1920;
  8034. * const h = 1080;
  8035. * const fullWidth = w * 3;
  8036. * const fullHeight = h * 2;
  8037. *
  8038. * --A--
  8039. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8040. * --B--
  8041. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8042. * --C--
  8043. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8044. * --D--
  8045. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8046. * --E--
  8047. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8048. * --F--
  8049. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8050. *
  8051. * Note there is no reason monitors have to be the same size or in a grid.
  8052. */
  8053. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8054. this.aspect = fullWidth / fullHeight;
  8055. if (this.view === null) {
  8056. this.view = {
  8057. enabled: true,
  8058. fullWidth: 1,
  8059. fullHeight: 1,
  8060. offsetX: 0,
  8061. offsetY: 0,
  8062. width: 1,
  8063. height: 1
  8064. };
  8065. }
  8066. this.view.enabled = true;
  8067. this.view.fullWidth = fullWidth;
  8068. this.view.fullHeight = fullHeight;
  8069. this.view.offsetX = x;
  8070. this.view.offsetY = y;
  8071. this.view.width = width;
  8072. this.view.height = height;
  8073. this.updateProjectionMatrix();
  8074. },
  8075. clearViewOffset: function () {
  8076. if (this.view !== null) {
  8077. this.view.enabled = false;
  8078. }
  8079. this.updateProjectionMatrix();
  8080. },
  8081. updateProjectionMatrix: function () {
  8082. const near = this.near;
  8083. let top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
  8084. let height = 2 * top;
  8085. let width = this.aspect * height;
  8086. let left = -0.5 * width;
  8087. const view = this.view;
  8088. if (this.view !== null && this.view.enabled) {
  8089. const fullWidth = view.fullWidth,
  8090. fullHeight = view.fullHeight;
  8091. left += view.offsetX * width / fullWidth;
  8092. top -= view.offsetY * height / fullHeight;
  8093. width *= view.width / fullWidth;
  8094. height *= view.height / fullHeight;
  8095. }
  8096. const skew = this.filmOffset;
  8097. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8098. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8099. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  8100. },
  8101. toJSON: function (meta) {
  8102. const data = Object3D.prototype.toJSON.call(this, meta);
  8103. data.object.fov = this.fov;
  8104. data.object.zoom = this.zoom;
  8105. data.object.near = this.near;
  8106. data.object.far = this.far;
  8107. data.object.focus = this.focus;
  8108. data.object.aspect = this.aspect;
  8109. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8110. data.object.filmGauge = this.filmGauge;
  8111. data.object.filmOffset = this.filmOffset;
  8112. return data;
  8113. }
  8114. });
  8115. const fov = 90,
  8116. aspect = 1;
  8117. function CubeCamera(near, far, renderTarget) {
  8118. Object3D.call(this);
  8119. this.type = 'CubeCamera';
  8120. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  8121. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  8122. return;
  8123. }
  8124. this.renderTarget = renderTarget;
  8125. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8126. cameraPX.layers = this.layers;
  8127. cameraPX.up.set(0, -1, 0);
  8128. cameraPX.lookAt(new Vector3(1, 0, 0));
  8129. this.add(cameraPX);
  8130. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8131. cameraNX.layers = this.layers;
  8132. cameraNX.up.set(0, -1, 0);
  8133. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8134. this.add(cameraNX);
  8135. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8136. cameraPY.layers = this.layers;
  8137. cameraPY.up.set(0, 0, 1);
  8138. cameraPY.lookAt(new Vector3(0, 1, 0));
  8139. this.add(cameraPY);
  8140. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8141. cameraNY.layers = this.layers;
  8142. cameraNY.up.set(0, 0, -1);
  8143. cameraNY.lookAt(new Vector3(0, -1, 0));
  8144. this.add(cameraNY);
  8145. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8146. cameraPZ.layers = this.layers;
  8147. cameraPZ.up.set(0, -1, 0);
  8148. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8149. this.add(cameraPZ);
  8150. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8151. cameraNZ.layers = this.layers;
  8152. cameraNZ.up.set(0, -1, 0);
  8153. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8154. this.add(cameraNZ);
  8155. this.update = function (renderer, scene) {
  8156. if (this.parent === null) this.updateMatrixWorld();
  8157. const currentXrEnabled = renderer.xr.enabled;
  8158. const currentRenderTarget = renderer.getRenderTarget();
  8159. renderer.xr.enabled = false;
  8160. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8161. renderTarget.texture.generateMipmaps = false;
  8162. renderer.setRenderTarget(renderTarget, 0);
  8163. renderer.render(scene, cameraPX);
  8164. renderer.setRenderTarget(renderTarget, 1);
  8165. renderer.render(scene, cameraNX);
  8166. renderer.setRenderTarget(renderTarget, 2);
  8167. renderer.render(scene, cameraPY);
  8168. renderer.setRenderTarget(renderTarget, 3);
  8169. renderer.render(scene, cameraNY);
  8170. renderer.setRenderTarget(renderTarget, 4);
  8171. renderer.render(scene, cameraPZ);
  8172. renderTarget.texture.generateMipmaps = generateMipmaps;
  8173. renderer.setRenderTarget(renderTarget, 5);
  8174. renderer.render(scene, cameraNZ);
  8175. renderer.setRenderTarget(currentRenderTarget);
  8176. renderer.xr.enabled = currentXrEnabled;
  8177. };
  8178. }
  8179. CubeCamera.prototype = Object.create(Object3D.prototype);
  8180. CubeCamera.prototype.constructor = CubeCamera;
  8181. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  8182. images = images !== undefined ? images : [];
  8183. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8184. format = format !== undefined ? format : RGBFormat;
  8185. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8186. this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
  8187. //
  8188. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8189. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8190. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8191. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8192. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  8193. // when using WebGLCubeRenderTarget.texture as a cube texture.
  8194. this._needsFlipEnvMap = true;
  8195. }
  8196. CubeTexture.prototype = Object.create(Texture.prototype);
  8197. CubeTexture.prototype.constructor = CubeTexture;
  8198. CubeTexture.prototype.isCubeTexture = true;
  8199. Object.defineProperty(CubeTexture.prototype, 'images', {
  8200. get: function () {
  8201. return this.image;
  8202. },
  8203. set: function (value) {
  8204. this.image = value;
  8205. }
  8206. });
  8207. function WebGLCubeRenderTarget(size, options, dummy) {
  8208. if (Number.isInteger(options)) {
  8209. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  8210. options = dummy;
  8211. }
  8212. WebGLRenderTarget.call(this, size, size, options);
  8213. options = options || {};
  8214. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  8215. this.texture._needsFlipEnvMap = false;
  8216. }
  8217. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  8218. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8219. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8220. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  8221. this.texture.type = texture.type;
  8222. this.texture.format = RGBAFormat; // see #18859
  8223. this.texture.encoding = texture.encoding;
  8224. this.texture.generateMipmaps = texture.generateMipmaps;
  8225. this.texture.minFilter = texture.minFilter;
  8226. this.texture.magFilter = texture.magFilter;
  8227. const shader = {
  8228. uniforms: {
  8229. tEquirect: {
  8230. value: null
  8231. }
  8232. },
  8233. vertexShader:
  8234. /* glsl */
  8235. `
  8236. varying vec3 vWorldDirection;
  8237. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8238. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8239. }
  8240. void main() {
  8241. vWorldDirection = transformDirection( position, modelMatrix );
  8242. #include <begin_vertex>
  8243. #include <project_vertex>
  8244. }
  8245. `,
  8246. fragmentShader:
  8247. /* glsl */
  8248. `
  8249. uniform sampler2D tEquirect;
  8250. varying vec3 vWorldDirection;
  8251. #include <common>
  8252. void main() {
  8253. vec3 direction = normalize( vWorldDirection );
  8254. vec2 sampleUV = equirectUv( direction );
  8255. gl_FragColor = texture2D( tEquirect, sampleUV );
  8256. }
  8257. `
  8258. };
  8259. const geometry = new BoxBufferGeometry(5, 5, 5);
  8260. const material = new ShaderMaterial({
  8261. name: 'CubemapFromEquirect',
  8262. uniforms: cloneUniforms(shader.uniforms),
  8263. vertexShader: shader.vertexShader,
  8264. fragmentShader: shader.fragmentShader,
  8265. side: BackSide,
  8266. blending: NoBlending
  8267. });
  8268. material.uniforms.tEquirect.value = texture;
  8269. const mesh = new Mesh(geometry, material);
  8270. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  8271. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  8272. const camera = new CubeCamera(1, 10, this);
  8273. camera.update(renderer, mesh);
  8274. texture.minFilter = currentMinFilter;
  8275. mesh.geometry.dispose();
  8276. mesh.material.dispose();
  8277. return this;
  8278. };
  8279. WebGLCubeRenderTarget.prototype.clear = function (renderer, color, depth, stencil) {
  8280. const currentRenderTarget = renderer.getRenderTarget();
  8281. for (let i = 0; i < 6; i++) {
  8282. renderer.setRenderTarget(this, i);
  8283. renderer.clear(color, depth, stencil);
  8284. }
  8285. renderer.setRenderTarget(currentRenderTarget);
  8286. };
  8287. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  8288. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8289. this.image = {
  8290. data: data || null,
  8291. width: width || 1,
  8292. height: height || 1
  8293. };
  8294. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8295. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8296. this.generateMipmaps = false;
  8297. this.flipY = false;
  8298. this.unpackAlignment = 1;
  8299. this.needsUpdate = true;
  8300. }
  8301. DataTexture.prototype = Object.create(Texture.prototype);
  8302. DataTexture.prototype.constructor = DataTexture;
  8303. DataTexture.prototype.isDataTexture = true;
  8304. const _sphere$1 =
  8305. /*@__PURE__*/
  8306. new Sphere();
  8307. const _vector$5 =
  8308. /*@__PURE__*/
  8309. new Vector3();
  8310. class Frustum {
  8311. constructor(p0, p1, p2, p3, p4, p5) {
  8312. this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
  8313. }
  8314. set(p0, p1, p2, p3, p4, p5) {
  8315. const planes = this.planes;
  8316. planes[0].copy(p0);
  8317. planes[1].copy(p1);
  8318. planes[2].copy(p2);
  8319. planes[3].copy(p3);
  8320. planes[4].copy(p4);
  8321. planes[5].copy(p5);
  8322. return this;
  8323. }
  8324. clone() {
  8325. return new this.constructor().copy(this);
  8326. }
  8327. copy(frustum) {
  8328. const planes = this.planes;
  8329. for (let i = 0; i < 6; i++) {
  8330. planes[i].copy(frustum.planes[i]);
  8331. }
  8332. return this;
  8333. }
  8334. setFromProjectionMatrix(m) {
  8335. const planes = this.planes;
  8336. const me = m.elements;
  8337. const me0 = me[0],
  8338. me1 = me[1],
  8339. me2 = me[2],
  8340. me3 = me[3];
  8341. const me4 = me[4],
  8342. me5 = me[5],
  8343. me6 = me[6],
  8344. me7 = me[7];
  8345. const me8 = me[8],
  8346. me9 = me[9],
  8347. me10 = me[10],
  8348. me11 = me[11];
  8349. const me12 = me[12],
  8350. me13 = me[13],
  8351. me14 = me[14],
  8352. me15 = me[15];
  8353. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  8354. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  8355. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  8356. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  8357. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  8358. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  8359. return this;
  8360. }
  8361. intersectsObject(object) {
  8362. const geometry = object.geometry;
  8363. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8364. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  8365. return this.intersectsSphere(_sphere$1);
  8366. }
  8367. intersectsSprite(sprite) {
  8368. _sphere$1.center.set(0, 0, 0);
  8369. _sphere$1.radius = 0.7071067811865476;
  8370. _sphere$1.applyMatrix4(sprite.matrixWorld);
  8371. return this.intersectsSphere(_sphere$1);
  8372. }
  8373. intersectsSphere(sphere) {
  8374. const planes = this.planes;
  8375. const center = sphere.center;
  8376. const negRadius = -sphere.radius;
  8377. for (let i = 0; i < 6; i++) {
  8378. const distance = planes[i].distanceToPoint(center);
  8379. if (distance < negRadius) {
  8380. return false;
  8381. }
  8382. }
  8383. return true;
  8384. }
  8385. intersectsBox(box) {
  8386. const planes = this.planes;
  8387. for (let i = 0; i < 6; i++) {
  8388. const plane = planes[i]; // corner at max distance
  8389. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8390. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8391. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8392. if (plane.distanceToPoint(_vector$5) < 0) {
  8393. return false;
  8394. }
  8395. }
  8396. return true;
  8397. }
  8398. containsPoint(point) {
  8399. const planes = this.planes;
  8400. for (let i = 0; i < 6; i++) {
  8401. if (planes[i].distanceToPoint(point) < 0) {
  8402. return false;
  8403. }
  8404. }
  8405. return true;
  8406. }
  8407. }
  8408. exports.Frustum = Frustum;
  8409. function WebGLAnimation() {
  8410. let context = null;
  8411. let isAnimating = false;
  8412. let animationLoop = null;
  8413. let requestId = null;
  8414. function onAnimationFrame(time, frame) {
  8415. animationLoop(time, frame);
  8416. requestId = context.requestAnimationFrame(onAnimationFrame);
  8417. }
  8418. return {
  8419. start: function () {
  8420. if (isAnimating === true) return;
  8421. if (animationLoop === null) return;
  8422. requestId = context.requestAnimationFrame(onAnimationFrame);
  8423. isAnimating = true;
  8424. },
  8425. stop: function () {
  8426. context.cancelAnimationFrame(requestId);
  8427. isAnimating = false;
  8428. },
  8429. setAnimationLoop: function (callback) {
  8430. animationLoop = callback;
  8431. },
  8432. setContext: function (value) {
  8433. context = value;
  8434. }
  8435. };
  8436. }
  8437. function WebGLAttributes(gl, capabilities) {
  8438. const isWebGL2 = capabilities.isWebGL2;
  8439. const buffers = new WeakMap();
  8440. function createBuffer(attribute, bufferType) {
  8441. const array = attribute.array;
  8442. const usage = attribute.usage;
  8443. const buffer = gl.createBuffer();
  8444. gl.bindBuffer(bufferType, buffer);
  8445. gl.bufferData(bufferType, array, usage);
  8446. attribute.onUploadCallback();
  8447. let type = 5126;
  8448. if (array instanceof Float32Array) {
  8449. type = 5126;
  8450. } else if (array instanceof Float64Array) {
  8451. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  8452. } else if (array instanceof Uint16Array) {
  8453. if (attribute.isFloat16BufferAttribute) {
  8454. if (isWebGL2) {
  8455. type = 5131;
  8456. } else {
  8457. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  8458. }
  8459. } else {
  8460. type = 5123;
  8461. }
  8462. } else if (array instanceof Int16Array) {
  8463. type = 5122;
  8464. } else if (array instanceof Uint32Array) {
  8465. type = 5125;
  8466. } else if (array instanceof Int32Array) {
  8467. type = 5124;
  8468. } else if (array instanceof Int8Array) {
  8469. type = 5120;
  8470. } else if (array instanceof Uint8Array) {
  8471. type = 5121;
  8472. }
  8473. return {
  8474. buffer: buffer,
  8475. type: type,
  8476. bytesPerElement: array.BYTES_PER_ELEMENT,
  8477. version: attribute.version
  8478. };
  8479. }
  8480. function updateBuffer(buffer, attribute, bufferType) {
  8481. const array = attribute.array;
  8482. const updateRange = attribute.updateRange;
  8483. gl.bindBuffer(bufferType, buffer);
  8484. if (updateRange.count === -1) {
  8485. // Not using update ranges
  8486. gl.bufferSubData(bufferType, 0, array);
  8487. } else {
  8488. if (isWebGL2) {
  8489. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  8490. } else {
  8491. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  8492. }
  8493. updateRange.count = -1; // reset range
  8494. }
  8495. } //
  8496. function get(attribute) {
  8497. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8498. return buffers.get(attribute);
  8499. }
  8500. function remove(attribute) {
  8501. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8502. const data = buffers.get(attribute);
  8503. if (data) {
  8504. gl.deleteBuffer(data.buffer);
  8505. buffers.delete(attribute);
  8506. }
  8507. }
  8508. function update(attribute, bufferType) {
  8509. if (attribute.isGLBufferAttribute) {
  8510. const cached = buffers.get(attribute);
  8511. if (!cached || cached.version < attribute.version) {
  8512. buffers.set(attribute, {
  8513. buffer: attribute.buffer,
  8514. type: attribute.type,
  8515. bytesPerElement: attribute.elementSize,
  8516. version: attribute.version
  8517. });
  8518. }
  8519. return;
  8520. }
  8521. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8522. const data = buffers.get(attribute);
  8523. if (data === undefined) {
  8524. buffers.set(attribute, createBuffer(attribute, bufferType));
  8525. } else if (data.version < attribute.version) {
  8526. updateBuffer(data.buffer, attribute, bufferType);
  8527. data.version = attribute.version;
  8528. }
  8529. }
  8530. return {
  8531. get: get,
  8532. remove: remove,
  8533. update: update
  8534. };
  8535. }
  8536. class PlaneBufferGeometry extends BufferGeometry {
  8537. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  8538. super();
  8539. this.type = 'PlaneBufferGeometry';
  8540. this.parameters = {
  8541. width: width,
  8542. height: height,
  8543. widthSegments: widthSegments,
  8544. heightSegments: heightSegments
  8545. };
  8546. const width_half = width / 2;
  8547. const height_half = height / 2;
  8548. const gridX = Math.floor(widthSegments);
  8549. const gridY = Math.floor(heightSegments);
  8550. const gridX1 = gridX + 1;
  8551. const gridY1 = gridY + 1;
  8552. const segment_width = width / gridX;
  8553. const segment_height = height / gridY; //
  8554. const indices = [];
  8555. const vertices = [];
  8556. const normals = [];
  8557. const uvs = [];
  8558. for (let iy = 0; iy < gridY1; iy++) {
  8559. const y = iy * segment_height - height_half;
  8560. for (let ix = 0; ix < gridX1; ix++) {
  8561. const x = ix * segment_width - width_half;
  8562. vertices.push(x, -y, 0);
  8563. normals.push(0, 0, 1);
  8564. uvs.push(ix / gridX);
  8565. uvs.push(1 - iy / gridY);
  8566. }
  8567. }
  8568. for (let iy = 0; iy < gridY; iy++) {
  8569. for (let ix = 0; ix < gridX; ix++) {
  8570. const a = ix + gridX1 * iy;
  8571. const b = ix + gridX1 * (iy + 1);
  8572. const c = ix + 1 + gridX1 * (iy + 1);
  8573. const d = ix + 1 + gridX1 * iy;
  8574. indices.push(a, b, d);
  8575. indices.push(b, c, d);
  8576. }
  8577. }
  8578. this.setIndex(indices);
  8579. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8580. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8581. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8582. }
  8583. }
  8584. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  8585. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8586. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8587. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8588. 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";
  8589. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8590. var begin_vertex = "vec3 transformed = vec3( position );";
  8591. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8592. 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";
  8593. 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 ) {\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 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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";
  8594. 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";
  8595. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8596. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8597. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8598. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8599. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8600. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8601. 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";
  8602. 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}";
  8603. 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";
  8604. 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";
  8605. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8606. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8607. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8608. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8609. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8610. 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}";
  8611. 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";
  8612. 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";
  8613. 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";
  8614. 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";
  8615. 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";
  8616. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8617. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8618. 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";
  8619. 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";
  8620. 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}";
  8621. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8622. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8623. 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";
  8624. 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";
  8625. 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";
  8626. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8627. 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)";
  8628. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8629. 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)";
  8630. 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";
  8631. 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}";
  8632. 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";
  8633. 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";
  8634. 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";
  8635. 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";
  8636. 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";
  8637. 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";
  8638. 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";
  8639. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8640. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8641. 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";
  8642. 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";
  8643. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8644. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8645. 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";
  8646. 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";
  8647. 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";
  8648. var normal_fragment_begin = "#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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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;";
  8649. 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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8650. 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 ) {\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\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  8651. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8652. 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 );\n\t#endif\n#endif";
  8653. 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";
  8654. 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}";
  8655. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8656. 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;";
  8657. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8658. 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";
  8659. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8660. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8661. 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";
  8662. 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";
  8663. 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";
  8664. 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}";
  8665. 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";
  8666. 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";
  8667. 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";
  8668. 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";
  8669. 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";
  8670. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8671. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8672. 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; }";
  8673. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8674. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8675. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8676. 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";
  8677. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8678. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8679. 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";
  8680. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8681. 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";
  8682. 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}";
  8683. 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}";
  8684. 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}";
  8685. 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}";
  8686. 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}";
  8687. 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}";
  8688. 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}";
  8689. 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}";
  8690. 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}";
  8691. 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}";
  8692. 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}";
  8693. 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}";
  8694. 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}";
  8695. 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}";
  8696. 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}";
  8697. 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}";
  8698. 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}";
  8699. 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}";
  8700. 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}";
  8701. 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}";
  8702. 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}";
  8703. 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}";
  8704. 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}";
  8705. 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}";
  8706. 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}";
  8707. 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}";
  8708. 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}";
  8709. 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}";
  8710. 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}";
  8711. 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}";
  8712. 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}";
  8713. 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}";
  8714. const ShaderChunk = {
  8715. alphamap_fragment: alphamap_fragment,
  8716. alphamap_pars_fragment: alphamap_pars_fragment,
  8717. alphatest_fragment: alphatest_fragment,
  8718. aomap_fragment: aomap_fragment,
  8719. aomap_pars_fragment: aomap_pars_fragment,
  8720. begin_vertex: begin_vertex,
  8721. beginnormal_vertex: beginnormal_vertex,
  8722. bsdfs: bsdfs,
  8723. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8724. clipping_planes_fragment: clipping_planes_fragment,
  8725. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8726. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8727. clipping_planes_vertex: clipping_planes_vertex,
  8728. color_fragment: color_fragment,
  8729. color_pars_fragment: color_pars_fragment,
  8730. color_pars_vertex: color_pars_vertex,
  8731. color_vertex: color_vertex,
  8732. common: common,
  8733. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8734. defaultnormal_vertex: defaultnormal_vertex,
  8735. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8736. displacementmap_vertex: displacementmap_vertex,
  8737. emissivemap_fragment: emissivemap_fragment,
  8738. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8739. encodings_fragment: encodings_fragment,
  8740. encodings_pars_fragment: encodings_pars_fragment,
  8741. envmap_fragment: envmap_fragment,
  8742. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8743. envmap_pars_fragment: envmap_pars_fragment,
  8744. envmap_pars_vertex: envmap_pars_vertex,
  8745. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8746. envmap_vertex: envmap_vertex,
  8747. fog_vertex: fog_vertex,
  8748. fog_pars_vertex: fog_pars_vertex,
  8749. fog_fragment: fog_fragment,
  8750. fog_pars_fragment: fog_pars_fragment,
  8751. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8752. lightmap_fragment: lightmap_fragment,
  8753. lightmap_pars_fragment: lightmap_pars_fragment,
  8754. lights_lambert_vertex: lights_lambert_vertex,
  8755. lights_pars_begin: lights_pars_begin,
  8756. lights_toon_fragment: lights_toon_fragment,
  8757. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8758. lights_phong_fragment: lights_phong_fragment,
  8759. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8760. lights_physical_fragment: lights_physical_fragment,
  8761. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8762. lights_fragment_begin: lights_fragment_begin,
  8763. lights_fragment_maps: lights_fragment_maps,
  8764. lights_fragment_end: lights_fragment_end,
  8765. logdepthbuf_fragment: logdepthbuf_fragment,
  8766. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8767. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8768. logdepthbuf_vertex: logdepthbuf_vertex,
  8769. map_fragment: map_fragment,
  8770. map_pars_fragment: map_pars_fragment,
  8771. map_particle_fragment: map_particle_fragment,
  8772. map_particle_pars_fragment: map_particle_pars_fragment,
  8773. metalnessmap_fragment: metalnessmap_fragment,
  8774. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8775. morphnormal_vertex: morphnormal_vertex,
  8776. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8777. morphtarget_vertex: morphtarget_vertex,
  8778. normal_fragment_begin: normal_fragment_begin,
  8779. normal_fragment_maps: normal_fragment_maps,
  8780. normalmap_pars_fragment: normalmap_pars_fragment,
  8781. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8782. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8783. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8784. packing: packing,
  8785. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8786. project_vertex: project_vertex,
  8787. dithering_fragment: dithering_fragment,
  8788. dithering_pars_fragment: dithering_pars_fragment,
  8789. roughnessmap_fragment: roughnessmap_fragment,
  8790. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8791. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8792. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8793. shadowmap_vertex: shadowmap_vertex,
  8794. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8795. skinbase_vertex: skinbase_vertex,
  8796. skinning_pars_vertex: skinning_pars_vertex,
  8797. skinning_vertex: skinning_vertex,
  8798. skinnormal_vertex: skinnormal_vertex,
  8799. specularmap_fragment: specularmap_fragment,
  8800. specularmap_pars_fragment: specularmap_pars_fragment,
  8801. tonemapping_fragment: tonemapping_fragment,
  8802. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8803. transmissionmap_fragment: transmissionmap_fragment,
  8804. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8805. uv_pars_fragment: uv_pars_fragment,
  8806. uv_pars_vertex: uv_pars_vertex,
  8807. uv_vertex: uv_vertex,
  8808. uv2_pars_fragment: uv2_pars_fragment,
  8809. uv2_pars_vertex: uv2_pars_vertex,
  8810. uv2_vertex: uv2_vertex,
  8811. worldpos_vertex: worldpos_vertex,
  8812. background_frag: background_frag,
  8813. background_vert: background_vert,
  8814. cube_frag: cube_frag,
  8815. cube_vert: cube_vert,
  8816. depth_frag: depth_frag,
  8817. depth_vert: depth_vert,
  8818. distanceRGBA_frag: distanceRGBA_frag,
  8819. distanceRGBA_vert: distanceRGBA_vert,
  8820. equirect_frag: equirect_frag,
  8821. equirect_vert: equirect_vert,
  8822. linedashed_frag: linedashed_frag,
  8823. linedashed_vert: linedashed_vert,
  8824. meshbasic_frag: meshbasic_frag,
  8825. meshbasic_vert: meshbasic_vert,
  8826. meshlambert_frag: meshlambert_frag,
  8827. meshlambert_vert: meshlambert_vert,
  8828. meshmatcap_frag: meshmatcap_frag,
  8829. meshmatcap_vert: meshmatcap_vert,
  8830. meshtoon_frag: meshtoon_frag,
  8831. meshtoon_vert: meshtoon_vert,
  8832. meshphong_frag: meshphong_frag,
  8833. meshphong_vert: meshphong_vert,
  8834. meshphysical_frag: meshphysical_frag,
  8835. meshphysical_vert: meshphysical_vert,
  8836. normal_frag: normal_frag,
  8837. normal_vert: normal_vert,
  8838. points_frag: points_frag,
  8839. points_vert: points_vert,
  8840. shadow_frag: shadow_frag,
  8841. shadow_vert: shadow_vert,
  8842. sprite_frag: sprite_frag,
  8843. sprite_vert: sprite_vert
  8844. };
  8845. /**
  8846. * Uniforms library for shared webgl shaders
  8847. */
  8848. exports.ShaderChunk = ShaderChunk;
  8849. const UniformsLib = {
  8850. common: {
  8851. diffuse: {
  8852. value: new Color(0xeeeeee)
  8853. },
  8854. opacity: {
  8855. value: 1.0
  8856. },
  8857. map: {
  8858. value: null
  8859. },
  8860. uvTransform: {
  8861. value: new Matrix3()
  8862. },
  8863. uv2Transform: {
  8864. value: new Matrix3()
  8865. },
  8866. alphaMap: {
  8867. value: null
  8868. }
  8869. },
  8870. specularmap: {
  8871. specularMap: {
  8872. value: null
  8873. }
  8874. },
  8875. envmap: {
  8876. envMap: {
  8877. value: null
  8878. },
  8879. flipEnvMap: {
  8880. value: -1
  8881. },
  8882. reflectivity: {
  8883. value: 1.0
  8884. },
  8885. refractionRatio: {
  8886. value: 0.98
  8887. },
  8888. maxMipLevel: {
  8889. value: 0
  8890. }
  8891. },
  8892. aomap: {
  8893. aoMap: {
  8894. value: null
  8895. },
  8896. aoMapIntensity: {
  8897. value: 1
  8898. }
  8899. },
  8900. lightmap: {
  8901. lightMap: {
  8902. value: null
  8903. },
  8904. lightMapIntensity: {
  8905. value: 1
  8906. }
  8907. },
  8908. emissivemap: {
  8909. emissiveMap: {
  8910. value: null
  8911. }
  8912. },
  8913. bumpmap: {
  8914. bumpMap: {
  8915. value: null
  8916. },
  8917. bumpScale: {
  8918. value: 1
  8919. }
  8920. },
  8921. normalmap: {
  8922. normalMap: {
  8923. value: null
  8924. },
  8925. normalScale: {
  8926. value: new Vector2(1, 1)
  8927. }
  8928. },
  8929. displacementmap: {
  8930. displacementMap: {
  8931. value: null
  8932. },
  8933. displacementScale: {
  8934. value: 1
  8935. },
  8936. displacementBias: {
  8937. value: 0
  8938. }
  8939. },
  8940. roughnessmap: {
  8941. roughnessMap: {
  8942. value: null
  8943. }
  8944. },
  8945. metalnessmap: {
  8946. metalnessMap: {
  8947. value: null
  8948. }
  8949. },
  8950. gradientmap: {
  8951. gradientMap: {
  8952. value: null
  8953. }
  8954. },
  8955. fog: {
  8956. fogDensity: {
  8957. value: 0.00025
  8958. },
  8959. fogNear: {
  8960. value: 1
  8961. },
  8962. fogFar: {
  8963. value: 2000
  8964. },
  8965. fogColor: {
  8966. value: new Color(0xffffff)
  8967. }
  8968. },
  8969. lights: {
  8970. ambientLightColor: {
  8971. value: []
  8972. },
  8973. lightProbe: {
  8974. value: []
  8975. },
  8976. directionalLights: {
  8977. value: [],
  8978. properties: {
  8979. direction: {},
  8980. color: {}
  8981. }
  8982. },
  8983. directionalLightShadows: {
  8984. value: [],
  8985. properties: {
  8986. shadowBias: {},
  8987. shadowNormalBias: {},
  8988. shadowRadius: {},
  8989. shadowMapSize: {}
  8990. }
  8991. },
  8992. directionalShadowMap: {
  8993. value: []
  8994. },
  8995. directionalShadowMatrix: {
  8996. value: []
  8997. },
  8998. spotLights: {
  8999. value: [],
  9000. properties: {
  9001. color: {},
  9002. position: {},
  9003. direction: {},
  9004. distance: {},
  9005. coneCos: {},
  9006. penumbraCos: {},
  9007. decay: {}
  9008. }
  9009. },
  9010. spotLightShadows: {
  9011. value: [],
  9012. properties: {
  9013. shadowBias: {},
  9014. shadowNormalBias: {},
  9015. shadowRadius: {},
  9016. shadowMapSize: {}
  9017. }
  9018. },
  9019. spotShadowMap: {
  9020. value: []
  9021. },
  9022. spotShadowMatrix: {
  9023. value: []
  9024. },
  9025. pointLights: {
  9026. value: [],
  9027. properties: {
  9028. color: {},
  9029. position: {},
  9030. decay: {},
  9031. distance: {}
  9032. }
  9033. },
  9034. pointLightShadows: {
  9035. value: [],
  9036. properties: {
  9037. shadowBias: {},
  9038. shadowNormalBias: {},
  9039. shadowRadius: {},
  9040. shadowMapSize: {},
  9041. shadowCameraNear: {},
  9042. shadowCameraFar: {}
  9043. }
  9044. },
  9045. pointShadowMap: {
  9046. value: []
  9047. },
  9048. pointShadowMatrix: {
  9049. value: []
  9050. },
  9051. hemisphereLights: {
  9052. value: [],
  9053. properties: {
  9054. direction: {},
  9055. skyColor: {},
  9056. groundColor: {}
  9057. }
  9058. },
  9059. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9060. rectAreaLights: {
  9061. value: [],
  9062. properties: {
  9063. color: {},
  9064. position: {},
  9065. width: {},
  9066. height: {}
  9067. }
  9068. },
  9069. ltc_1: {
  9070. value: null
  9071. },
  9072. ltc_2: {
  9073. value: null
  9074. }
  9075. },
  9076. points: {
  9077. diffuse: {
  9078. value: new Color(0xeeeeee)
  9079. },
  9080. opacity: {
  9081. value: 1.0
  9082. },
  9083. size: {
  9084. value: 1.0
  9085. },
  9086. scale: {
  9087. value: 1.0
  9088. },
  9089. map: {
  9090. value: null
  9091. },
  9092. alphaMap: {
  9093. value: null
  9094. },
  9095. uvTransform: {
  9096. value: new Matrix3()
  9097. }
  9098. },
  9099. sprite: {
  9100. diffuse: {
  9101. value: new Color(0xeeeeee)
  9102. },
  9103. opacity: {
  9104. value: 1.0
  9105. },
  9106. center: {
  9107. value: new Vector2(0.5, 0.5)
  9108. },
  9109. rotation: {
  9110. value: 0.0
  9111. },
  9112. map: {
  9113. value: null
  9114. },
  9115. alphaMap: {
  9116. value: null
  9117. },
  9118. uvTransform: {
  9119. value: new Matrix3()
  9120. }
  9121. }
  9122. };
  9123. exports.UniformsLib = UniformsLib;
  9124. const ShaderLib = {
  9125. basic: {
  9126. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9127. vertexShader: ShaderChunk.meshbasic_vert,
  9128. fragmentShader: ShaderChunk.meshbasic_frag
  9129. },
  9130. lambert: {
  9131. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9132. emissive: {
  9133. value: new Color(0x000000)
  9134. }
  9135. }]),
  9136. vertexShader: ShaderChunk.meshlambert_vert,
  9137. fragmentShader: ShaderChunk.meshlambert_frag
  9138. },
  9139. phong: {
  9140. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  9141. emissive: {
  9142. value: new Color(0x000000)
  9143. },
  9144. specular: {
  9145. value: new Color(0x111111)
  9146. },
  9147. shininess: {
  9148. value: 30
  9149. }
  9150. }]),
  9151. vertexShader: ShaderChunk.meshphong_vert,
  9152. fragmentShader: ShaderChunk.meshphong_frag
  9153. },
  9154. standard: {
  9155. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  9156. emissive: {
  9157. value: new Color(0x000000)
  9158. },
  9159. roughness: {
  9160. value: 1.0
  9161. },
  9162. metalness: {
  9163. value: 0.0
  9164. },
  9165. envMapIntensity: {
  9166. value: 1
  9167. } // temporary
  9168. }]),
  9169. vertexShader: ShaderChunk.meshphysical_vert,
  9170. fragmentShader: ShaderChunk.meshphysical_frag
  9171. },
  9172. toon: {
  9173. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  9174. emissive: {
  9175. value: new Color(0x000000)
  9176. }
  9177. }]),
  9178. vertexShader: ShaderChunk.meshtoon_vert,
  9179. fragmentShader: ShaderChunk.meshtoon_frag
  9180. },
  9181. matcap: {
  9182. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9183. matcap: {
  9184. value: null
  9185. }
  9186. }]),
  9187. vertexShader: ShaderChunk.meshmatcap_vert,
  9188. fragmentShader: ShaderChunk.meshmatcap_frag
  9189. },
  9190. points: {
  9191. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9192. vertexShader: ShaderChunk.points_vert,
  9193. fragmentShader: ShaderChunk.points_frag
  9194. },
  9195. dashed: {
  9196. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9197. scale: {
  9198. value: 1
  9199. },
  9200. dashSize: {
  9201. value: 1
  9202. },
  9203. totalSize: {
  9204. value: 2
  9205. }
  9206. }]),
  9207. vertexShader: ShaderChunk.linedashed_vert,
  9208. fragmentShader: ShaderChunk.linedashed_frag
  9209. },
  9210. depth: {
  9211. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9212. vertexShader: ShaderChunk.depth_vert,
  9213. fragmentShader: ShaderChunk.depth_frag
  9214. },
  9215. normal: {
  9216. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  9217. opacity: {
  9218. value: 1.0
  9219. }
  9220. }]),
  9221. vertexShader: ShaderChunk.normal_vert,
  9222. fragmentShader: ShaderChunk.normal_frag
  9223. },
  9224. sprite: {
  9225. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  9226. vertexShader: ShaderChunk.sprite_vert,
  9227. fragmentShader: ShaderChunk.sprite_frag
  9228. },
  9229. background: {
  9230. uniforms: {
  9231. uvTransform: {
  9232. value: new Matrix3()
  9233. },
  9234. t2D: {
  9235. value: null
  9236. }
  9237. },
  9238. vertexShader: ShaderChunk.background_vert,
  9239. fragmentShader: ShaderChunk.background_frag
  9240. },
  9241. /* -------------------------------------------------------------------------
  9242. // Cube map shader
  9243. ------------------------------------------------------------------------- */
  9244. cube: {
  9245. uniforms: mergeUniforms([UniformsLib.envmap, {
  9246. opacity: {
  9247. value: 1.0
  9248. }
  9249. }]),
  9250. vertexShader: ShaderChunk.cube_vert,
  9251. fragmentShader: ShaderChunk.cube_frag
  9252. },
  9253. equirect: {
  9254. uniforms: {
  9255. tEquirect: {
  9256. value: null
  9257. }
  9258. },
  9259. vertexShader: ShaderChunk.equirect_vert,
  9260. fragmentShader: ShaderChunk.equirect_frag
  9261. },
  9262. distanceRGBA: {
  9263. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  9264. referencePosition: {
  9265. value: new Vector3()
  9266. },
  9267. nearDistance: {
  9268. value: 1
  9269. },
  9270. farDistance: {
  9271. value: 1000
  9272. }
  9273. }]),
  9274. vertexShader: ShaderChunk.distanceRGBA_vert,
  9275. fragmentShader: ShaderChunk.distanceRGBA_frag
  9276. },
  9277. shadow: {
  9278. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  9279. color: {
  9280. value: new Color(0x00000)
  9281. },
  9282. opacity: {
  9283. value: 1.0
  9284. }
  9285. }]),
  9286. vertexShader: ShaderChunk.shadow_vert,
  9287. fragmentShader: ShaderChunk.shadow_frag
  9288. }
  9289. };
  9290. exports.ShaderLib = ShaderLib;
  9291. ShaderLib.physical = {
  9292. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  9293. clearcoat: {
  9294. value: 0
  9295. },
  9296. clearcoatMap: {
  9297. value: null
  9298. },
  9299. clearcoatRoughness: {
  9300. value: 0
  9301. },
  9302. clearcoatRoughnessMap: {
  9303. value: null
  9304. },
  9305. clearcoatNormalScale: {
  9306. value: new Vector2(1, 1)
  9307. },
  9308. clearcoatNormalMap: {
  9309. value: null
  9310. },
  9311. sheen: {
  9312. value: new Color(0x000000)
  9313. },
  9314. transmission: {
  9315. value: 0
  9316. },
  9317. transmissionMap: {
  9318. value: null
  9319. }
  9320. }]),
  9321. vertexShader: ShaderChunk.meshphysical_vert,
  9322. fragmentShader: ShaderChunk.meshphysical_frag
  9323. };
  9324. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  9325. const clearColor = new Color(0x000000);
  9326. let clearAlpha = 0;
  9327. let planeMesh;
  9328. let boxMesh;
  9329. let currentBackground = null;
  9330. let currentBackgroundVersion = 0;
  9331. let currentTonemapping = null;
  9332. function render(renderList, scene, camera, forceClear) {
  9333. let background = scene.isScene === true ? scene.background : null;
  9334. if (background && background.isTexture) {
  9335. background = cubemaps.get(background);
  9336. } // Ignore background in AR
  9337. // TODO: Reconsider this.
  9338. const xr = renderer.xr;
  9339. const session = xr.getSession && xr.getSession();
  9340. if (session && session.environmentBlendMode === 'additive') {
  9341. background = null;
  9342. }
  9343. if (background === null) {
  9344. setClear(clearColor, clearAlpha);
  9345. } else if (background && background.isColor) {
  9346. setClear(background, 1);
  9347. forceClear = true;
  9348. }
  9349. if (renderer.autoClear || forceClear) {
  9350. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  9351. }
  9352. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  9353. if (boxMesh === undefined) {
  9354. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  9355. name: 'BackgroundCubeMaterial',
  9356. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  9357. vertexShader: ShaderLib.cube.vertexShader,
  9358. fragmentShader: ShaderLib.cube.fragmentShader,
  9359. side: BackSide,
  9360. depthTest: false,
  9361. depthWrite: false,
  9362. fog: false
  9363. }));
  9364. boxMesh.geometry.deleteAttribute('normal');
  9365. boxMesh.geometry.deleteAttribute('uv');
  9366. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  9367. this.matrixWorld.copyPosition(camera.matrixWorld);
  9368. }; // enable code injection for non-built-in material
  9369. Object.defineProperty(boxMesh.material, 'envMap', {
  9370. get: function () {
  9371. return this.uniforms.envMap.value;
  9372. }
  9373. });
  9374. objects.update(boxMesh);
  9375. }
  9376. if (background.isWebGLCubeRenderTarget) {
  9377. // TODO Deprecate
  9378. background = background.texture;
  9379. }
  9380. boxMesh.material.uniforms.envMap.value = background;
  9381. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  9382. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  9383. boxMesh.material.needsUpdate = true;
  9384. currentBackground = background;
  9385. currentBackgroundVersion = background.version;
  9386. currentTonemapping = renderer.toneMapping;
  9387. } // push to the pre-sorted opaque render list
  9388. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  9389. } else if (background && background.isTexture) {
  9390. if (planeMesh === undefined) {
  9391. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  9392. name: 'BackgroundMaterial',
  9393. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  9394. vertexShader: ShaderLib.background.vertexShader,
  9395. fragmentShader: ShaderLib.background.fragmentShader,
  9396. side: FrontSide,
  9397. depthTest: false,
  9398. depthWrite: false,
  9399. fog: false
  9400. }));
  9401. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  9402. Object.defineProperty(planeMesh.material, 'map', {
  9403. get: function () {
  9404. return this.uniforms.t2D.value;
  9405. }
  9406. });
  9407. objects.update(planeMesh);
  9408. }
  9409. planeMesh.material.uniforms.t2D.value = background;
  9410. if (background.matrixAutoUpdate === true) {
  9411. background.updateMatrix();
  9412. }
  9413. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  9414. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  9415. planeMesh.material.needsUpdate = true;
  9416. currentBackground = background;
  9417. currentBackgroundVersion = background.version;
  9418. currentTonemapping = renderer.toneMapping;
  9419. } // push to the pre-sorted opaque render list
  9420. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  9421. }
  9422. }
  9423. function setClear(color, alpha) {
  9424. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  9425. }
  9426. return {
  9427. getClearColor: function () {
  9428. return clearColor;
  9429. },
  9430. setClearColor: function (color, alpha = 1) {
  9431. clearColor.set(color);
  9432. clearAlpha = alpha;
  9433. setClear(clearColor, clearAlpha);
  9434. },
  9435. getClearAlpha: function () {
  9436. return clearAlpha;
  9437. },
  9438. setClearAlpha: function (alpha) {
  9439. clearAlpha = alpha;
  9440. setClear(clearColor, clearAlpha);
  9441. },
  9442. render: render
  9443. };
  9444. }
  9445. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  9446. const maxVertexAttributes = gl.getParameter(34921);
  9447. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  9448. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9449. const bindingStates = {};
  9450. const defaultState = createBindingState(null);
  9451. let currentState = defaultState;
  9452. function setup(object, material, program, geometry, index) {
  9453. let updateBuffers = false;
  9454. if (vaoAvailable) {
  9455. const state = getBindingState(geometry, program, material);
  9456. if (currentState !== state) {
  9457. currentState = state;
  9458. bindVertexArrayObject(currentState.object);
  9459. }
  9460. updateBuffers = needsUpdate(geometry, index);
  9461. if (updateBuffers) saveCache(geometry, index);
  9462. } else {
  9463. const wireframe = material.wireframe === true;
  9464. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  9465. currentState.geometry = geometry.id;
  9466. currentState.program = program.id;
  9467. currentState.wireframe = wireframe;
  9468. updateBuffers = true;
  9469. }
  9470. }
  9471. if (object.isInstancedMesh === true) {
  9472. updateBuffers = true;
  9473. }
  9474. if (index !== null) {
  9475. attributes.update(index, 34963);
  9476. }
  9477. if (updateBuffers) {
  9478. setupVertexAttributes(object, material, program, geometry);
  9479. if (index !== null) {
  9480. gl.bindBuffer(34963, attributes.get(index).buffer);
  9481. }
  9482. }
  9483. }
  9484. function createVertexArrayObject() {
  9485. if (capabilities.isWebGL2) return gl.createVertexArray();
  9486. return extension.createVertexArrayOES();
  9487. }
  9488. function bindVertexArrayObject(vao) {
  9489. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  9490. return extension.bindVertexArrayOES(vao);
  9491. }
  9492. function deleteVertexArrayObject(vao) {
  9493. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  9494. return extension.deleteVertexArrayOES(vao);
  9495. }
  9496. function getBindingState(geometry, program, material) {
  9497. const wireframe = material.wireframe === true;
  9498. let programMap = bindingStates[geometry.id];
  9499. if (programMap === undefined) {
  9500. programMap = {};
  9501. bindingStates[geometry.id] = programMap;
  9502. }
  9503. let stateMap = programMap[program.id];
  9504. if (stateMap === undefined) {
  9505. stateMap = {};
  9506. programMap[program.id] = stateMap;
  9507. }
  9508. let state = stateMap[wireframe];
  9509. if (state === undefined) {
  9510. state = createBindingState(createVertexArrayObject());
  9511. stateMap[wireframe] = state;
  9512. }
  9513. return state;
  9514. }
  9515. function createBindingState(vao) {
  9516. const newAttributes = [];
  9517. const enabledAttributes = [];
  9518. const attributeDivisors = [];
  9519. for (let i = 0; i < maxVertexAttributes; i++) {
  9520. newAttributes[i] = 0;
  9521. enabledAttributes[i] = 0;
  9522. attributeDivisors[i] = 0;
  9523. }
  9524. return {
  9525. // for backward compatibility on non-VAO support browser
  9526. geometry: null,
  9527. program: null,
  9528. wireframe: false,
  9529. newAttributes: newAttributes,
  9530. enabledAttributes: enabledAttributes,
  9531. attributeDivisors: attributeDivisors,
  9532. object: vao,
  9533. attributes: {},
  9534. index: null
  9535. };
  9536. }
  9537. function needsUpdate(geometry, index) {
  9538. const cachedAttributes = currentState.attributes;
  9539. const geometryAttributes = geometry.attributes;
  9540. let attributesNum = 0;
  9541. for (const key in geometryAttributes) {
  9542. const cachedAttribute = cachedAttributes[key];
  9543. const geometryAttribute = geometryAttributes[key];
  9544. if (cachedAttribute === undefined) return true;
  9545. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9546. if (cachedAttribute.data !== geometryAttribute.data) return true;
  9547. attributesNum++;
  9548. }
  9549. if (currentState.attributesNum !== attributesNum) return true;
  9550. if (currentState.index !== index) return true;
  9551. return false;
  9552. }
  9553. function saveCache(geometry, index) {
  9554. const cache = {};
  9555. const attributes = geometry.attributes;
  9556. let attributesNum = 0;
  9557. for (const key in attributes) {
  9558. const attribute = attributes[key];
  9559. const data = {};
  9560. data.attribute = attribute;
  9561. if (attribute.data) {
  9562. data.data = attribute.data;
  9563. }
  9564. cache[key] = data;
  9565. attributesNum++;
  9566. }
  9567. currentState.attributes = cache;
  9568. currentState.attributesNum = attributesNum;
  9569. currentState.index = index;
  9570. }
  9571. function initAttributes() {
  9572. const newAttributes = currentState.newAttributes;
  9573. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9574. newAttributes[i] = 0;
  9575. }
  9576. }
  9577. function enableAttribute(attribute) {
  9578. enableAttributeAndDivisor(attribute, 0);
  9579. }
  9580. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9581. const newAttributes = currentState.newAttributes;
  9582. const enabledAttributes = currentState.enabledAttributes;
  9583. const attributeDivisors = currentState.attributeDivisors;
  9584. newAttributes[attribute] = 1;
  9585. if (enabledAttributes[attribute] === 0) {
  9586. gl.enableVertexAttribArray(attribute);
  9587. enabledAttributes[attribute] = 1;
  9588. }
  9589. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9590. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9591. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9592. attributeDivisors[attribute] = meshPerAttribute;
  9593. }
  9594. }
  9595. function disableUnusedAttributes() {
  9596. const newAttributes = currentState.newAttributes;
  9597. const enabledAttributes = currentState.enabledAttributes;
  9598. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9599. if (enabledAttributes[i] !== newAttributes[i]) {
  9600. gl.disableVertexAttribArray(i);
  9601. enabledAttributes[i] = 0;
  9602. }
  9603. }
  9604. }
  9605. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9606. if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
  9607. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9608. } else {
  9609. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9610. }
  9611. }
  9612. function setupVertexAttributes(object, material, program, geometry) {
  9613. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9614. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9615. }
  9616. initAttributes();
  9617. const geometryAttributes = geometry.attributes;
  9618. const programAttributes = program.getAttributes();
  9619. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9620. for (const name in programAttributes) {
  9621. const programAttribute = programAttributes[name];
  9622. if (programAttribute >= 0) {
  9623. const geometryAttribute = geometryAttributes[name];
  9624. if (geometryAttribute !== undefined) {
  9625. const normalized = geometryAttribute.normalized;
  9626. const size = geometryAttribute.itemSize;
  9627. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9628. if (attribute === undefined) continue;
  9629. const buffer = attribute.buffer;
  9630. const type = attribute.type;
  9631. const bytesPerElement = attribute.bytesPerElement;
  9632. if (geometryAttribute.isInterleavedBufferAttribute) {
  9633. const data = geometryAttribute.data;
  9634. const stride = data.stride;
  9635. const offset = geometryAttribute.offset;
  9636. if (data && data.isInstancedInterleavedBuffer) {
  9637. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  9638. if (geometry._maxInstanceCount === undefined) {
  9639. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9640. }
  9641. } else {
  9642. enableAttribute(programAttribute);
  9643. }
  9644. gl.bindBuffer(34962, buffer);
  9645. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  9646. } else {
  9647. if (geometryAttribute.isInstancedBufferAttribute) {
  9648. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  9649. if (geometry._maxInstanceCount === undefined) {
  9650. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9651. }
  9652. } else {
  9653. enableAttribute(programAttribute);
  9654. }
  9655. gl.bindBuffer(34962, buffer);
  9656. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  9657. }
  9658. } else if (name === 'instanceMatrix') {
  9659. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  9660. if (attribute === undefined) continue;
  9661. const buffer = attribute.buffer;
  9662. const type = attribute.type;
  9663. enableAttributeAndDivisor(programAttribute + 0, 1);
  9664. enableAttributeAndDivisor(programAttribute + 1, 1);
  9665. enableAttributeAndDivisor(programAttribute + 2, 1);
  9666. enableAttributeAndDivisor(programAttribute + 3, 1);
  9667. gl.bindBuffer(34962, buffer);
  9668. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  9669. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  9670. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  9671. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  9672. } else if (name === 'instanceColor') {
  9673. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  9674. if (attribute === undefined) continue;
  9675. const buffer = attribute.buffer;
  9676. const type = attribute.type;
  9677. enableAttributeAndDivisor(programAttribute, 1);
  9678. gl.bindBuffer(34962, buffer);
  9679. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  9680. } else if (materialDefaultAttributeValues !== undefined) {
  9681. const value = materialDefaultAttributeValues[name];
  9682. if (value !== undefined) {
  9683. switch (value.length) {
  9684. case 2:
  9685. gl.vertexAttrib2fv(programAttribute, value);
  9686. break;
  9687. case 3:
  9688. gl.vertexAttrib3fv(programAttribute, value);
  9689. break;
  9690. case 4:
  9691. gl.vertexAttrib4fv(programAttribute, value);
  9692. break;
  9693. default:
  9694. gl.vertexAttrib1fv(programAttribute, value);
  9695. }
  9696. }
  9697. }
  9698. }
  9699. }
  9700. disableUnusedAttributes();
  9701. }
  9702. function dispose() {
  9703. reset();
  9704. for (const geometryId in bindingStates) {
  9705. const programMap = bindingStates[geometryId];
  9706. for (const programId in programMap) {
  9707. const stateMap = programMap[programId];
  9708. for (const wireframe in stateMap) {
  9709. deleteVertexArrayObject(stateMap[wireframe].object);
  9710. delete stateMap[wireframe];
  9711. }
  9712. delete programMap[programId];
  9713. }
  9714. delete bindingStates[geometryId];
  9715. }
  9716. }
  9717. function releaseStatesOfGeometry(geometry) {
  9718. if (bindingStates[geometry.id] === undefined) return;
  9719. const programMap = bindingStates[geometry.id];
  9720. for (const programId in programMap) {
  9721. const stateMap = programMap[programId];
  9722. for (const wireframe in stateMap) {
  9723. deleteVertexArrayObject(stateMap[wireframe].object);
  9724. delete stateMap[wireframe];
  9725. }
  9726. delete programMap[programId];
  9727. }
  9728. delete bindingStates[geometry.id];
  9729. }
  9730. function releaseStatesOfProgram(program) {
  9731. for (const geometryId in bindingStates) {
  9732. const programMap = bindingStates[geometryId];
  9733. if (programMap[program.id] === undefined) continue;
  9734. const stateMap = programMap[program.id];
  9735. for (const wireframe in stateMap) {
  9736. deleteVertexArrayObject(stateMap[wireframe].object);
  9737. delete stateMap[wireframe];
  9738. }
  9739. delete programMap[program.id];
  9740. }
  9741. }
  9742. function reset() {
  9743. resetDefaultState();
  9744. if (currentState === defaultState) return;
  9745. currentState = defaultState;
  9746. bindVertexArrayObject(currentState.object);
  9747. } // for backward-compatilibity
  9748. function resetDefaultState() {
  9749. defaultState.geometry = null;
  9750. defaultState.program = null;
  9751. defaultState.wireframe = false;
  9752. }
  9753. return {
  9754. setup: setup,
  9755. reset: reset,
  9756. resetDefaultState: resetDefaultState,
  9757. dispose: dispose,
  9758. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9759. releaseStatesOfProgram: releaseStatesOfProgram,
  9760. initAttributes: initAttributes,
  9761. enableAttribute: enableAttribute,
  9762. disableUnusedAttributes: disableUnusedAttributes
  9763. };
  9764. }
  9765. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9766. const isWebGL2 = capabilities.isWebGL2;
  9767. let mode;
  9768. function setMode(value) {
  9769. mode = value;
  9770. }
  9771. function render(start, count) {
  9772. gl.drawArrays(mode, start, count);
  9773. info.update(count, mode, 1);
  9774. }
  9775. function renderInstances(start, count, primcount) {
  9776. if (primcount === 0) return;
  9777. let extension, methodName;
  9778. if (isWebGL2) {
  9779. extension = gl;
  9780. methodName = 'drawArraysInstanced';
  9781. } else {
  9782. extension = extensions.get('ANGLE_instanced_arrays');
  9783. methodName = 'drawArraysInstancedANGLE';
  9784. if (extension === null) {
  9785. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9786. return;
  9787. }
  9788. }
  9789. extension[methodName](mode, start, count, primcount);
  9790. info.update(count, mode, primcount);
  9791. } //
  9792. this.setMode = setMode;
  9793. this.render = render;
  9794. this.renderInstances = renderInstances;
  9795. }
  9796. function WebGLCapabilities(gl, extensions, parameters) {
  9797. let maxAnisotropy;
  9798. function getMaxAnisotropy() {
  9799. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9800. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9801. if (extension !== null) {
  9802. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9803. } else {
  9804. maxAnisotropy = 0;
  9805. }
  9806. return maxAnisotropy;
  9807. }
  9808. function getMaxPrecision(precision) {
  9809. if (precision === 'highp') {
  9810. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  9811. return 'highp';
  9812. }
  9813. precision = 'mediump';
  9814. }
  9815. if (precision === 'mediump') {
  9816. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  9817. return 'mediump';
  9818. }
  9819. }
  9820. return 'lowp';
  9821. }
  9822. /* eslint-disable no-undef */
  9823. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9824. /* eslint-enable no-undef */
  9825. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9826. const maxPrecision = getMaxPrecision(precision);
  9827. if (maxPrecision !== precision) {
  9828. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9829. precision = maxPrecision;
  9830. }
  9831. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9832. const maxTextures = gl.getParameter(34930);
  9833. const maxVertexTextures = gl.getParameter(35660);
  9834. const maxTextureSize = gl.getParameter(3379);
  9835. const maxCubemapSize = gl.getParameter(34076);
  9836. const maxAttributes = gl.getParameter(34921);
  9837. const maxVertexUniforms = gl.getParameter(36347);
  9838. const maxVaryings = gl.getParameter(36348);
  9839. const maxFragmentUniforms = gl.getParameter(36349);
  9840. const vertexTextures = maxVertexTextures > 0;
  9841. const floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  9842. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9843. const maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  9844. return {
  9845. isWebGL2: isWebGL2,
  9846. getMaxAnisotropy: getMaxAnisotropy,
  9847. getMaxPrecision: getMaxPrecision,
  9848. precision: precision,
  9849. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9850. maxTextures: maxTextures,
  9851. maxVertexTextures: maxVertexTextures,
  9852. maxTextureSize: maxTextureSize,
  9853. maxCubemapSize: maxCubemapSize,
  9854. maxAttributes: maxAttributes,
  9855. maxVertexUniforms: maxVertexUniforms,
  9856. maxVaryings: maxVaryings,
  9857. maxFragmentUniforms: maxFragmentUniforms,
  9858. vertexTextures: vertexTextures,
  9859. floatFragmentTextures: floatFragmentTextures,
  9860. floatVertexTextures: floatVertexTextures,
  9861. maxSamples: maxSamples
  9862. };
  9863. }
  9864. function WebGLClipping(properties) {
  9865. const scope = this;
  9866. let globalState = null,
  9867. numGlobalPlanes = 0,
  9868. localClippingEnabled = false,
  9869. renderingShadows = false;
  9870. const plane = new Plane(),
  9871. viewNormalMatrix = new Matrix3(),
  9872. uniform = {
  9873. value: null,
  9874. needsUpdate: false
  9875. };
  9876. this.uniform = uniform;
  9877. this.numPlanes = 0;
  9878. this.numIntersection = 0;
  9879. this.init = function (planes, enableLocalClipping, camera) {
  9880. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9881. // run another frame in order to reset the state:
  9882. numGlobalPlanes !== 0 || localClippingEnabled;
  9883. localClippingEnabled = enableLocalClipping;
  9884. globalState = projectPlanes(planes, camera, 0);
  9885. numGlobalPlanes = planes.length;
  9886. return enabled;
  9887. };
  9888. this.beginShadows = function () {
  9889. renderingShadows = true;
  9890. projectPlanes(null);
  9891. };
  9892. this.endShadows = function () {
  9893. renderingShadows = false;
  9894. resetGlobalState();
  9895. };
  9896. this.setState = function (material, camera, useCache) {
  9897. const planes = material.clippingPlanes,
  9898. clipIntersection = material.clipIntersection,
  9899. clipShadows = material.clipShadows;
  9900. const materialProperties = properties.get(material);
  9901. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9902. // there's no local clipping
  9903. if (renderingShadows) {
  9904. // there's no global clipping
  9905. projectPlanes(null);
  9906. } else {
  9907. resetGlobalState();
  9908. }
  9909. } else {
  9910. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9911. lGlobal = nGlobal * 4;
  9912. let dstArray = materialProperties.clippingState || null;
  9913. uniform.value = dstArray; // ensure unique state
  9914. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9915. for (let i = 0; i !== lGlobal; ++i) {
  9916. dstArray[i] = globalState[i];
  9917. }
  9918. materialProperties.clippingState = dstArray;
  9919. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9920. this.numPlanes += nGlobal;
  9921. }
  9922. };
  9923. function resetGlobalState() {
  9924. if (uniform.value !== globalState) {
  9925. uniform.value = globalState;
  9926. uniform.needsUpdate = numGlobalPlanes > 0;
  9927. }
  9928. scope.numPlanes = numGlobalPlanes;
  9929. scope.numIntersection = 0;
  9930. }
  9931. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9932. const nPlanes = planes !== null ? planes.length : 0;
  9933. let dstArray = null;
  9934. if (nPlanes !== 0) {
  9935. dstArray = uniform.value;
  9936. if (skipTransform !== true || dstArray === null) {
  9937. const flatSize = dstOffset + nPlanes * 4,
  9938. viewMatrix = camera.matrixWorldInverse;
  9939. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9940. if (dstArray === null || dstArray.length < flatSize) {
  9941. dstArray = new Float32Array(flatSize);
  9942. }
  9943. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9944. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9945. plane.normal.toArray(dstArray, i4);
  9946. dstArray[i4 + 3] = plane.constant;
  9947. }
  9948. }
  9949. uniform.value = dstArray;
  9950. uniform.needsUpdate = true;
  9951. }
  9952. scope.numPlanes = nPlanes;
  9953. scope.numIntersection = 0;
  9954. return dstArray;
  9955. }
  9956. }
  9957. function WebGLCubeMaps(renderer) {
  9958. let cubemaps = new WeakMap();
  9959. function mapTextureMapping(texture, mapping) {
  9960. if (mapping === EquirectangularReflectionMapping) {
  9961. texture.mapping = CubeReflectionMapping;
  9962. } else if (mapping === EquirectangularRefractionMapping) {
  9963. texture.mapping = CubeRefractionMapping;
  9964. }
  9965. return texture;
  9966. }
  9967. function get(texture) {
  9968. if (texture && texture.isTexture) {
  9969. const mapping = texture.mapping;
  9970. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9971. if (cubemaps.has(texture)) {
  9972. const cubemap = cubemaps.get(texture).texture;
  9973. return mapTextureMapping(cubemap, texture.mapping);
  9974. } else {
  9975. const image = texture.image;
  9976. if (image && image.height > 0) {
  9977. const currentRenderList = renderer.getRenderList();
  9978. const currentRenderTarget = renderer.getRenderTarget();
  9979. const currentRenderState = renderer.getRenderState();
  9980. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9981. renderTarget.fromEquirectangularTexture(renderer, texture);
  9982. cubemaps.set(texture, renderTarget);
  9983. renderer.setRenderTarget(currentRenderTarget);
  9984. renderer.setRenderList(currentRenderList);
  9985. renderer.setRenderState(currentRenderState);
  9986. texture.addEventListener('dispose', onTextureDispose);
  9987. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9988. } else {
  9989. // image not yet ready. try the conversion next frame
  9990. return null;
  9991. }
  9992. }
  9993. }
  9994. }
  9995. return texture;
  9996. }
  9997. function onTextureDispose(event) {
  9998. const texture = event.target;
  9999. texture.removeEventListener('dispose', onTextureDispose);
  10000. const cubemap = cubemaps.get(texture);
  10001. if (cubemap !== undefined) {
  10002. cubemaps.delete(texture);
  10003. cubemap.dispose();
  10004. }
  10005. }
  10006. function dispose() {
  10007. cubemaps = new WeakMap();
  10008. }
  10009. return {
  10010. get: get,
  10011. dispose: dispose
  10012. };
  10013. }
  10014. function WebGLExtensions(gl) {
  10015. const extensions = {};
  10016. return {
  10017. has: function (name) {
  10018. if (extensions[name] !== undefined) {
  10019. return extensions[name] !== null;
  10020. }
  10021. let extension;
  10022. switch (name) {
  10023. case 'WEBGL_depth_texture':
  10024. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10025. break;
  10026. case 'EXT_texture_filter_anisotropic':
  10027. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10028. break;
  10029. case 'WEBGL_compressed_texture_s3tc':
  10030. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10031. break;
  10032. case 'WEBGL_compressed_texture_pvrtc':
  10033. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10034. break;
  10035. default:
  10036. extension = gl.getExtension(name);
  10037. }
  10038. extensions[name] = extension;
  10039. return extension !== null;
  10040. },
  10041. get: function (name) {
  10042. if (!this.has(name)) {
  10043. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10044. }
  10045. return extensions[name];
  10046. }
  10047. };
  10048. }
  10049. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10050. const geometries = new WeakMap();
  10051. const wireframeAttributes = new WeakMap();
  10052. function onGeometryDispose(event) {
  10053. const geometry = event.target;
  10054. const buffergeometry = geometries.get(geometry);
  10055. if (buffergeometry.index !== null) {
  10056. attributes.remove(buffergeometry.index);
  10057. }
  10058. for (const name in buffergeometry.attributes) {
  10059. attributes.remove(buffergeometry.attributes[name]);
  10060. }
  10061. geometry.removeEventListener('dispose', onGeometryDispose);
  10062. geometries.delete(geometry);
  10063. const attribute = wireframeAttributes.get(buffergeometry);
  10064. if (attribute) {
  10065. attributes.remove(attribute);
  10066. wireframeAttributes.delete(buffergeometry);
  10067. }
  10068. bindingStates.releaseStatesOfGeometry(buffergeometry);
  10069. if (geometry.isInstancedBufferGeometry === true) {
  10070. delete geometry._maxInstanceCount;
  10071. } //
  10072. info.memory.geometries--;
  10073. }
  10074. function get(object, geometry) {
  10075. let buffergeometry = geometries.get(geometry);
  10076. if (buffergeometry) return buffergeometry;
  10077. geometry.addEventListener('dispose', onGeometryDispose);
  10078. if (geometry.isBufferGeometry) {
  10079. buffergeometry = geometry;
  10080. } else if (geometry.isGeometry) {
  10081. if (geometry._bufferGeometry === undefined) {
  10082. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10083. }
  10084. buffergeometry = geometry._bufferGeometry;
  10085. }
  10086. geometries.set(geometry, buffergeometry);
  10087. info.memory.geometries++;
  10088. return buffergeometry;
  10089. }
  10090. function update(geometry) {
  10091. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10092. for (const name in geometryAttributes) {
  10093. attributes.update(geometryAttributes[name], 34962);
  10094. } // morph targets
  10095. const morphAttributes = geometry.morphAttributes;
  10096. for (const name in morphAttributes) {
  10097. const array = morphAttributes[name];
  10098. for (let i = 0, l = array.length; i < l; i++) {
  10099. attributes.update(array[i], 34962);
  10100. }
  10101. }
  10102. }
  10103. function updateWireframeAttribute(geometry) {
  10104. const indices = [];
  10105. const geometryIndex = geometry.index;
  10106. const geometryPosition = geometry.attributes.position;
  10107. let version = 0;
  10108. if (geometryIndex !== null) {
  10109. const array = geometryIndex.array;
  10110. version = geometryIndex.version;
  10111. for (let i = 0, l = array.length; i < l; i += 3) {
  10112. const a = array[i + 0];
  10113. const b = array[i + 1];
  10114. const c = array[i + 2];
  10115. indices.push(a, b, b, c, c, a);
  10116. }
  10117. } else {
  10118. const array = geometryPosition.array;
  10119. version = geometryPosition.version;
  10120. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10121. const a = i + 0;
  10122. const b = i + 1;
  10123. const c = i + 2;
  10124. indices.push(a, b, b, c, c, a);
  10125. }
  10126. }
  10127. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10128. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10129. //
  10130. const previousAttribute = wireframeAttributes.get(geometry);
  10131. if (previousAttribute) attributes.remove(previousAttribute); //
  10132. wireframeAttributes.set(geometry, attribute);
  10133. }
  10134. function getWireframeAttribute(geometry) {
  10135. const currentAttribute = wireframeAttributes.get(geometry);
  10136. if (currentAttribute) {
  10137. const geometryIndex = geometry.index;
  10138. if (geometryIndex !== null) {
  10139. // if the attribute is obsolete, create a new one
  10140. if (currentAttribute.version < geometryIndex.version) {
  10141. updateWireframeAttribute(geometry);
  10142. }
  10143. }
  10144. } else {
  10145. updateWireframeAttribute(geometry);
  10146. }
  10147. return wireframeAttributes.get(geometry);
  10148. }
  10149. return {
  10150. get: get,
  10151. update: update,
  10152. getWireframeAttribute: getWireframeAttribute
  10153. };
  10154. }
  10155. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10156. const isWebGL2 = capabilities.isWebGL2;
  10157. let mode;
  10158. function setMode(value) {
  10159. mode = value;
  10160. }
  10161. let type, bytesPerElement;
  10162. function setIndex(value) {
  10163. type = value.type;
  10164. bytesPerElement = value.bytesPerElement;
  10165. }
  10166. function render(start, count) {
  10167. gl.drawElements(mode, count, type, start * bytesPerElement);
  10168. info.update(count, mode, 1);
  10169. }
  10170. function renderInstances(start, count, primcount) {
  10171. if (primcount === 0) return;
  10172. let extension, methodName;
  10173. if (isWebGL2) {
  10174. extension = gl;
  10175. methodName = 'drawElementsInstanced';
  10176. } else {
  10177. extension = extensions.get('ANGLE_instanced_arrays');
  10178. methodName = 'drawElementsInstancedANGLE';
  10179. if (extension === null) {
  10180. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10181. return;
  10182. }
  10183. }
  10184. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10185. info.update(count, mode, primcount);
  10186. } //
  10187. this.setMode = setMode;
  10188. this.setIndex = setIndex;
  10189. this.render = render;
  10190. this.renderInstances = renderInstances;
  10191. }
  10192. function WebGLInfo(gl) {
  10193. const memory = {
  10194. geometries: 0,
  10195. textures: 0
  10196. };
  10197. const render = {
  10198. frame: 0,
  10199. calls: 0,
  10200. triangles: 0,
  10201. points: 0,
  10202. lines: 0
  10203. };
  10204. function update(count, mode, instanceCount) {
  10205. render.calls++;
  10206. switch (mode) {
  10207. case 4:
  10208. render.triangles += instanceCount * (count / 3);
  10209. break;
  10210. case 1:
  10211. render.lines += instanceCount * (count / 2);
  10212. break;
  10213. case 3:
  10214. render.lines += instanceCount * (count - 1);
  10215. break;
  10216. case 2:
  10217. render.lines += instanceCount * count;
  10218. break;
  10219. case 0:
  10220. render.points += instanceCount * count;
  10221. break;
  10222. default:
  10223. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10224. break;
  10225. }
  10226. }
  10227. function reset() {
  10228. render.frame++;
  10229. render.calls = 0;
  10230. render.triangles = 0;
  10231. render.points = 0;
  10232. render.lines = 0;
  10233. }
  10234. return {
  10235. memory: memory,
  10236. render: render,
  10237. programs: null,
  10238. autoReset: true,
  10239. reset: reset,
  10240. update: update
  10241. };
  10242. }
  10243. function numericalSort(a, b) {
  10244. return a[0] - b[0];
  10245. }
  10246. function absNumericalSort(a, b) {
  10247. return Math.abs(b[1]) - Math.abs(a[1]);
  10248. }
  10249. function WebGLMorphtargets(gl) {
  10250. const influencesList = {};
  10251. const morphInfluences = new Float32Array(8);
  10252. const workInfluences = [];
  10253. for (let i = 0; i < 8; i++) {
  10254. workInfluences[i] = [i, 0];
  10255. }
  10256. function update(object, geometry, material, program) {
  10257. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10258. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10259. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10260. let influences = influencesList[geometry.id];
  10261. if (influences === undefined) {
  10262. // initialise list
  10263. influences = [];
  10264. for (let i = 0; i < length; i++) {
  10265. influences[i] = [i, 0];
  10266. }
  10267. influencesList[geometry.id] = influences;
  10268. } // Collect influences
  10269. for (let i = 0; i < length; i++) {
  10270. const influence = influences[i];
  10271. influence[0] = i;
  10272. influence[1] = objectInfluences[i];
  10273. }
  10274. influences.sort(absNumericalSort);
  10275. for (let i = 0; i < 8; i++) {
  10276. if (i < length && influences[i][1]) {
  10277. workInfluences[i][0] = influences[i][0];
  10278. workInfluences[i][1] = influences[i][1];
  10279. } else {
  10280. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10281. workInfluences[i][1] = 0;
  10282. }
  10283. }
  10284. workInfluences.sort(numericalSort);
  10285. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10286. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10287. let morphInfluencesSum = 0;
  10288. for (let i = 0; i < 8; i++) {
  10289. const influence = workInfluences[i];
  10290. const index = influence[0];
  10291. const value = influence[1];
  10292. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10293. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10294. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10295. }
  10296. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10297. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10298. }
  10299. morphInfluences[i] = value;
  10300. morphInfluencesSum += value;
  10301. } else {
  10302. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10303. geometry.deleteAttribute('morphTarget' + i);
  10304. }
  10305. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10306. geometry.deleteAttribute('morphNormal' + i);
  10307. }
  10308. morphInfluences[i] = 0;
  10309. }
  10310. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10311. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10312. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10313. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10314. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10315. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10316. }
  10317. return {
  10318. update: update
  10319. };
  10320. }
  10321. function WebGLObjects(gl, geometries, attributes, info) {
  10322. let updateMap = new WeakMap();
  10323. function update(object) {
  10324. const frame = info.render.frame;
  10325. const geometry = object.geometry;
  10326. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10327. if (updateMap.get(buffergeometry) !== frame) {
  10328. if (geometry.isGeometry) {
  10329. buffergeometry.updateFromObject(object);
  10330. }
  10331. geometries.update(buffergeometry);
  10332. updateMap.set(buffergeometry, frame);
  10333. }
  10334. if (object.isInstancedMesh) {
  10335. attributes.update(object.instanceMatrix, 34962);
  10336. if (object.instanceColor !== null) {
  10337. attributes.update(object.instanceColor, 34962);
  10338. }
  10339. }
  10340. return buffergeometry;
  10341. }
  10342. function dispose() {
  10343. updateMap = new WeakMap();
  10344. }
  10345. return {
  10346. update: update,
  10347. dispose: dispose
  10348. };
  10349. }
  10350. function DataTexture2DArray(data = null, width = 1, height = 1, depth = 1) {
  10351. Texture.call(this, null);
  10352. this.image = {
  10353. data,
  10354. width,
  10355. height,
  10356. depth
  10357. };
  10358. this.magFilter = NearestFilter;
  10359. this.minFilter = NearestFilter;
  10360. this.wrapR = ClampToEdgeWrapping;
  10361. this.generateMipmaps = false;
  10362. this.flipY = false;
  10363. this.needsUpdate = true;
  10364. }
  10365. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10366. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10367. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10368. function DataTexture3D(data = null, width = 1, height = 1, depth = 1) {
  10369. // We're going to add .setXXX() methods for setting properties later.
  10370. // Users can still set in DataTexture3D directly.
  10371. //
  10372. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10373. // texture.anisotropy = 16;
  10374. //
  10375. // See #14839
  10376. Texture.call(this, null);
  10377. this.image = {
  10378. data,
  10379. width,
  10380. height,
  10381. depth
  10382. };
  10383. this.magFilter = NearestFilter;
  10384. this.minFilter = NearestFilter;
  10385. this.wrapR = ClampToEdgeWrapping;
  10386. this.generateMipmaps = false;
  10387. this.flipY = false;
  10388. this.needsUpdate = true;
  10389. }
  10390. DataTexture3D.prototype = Object.create(Texture.prototype);
  10391. DataTexture3D.prototype.constructor = DataTexture3D;
  10392. DataTexture3D.prototype.isDataTexture3D = true;
  10393. /**
  10394. * Uniforms of a program.
  10395. * Those form a tree structure with a special top-level container for the root,
  10396. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10397. *
  10398. *
  10399. * Properties of inner nodes including the top-level container:
  10400. *
  10401. * .seq - array of nested uniforms
  10402. * .map - nested uniforms by name
  10403. *
  10404. *
  10405. * Methods of all nodes except the top-level container:
  10406. *
  10407. * .setValue( gl, value, [textures] )
  10408. *
  10409. * uploads a uniform value(s)
  10410. * the 'textures' parameter is needed for sampler uniforms
  10411. *
  10412. *
  10413. * Static methods of the top-level container (textures factorizations):
  10414. *
  10415. * .upload( gl, seq, values, textures )
  10416. *
  10417. * sets uniforms in 'seq' to 'values[id].value'
  10418. *
  10419. * .seqWithValue( seq, values ) : filteredSeq
  10420. *
  10421. * filters 'seq' entries with corresponding entry in values
  10422. *
  10423. *
  10424. * Methods of the top-level container (textures factorizations):
  10425. *
  10426. * .setValue( gl, name, value, textures )
  10427. *
  10428. * sets uniform with name 'name' to 'value'
  10429. *
  10430. * .setOptional( gl, obj, prop )
  10431. *
  10432. * like .set for an optional property of the object
  10433. *
  10434. */
  10435. const emptyTexture = new Texture();
  10436. const emptyTexture2dArray = new DataTexture2DArray();
  10437. const emptyTexture3d = new DataTexture3D();
  10438. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10439. // Array Caches (provide typed arrays for temporary by size)
  10440. const arrayCacheF32 = [];
  10441. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10442. const mat4array = new Float32Array(16);
  10443. const mat3array = new Float32Array(9);
  10444. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10445. function flatten(array, nBlocks, blockSize) {
  10446. const firstElem = array[0];
  10447. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10448. // see http://jacksondunstan.com/articles/983
  10449. const n = nBlocks * blockSize;
  10450. let r = arrayCacheF32[n];
  10451. if (r === undefined) {
  10452. r = new Float32Array(n);
  10453. arrayCacheF32[n] = r;
  10454. }
  10455. if (nBlocks !== 0) {
  10456. firstElem.toArray(r, 0);
  10457. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10458. offset += blockSize;
  10459. array[i].toArray(r, offset);
  10460. }
  10461. }
  10462. return r;
  10463. }
  10464. function arraysEqual(a, b) {
  10465. if (a.length !== b.length) return false;
  10466. for (let i = 0, l = a.length; i < l; i++) {
  10467. if (a[i] !== b[i]) return false;
  10468. }
  10469. return true;
  10470. }
  10471. function copyArray(a, b) {
  10472. for (let i = 0, l = b.length; i < l; i++) {
  10473. a[i] = b[i];
  10474. }
  10475. } // Texture unit allocation
  10476. function allocTexUnits(textures, n) {
  10477. let r = arrayCacheI32[n];
  10478. if (r === undefined) {
  10479. r = new Int32Array(n);
  10480. arrayCacheI32[n] = r;
  10481. }
  10482. for (let i = 0; i !== n; ++i) {
  10483. r[i] = textures.allocateTextureUnit();
  10484. }
  10485. return r;
  10486. } // --- Setters ---
  10487. // Note: Defining these methods externally, because they come in a bunch
  10488. // and this way their names minify.
  10489. // Single scalar
  10490. function setValueV1f(gl, v) {
  10491. const cache = this.cache;
  10492. if (cache[0] === v) return;
  10493. gl.uniform1f(this.addr, v);
  10494. cache[0] = v;
  10495. } // Single float vector (from flat array or THREE.VectorN)
  10496. function setValueV2f(gl, v) {
  10497. const cache = this.cache;
  10498. if (v.x !== undefined) {
  10499. if (cache[0] !== v.x || cache[1] !== v.y) {
  10500. gl.uniform2f(this.addr, v.x, v.y);
  10501. cache[0] = v.x;
  10502. cache[1] = v.y;
  10503. }
  10504. } else {
  10505. if (arraysEqual(cache, v)) return;
  10506. gl.uniform2fv(this.addr, v);
  10507. copyArray(cache, v);
  10508. }
  10509. }
  10510. function setValueV3f(gl, v) {
  10511. const cache = this.cache;
  10512. if (v.x !== undefined) {
  10513. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10514. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10515. cache[0] = v.x;
  10516. cache[1] = v.y;
  10517. cache[2] = v.z;
  10518. }
  10519. } else if (v.r !== undefined) {
  10520. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10521. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10522. cache[0] = v.r;
  10523. cache[1] = v.g;
  10524. cache[2] = v.b;
  10525. }
  10526. } else {
  10527. if (arraysEqual(cache, v)) return;
  10528. gl.uniform3fv(this.addr, v);
  10529. copyArray(cache, v);
  10530. }
  10531. }
  10532. function setValueV4f(gl, v) {
  10533. const cache = this.cache;
  10534. if (v.x !== undefined) {
  10535. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10536. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10537. cache[0] = v.x;
  10538. cache[1] = v.y;
  10539. cache[2] = v.z;
  10540. cache[3] = v.w;
  10541. }
  10542. } else {
  10543. if (arraysEqual(cache, v)) return;
  10544. gl.uniform4fv(this.addr, v);
  10545. copyArray(cache, v);
  10546. }
  10547. } // Single matrix (from flat array or MatrixN)
  10548. function setValueM2(gl, v) {
  10549. const cache = this.cache;
  10550. const elements = v.elements;
  10551. if (elements === undefined) {
  10552. if (arraysEqual(cache, v)) return;
  10553. gl.uniformMatrix2fv(this.addr, false, v);
  10554. copyArray(cache, v);
  10555. } else {
  10556. if (arraysEqual(cache, elements)) return;
  10557. mat2array.set(elements);
  10558. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10559. copyArray(cache, elements);
  10560. }
  10561. }
  10562. function setValueM3(gl, v) {
  10563. const cache = this.cache;
  10564. const elements = v.elements;
  10565. if (elements === undefined) {
  10566. if (arraysEqual(cache, v)) return;
  10567. gl.uniformMatrix3fv(this.addr, false, v);
  10568. copyArray(cache, v);
  10569. } else {
  10570. if (arraysEqual(cache, elements)) return;
  10571. mat3array.set(elements);
  10572. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10573. copyArray(cache, elements);
  10574. }
  10575. }
  10576. function setValueM4(gl, v) {
  10577. const cache = this.cache;
  10578. const elements = v.elements;
  10579. if (elements === undefined) {
  10580. if (arraysEqual(cache, v)) return;
  10581. gl.uniformMatrix4fv(this.addr, false, v);
  10582. copyArray(cache, v);
  10583. } else {
  10584. if (arraysEqual(cache, elements)) return;
  10585. mat4array.set(elements);
  10586. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10587. copyArray(cache, elements);
  10588. }
  10589. } // Single texture (2D / Cube)
  10590. function setValueT1(gl, v, textures) {
  10591. const cache = this.cache;
  10592. const unit = textures.allocateTextureUnit();
  10593. if (cache[0] !== unit) {
  10594. gl.uniform1i(this.addr, unit);
  10595. cache[0] = unit;
  10596. }
  10597. textures.safeSetTexture2D(v || emptyTexture, unit);
  10598. }
  10599. function setValueT2DArray1(gl, v, textures) {
  10600. const cache = this.cache;
  10601. const unit = textures.allocateTextureUnit();
  10602. if (cache[0] !== unit) {
  10603. gl.uniform1i(this.addr, unit);
  10604. cache[0] = unit;
  10605. }
  10606. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10607. }
  10608. function setValueT3D1(gl, v, textures) {
  10609. const cache = this.cache;
  10610. const unit = textures.allocateTextureUnit();
  10611. if (cache[0] !== unit) {
  10612. gl.uniform1i(this.addr, unit);
  10613. cache[0] = unit;
  10614. }
  10615. textures.setTexture3D(v || emptyTexture3d, unit);
  10616. }
  10617. function setValueT6(gl, v, textures) {
  10618. const cache = this.cache;
  10619. const unit = textures.allocateTextureUnit();
  10620. if (cache[0] !== unit) {
  10621. gl.uniform1i(this.addr, unit);
  10622. cache[0] = unit;
  10623. }
  10624. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10625. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10626. function setValueV1i(gl, v) {
  10627. const cache = this.cache;
  10628. if (cache[0] === v) return;
  10629. gl.uniform1i(this.addr, v);
  10630. cache[0] = v;
  10631. }
  10632. function setValueV2i(gl, v) {
  10633. const cache = this.cache;
  10634. if (arraysEqual(cache, v)) return;
  10635. gl.uniform2iv(this.addr, v);
  10636. copyArray(cache, v);
  10637. }
  10638. function setValueV3i(gl, v) {
  10639. const cache = this.cache;
  10640. if (arraysEqual(cache, v)) return;
  10641. gl.uniform3iv(this.addr, v);
  10642. copyArray(cache, v);
  10643. }
  10644. function setValueV4i(gl, v) {
  10645. const cache = this.cache;
  10646. if (arraysEqual(cache, v)) return;
  10647. gl.uniform4iv(this.addr, v);
  10648. copyArray(cache, v);
  10649. } // uint
  10650. function setValueV1ui(gl, v) {
  10651. const cache = this.cache;
  10652. if (cache[0] === v) return;
  10653. gl.uniform1ui(this.addr, v);
  10654. cache[0] = v;
  10655. } // Helper to pick the right setter for the singular case
  10656. function getSingularSetter(type) {
  10657. switch (type) {
  10658. case 0x1406:
  10659. return setValueV1f;
  10660. // FLOAT
  10661. case 0x8b50:
  10662. return setValueV2f;
  10663. // _VEC2
  10664. case 0x8b51:
  10665. return setValueV3f;
  10666. // _VEC3
  10667. case 0x8b52:
  10668. return setValueV4f;
  10669. // _VEC4
  10670. case 0x8b5a:
  10671. return setValueM2;
  10672. // _MAT2
  10673. case 0x8b5b:
  10674. return setValueM3;
  10675. // _MAT3
  10676. case 0x8b5c:
  10677. return setValueM4;
  10678. // _MAT4
  10679. case 0x1404:
  10680. case 0x8b56:
  10681. return setValueV1i;
  10682. // INT, BOOL
  10683. case 0x8b53:
  10684. case 0x8b57:
  10685. return setValueV2i;
  10686. // _VEC2
  10687. case 0x8b54:
  10688. case 0x8b58:
  10689. return setValueV3i;
  10690. // _VEC3
  10691. case 0x8b55:
  10692. case 0x8b59:
  10693. return setValueV4i;
  10694. // _VEC4
  10695. case 0x1405:
  10696. return setValueV1ui;
  10697. // UINT
  10698. case 0x8b5e: // SAMPLER_2D
  10699. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10700. case 0x8dca: // INT_SAMPLER_2D
  10701. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10702. case 0x8b62:
  10703. // SAMPLER_2D_SHADOW
  10704. return setValueT1;
  10705. case 0x8b5f: // SAMPLER_3D
  10706. case 0x8dcb: // INT_SAMPLER_3D
  10707. case 0x8dd3:
  10708. // UNSIGNED_INT_SAMPLER_3D
  10709. return setValueT3D1;
  10710. case 0x8b60: // SAMPLER_CUBE
  10711. case 0x8dcc: // INT_SAMPLER_CUBE
  10712. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10713. case 0x8dc5:
  10714. // SAMPLER_CUBE_SHADOW
  10715. return setValueT6;
  10716. case 0x8dc1: // SAMPLER_2D_ARRAY
  10717. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10718. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10719. case 0x8dc4:
  10720. // SAMPLER_2D_ARRAY_SHADOW
  10721. return setValueT2DArray1;
  10722. }
  10723. } // Array of scalars
  10724. function setValueV1fArray(gl, v) {
  10725. gl.uniform1fv(this.addr, v);
  10726. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10727. function setValueV1iArray(gl, v) {
  10728. gl.uniform1iv(this.addr, v);
  10729. }
  10730. function setValueV2iArray(gl, v) {
  10731. gl.uniform2iv(this.addr, v);
  10732. }
  10733. function setValueV3iArray(gl, v) {
  10734. gl.uniform3iv(this.addr, v);
  10735. }
  10736. function setValueV4iArray(gl, v) {
  10737. gl.uniform4iv(this.addr, v);
  10738. } // Array of vectors (flat or from THREE classes)
  10739. function setValueV2fArray(gl, v) {
  10740. const data = flatten(v, this.size, 2);
  10741. gl.uniform2fv(this.addr, data);
  10742. }
  10743. function setValueV3fArray(gl, v) {
  10744. const data = flatten(v, this.size, 3);
  10745. gl.uniform3fv(this.addr, data);
  10746. }
  10747. function setValueV4fArray(gl, v) {
  10748. const data = flatten(v, this.size, 4);
  10749. gl.uniform4fv(this.addr, data);
  10750. } // Array of matrices (flat or from THREE clases)
  10751. function setValueM2Array(gl, v) {
  10752. const data = flatten(v, this.size, 4);
  10753. gl.uniformMatrix2fv(this.addr, false, data);
  10754. }
  10755. function setValueM3Array(gl, v) {
  10756. const data = flatten(v, this.size, 9);
  10757. gl.uniformMatrix3fv(this.addr, false, data);
  10758. }
  10759. function setValueM4Array(gl, v) {
  10760. const data = flatten(v, this.size, 16);
  10761. gl.uniformMatrix4fv(this.addr, false, data);
  10762. } // Array of textures (2D / Cube)
  10763. function setValueT1Array(gl, v, textures) {
  10764. const n = v.length;
  10765. const units = allocTexUnits(textures, n);
  10766. gl.uniform1iv(this.addr, units);
  10767. for (let i = 0; i !== n; ++i) {
  10768. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10769. }
  10770. }
  10771. function setValueT6Array(gl, v, textures) {
  10772. const n = v.length;
  10773. const units = allocTexUnits(textures, n);
  10774. gl.uniform1iv(this.addr, units);
  10775. for (let i = 0; i !== n; ++i) {
  10776. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10777. }
  10778. } // Helper to pick the right setter for a pure (bottom-level) array
  10779. function getPureArraySetter(type) {
  10780. switch (type) {
  10781. case 0x1406:
  10782. return setValueV1fArray;
  10783. // FLOAT
  10784. case 0x8b50:
  10785. return setValueV2fArray;
  10786. // _VEC2
  10787. case 0x8b51:
  10788. return setValueV3fArray;
  10789. // _VEC3
  10790. case 0x8b52:
  10791. return setValueV4fArray;
  10792. // _VEC4
  10793. case 0x8b5a:
  10794. return setValueM2Array;
  10795. // _MAT2
  10796. case 0x8b5b:
  10797. return setValueM3Array;
  10798. // _MAT3
  10799. case 0x8b5c:
  10800. return setValueM4Array;
  10801. // _MAT4
  10802. case 0x1404:
  10803. case 0x8b56:
  10804. return setValueV1iArray;
  10805. // INT, BOOL
  10806. case 0x8b53:
  10807. case 0x8b57:
  10808. return setValueV2iArray;
  10809. // _VEC2
  10810. case 0x8b54:
  10811. case 0x8b58:
  10812. return setValueV3iArray;
  10813. // _VEC3
  10814. case 0x8b55:
  10815. case 0x8b59:
  10816. return setValueV4iArray;
  10817. // _VEC4
  10818. case 0x8b5e: // SAMPLER_2D
  10819. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10820. case 0x8dca: // INT_SAMPLER_2D
  10821. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10822. case 0x8b62:
  10823. // SAMPLER_2D_SHADOW
  10824. return setValueT1Array;
  10825. case 0x8b60: // SAMPLER_CUBE
  10826. case 0x8dcc: // INT_SAMPLER_CUBE
  10827. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10828. case 0x8dc5:
  10829. // SAMPLER_CUBE_SHADOW
  10830. return setValueT6Array;
  10831. }
  10832. } // --- Uniform Classes ---
  10833. function SingleUniform(id, activeInfo, addr) {
  10834. this.id = id;
  10835. this.addr = addr;
  10836. this.cache = [];
  10837. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10838. }
  10839. function PureArrayUniform(id, activeInfo, addr) {
  10840. this.id = id;
  10841. this.addr = addr;
  10842. this.cache = [];
  10843. this.size = activeInfo.size;
  10844. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10845. }
  10846. PureArrayUniform.prototype.updateCache = function (data) {
  10847. const cache = this.cache;
  10848. if (data instanceof Float32Array && cache.length !== data.length) {
  10849. this.cache = new Float32Array(data.length);
  10850. }
  10851. copyArray(cache, data);
  10852. };
  10853. function StructuredUniform(id) {
  10854. this.id = id;
  10855. this.seq = [];
  10856. this.map = {};
  10857. }
  10858. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10859. const seq = this.seq;
  10860. for (let i = 0, n = seq.length; i !== n; ++i) {
  10861. const u = seq[i];
  10862. u.setValue(gl, value[u.id], textures);
  10863. }
  10864. }; // --- Top-level ---
  10865. // Parser - builds up the property tree from the path strings
  10866. const RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  10867. // - the identifier (member name or array index)
  10868. // - followed by an optional right bracket (found when array index)
  10869. // - followed by an optional left bracket or dot (type of subscript)
  10870. //
  10871. // Note: These portions can be read in a non-overlapping fashion and
  10872. // allow straightforward parsing of the hierarchy that WebGL encodes
  10873. // in the uniform names.
  10874. function addUniform(container, uniformObject) {
  10875. container.seq.push(uniformObject);
  10876. container.map[uniformObject.id] = uniformObject;
  10877. }
  10878. function parseUniform(activeInfo, addr, container) {
  10879. const path = activeInfo.name,
  10880. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10881. RePathPart.lastIndex = 0;
  10882. while (true) {
  10883. const match = RePathPart.exec(path),
  10884. matchEnd = RePathPart.lastIndex;
  10885. let id = match[1];
  10886. const idIsIndex = match[2] === ']',
  10887. subscript = match[3];
  10888. if (idIsIndex) id = id | 0; // convert to integer
  10889. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10890. // bare name or "pure" bottom-level array "[0]" suffix
  10891. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10892. break;
  10893. } else {
  10894. // step into inner node / create it in case it doesn't exist
  10895. const map = container.map;
  10896. let next = map[id];
  10897. if (next === undefined) {
  10898. next = new StructuredUniform(id);
  10899. addUniform(container, next);
  10900. }
  10901. container = next;
  10902. }
  10903. }
  10904. } // Root Container
  10905. function WebGLUniforms(gl, program) {
  10906. this.seq = [];
  10907. this.map = {};
  10908. const n = gl.getProgramParameter(program, 35718);
  10909. for (let i = 0; i < n; ++i) {
  10910. const info = gl.getActiveUniform(program, i),
  10911. addr = gl.getUniformLocation(program, info.name);
  10912. parseUniform(info, addr, this);
  10913. }
  10914. }
  10915. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10916. const u = this.map[name];
  10917. if (u !== undefined) u.setValue(gl, value, textures);
  10918. };
  10919. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10920. const v = object[name];
  10921. if (v !== undefined) this.setValue(gl, name, v);
  10922. }; // Static interface
  10923. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10924. for (let i = 0, n = seq.length; i !== n; ++i) {
  10925. const u = seq[i],
  10926. v = values[u.id];
  10927. if (v.needsUpdate !== false) {
  10928. // note: always updating when .needsUpdate is undefined
  10929. u.setValue(gl, v.value, textures);
  10930. }
  10931. }
  10932. };
  10933. WebGLUniforms.seqWithValue = function (seq, values) {
  10934. const r = [];
  10935. for (let i = 0, n = seq.length; i !== n; ++i) {
  10936. const u = seq[i];
  10937. if (u.id in values) r.push(u);
  10938. }
  10939. return r;
  10940. };
  10941. function WebGLShader(gl, type, string) {
  10942. const shader = gl.createShader(type);
  10943. gl.shaderSource(shader, string);
  10944. gl.compileShader(shader);
  10945. return shader;
  10946. }
  10947. let programIdCount = 0;
  10948. function addLineNumbers(string) {
  10949. const lines = string.split('\n');
  10950. for (let i = 0; i < lines.length; i++) {
  10951. lines[i] = i + 1 + ': ' + lines[i];
  10952. }
  10953. return lines.join('\n');
  10954. }
  10955. function getEncodingComponents(encoding) {
  10956. switch (encoding) {
  10957. case LinearEncoding:
  10958. return ['Linear', '( value )'];
  10959. case sRGBEncoding:
  10960. return ['sRGB', '( value )'];
  10961. case RGBEEncoding:
  10962. return ['RGBE', '( value )'];
  10963. case RGBM7Encoding:
  10964. return ['RGBM', '( value, 7.0 )'];
  10965. case RGBM16Encoding:
  10966. return ['RGBM', '( value, 16.0 )'];
  10967. case RGBDEncoding:
  10968. return ['RGBD', '( value, 256.0 )'];
  10969. case GammaEncoding:
  10970. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10971. case LogLuvEncoding:
  10972. return ['LogLuv', '( value )'];
  10973. default:
  10974. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10975. return ['Linear', '( value )'];
  10976. }
  10977. }
  10978. function getShaderErrors(gl, shader, type) {
  10979. const status = gl.getShaderParameter(shader, 35713);
  10980. const log = gl.getShaderInfoLog(shader).trim();
  10981. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10982. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10983. const source = gl.getShaderSource(shader);
  10984. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10985. }
  10986. function getTexelDecodingFunction(functionName, encoding) {
  10987. const components = getEncodingComponents(encoding);
  10988. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10989. }
  10990. function getTexelEncodingFunction(functionName, encoding) {
  10991. const components = getEncodingComponents(encoding);
  10992. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10993. }
  10994. function getToneMappingFunction(functionName, toneMapping) {
  10995. let toneMappingName;
  10996. switch (toneMapping) {
  10997. case LinearToneMapping:
  10998. toneMappingName = 'Linear';
  10999. break;
  11000. case ReinhardToneMapping:
  11001. toneMappingName = 'Reinhard';
  11002. break;
  11003. case CineonToneMapping:
  11004. toneMappingName = 'OptimizedCineon';
  11005. break;
  11006. case ACESFilmicToneMapping:
  11007. toneMappingName = 'ACESFilmic';
  11008. break;
  11009. case CustomToneMapping:
  11010. toneMappingName = 'Custom';
  11011. break;
  11012. default:
  11013. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11014. toneMappingName = 'Linear';
  11015. }
  11016. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11017. }
  11018. function generateExtensions(parameters) {
  11019. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11020. return chunks.filter(filterEmptyLine).join('\n');
  11021. }
  11022. function generateDefines(defines) {
  11023. const chunks = [];
  11024. for (const name in defines) {
  11025. const value = defines[name];
  11026. if (value === false) continue;
  11027. chunks.push('#define ' + name + ' ' + value);
  11028. }
  11029. return chunks.join('\n');
  11030. }
  11031. function fetchAttributeLocations(gl, program) {
  11032. const attributes = {};
  11033. const n = gl.getProgramParameter(program, 35721);
  11034. for (let i = 0; i < n; i++) {
  11035. const info = gl.getActiveAttrib(program, i);
  11036. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11037. attributes[name] = gl.getAttribLocation(program, name);
  11038. }
  11039. return attributes;
  11040. }
  11041. function filterEmptyLine(string) {
  11042. return string !== '';
  11043. }
  11044. function replaceLightNums(string, parameters) {
  11045. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11046. }
  11047. function replaceClippingPlaneNums(string, parameters) {
  11048. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11049. } // Resolve Includes
  11050. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11051. function resolveIncludes(string) {
  11052. return string.replace(includePattern, includeReplacer);
  11053. }
  11054. function includeReplacer(match, include) {
  11055. const string = ShaderChunk[include];
  11056. if (string === undefined) {
  11057. throw new Error('Can not resolve #include <' + include + '>');
  11058. }
  11059. return resolveIncludes(string);
  11060. } // Unroll Loops
  11061. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11062. 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;
  11063. function unrollLoops(string) {
  11064. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11065. }
  11066. function deprecatedLoopReplacer(match, start, end, snippet) {
  11067. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11068. return loopReplacer(match, start, end, snippet);
  11069. }
  11070. function loopReplacer(match, start, end, snippet) {
  11071. let string = '';
  11072. for (let i = parseInt(start); i < parseInt(end); i++) {
  11073. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11074. }
  11075. return string;
  11076. } //
  11077. function generatePrecision(parameters) {
  11078. let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11079. if (parameters.precision === "highp") {
  11080. precisionstring += "\n#define HIGH_PRECISION";
  11081. } else if (parameters.precision === "mediump") {
  11082. precisionstring += "\n#define MEDIUM_PRECISION";
  11083. } else if (parameters.precision === "lowp") {
  11084. precisionstring += "\n#define LOW_PRECISION";
  11085. }
  11086. return precisionstring;
  11087. }
  11088. function generateShadowMapTypeDefine(parameters) {
  11089. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11090. if (parameters.shadowMapType === PCFShadowMap) {
  11091. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11092. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11093. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11094. } else if (parameters.shadowMapType === VSMShadowMap) {
  11095. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11096. }
  11097. return shadowMapTypeDefine;
  11098. }
  11099. function generateEnvMapTypeDefine(parameters) {
  11100. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11101. if (parameters.envMap) {
  11102. switch (parameters.envMapMode) {
  11103. case CubeReflectionMapping:
  11104. case CubeRefractionMapping:
  11105. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11106. break;
  11107. case CubeUVReflectionMapping:
  11108. case CubeUVRefractionMapping:
  11109. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11110. break;
  11111. }
  11112. }
  11113. return envMapTypeDefine;
  11114. }
  11115. function generateEnvMapModeDefine(parameters) {
  11116. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11117. if (parameters.envMap) {
  11118. switch (parameters.envMapMode) {
  11119. case CubeRefractionMapping:
  11120. case CubeUVRefractionMapping:
  11121. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11122. break;
  11123. }
  11124. }
  11125. return envMapModeDefine;
  11126. }
  11127. function generateEnvMapBlendingDefine(parameters) {
  11128. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11129. if (parameters.envMap) {
  11130. switch (parameters.combine) {
  11131. case MultiplyOperation:
  11132. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11133. break;
  11134. case MixOperation:
  11135. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11136. break;
  11137. case AddOperation:
  11138. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11139. break;
  11140. }
  11141. }
  11142. return envMapBlendingDefine;
  11143. }
  11144. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11145. const gl = renderer.getContext();
  11146. const defines = parameters.defines;
  11147. let vertexShader = parameters.vertexShader;
  11148. let fragmentShader = parameters.fragmentShader;
  11149. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11150. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11151. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11152. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11153. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11154. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11155. const customDefines = generateDefines(defines);
  11156. const program = gl.createProgram();
  11157. let prefixVertex, prefixFragment;
  11158. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + "\n" : '';
  11159. if (parameters.isRawShaderMaterial) {
  11160. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11161. if (prefixVertex.length > 0) {
  11162. prefixVertex += '\n';
  11163. }
  11164. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11165. if (prefixFragment.length > 0) {
  11166. prefixFragment += '\n';
  11167. }
  11168. } else {
  11169. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11170. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11171. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11172. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11173. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11174. }
  11175. vertexShader = resolveIncludes(vertexShader);
  11176. vertexShader = replaceLightNums(vertexShader, parameters);
  11177. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11178. fragmentShader = resolveIncludes(fragmentShader);
  11179. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11180. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11181. vertexShader = unrollLoops(vertexShader);
  11182. fragmentShader = unrollLoops(fragmentShader);
  11183. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11184. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11185. versionString = '#version 300 es\n';
  11186. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11187. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11188. }
  11189. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11190. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11191. // console.log( '*FRAGMENT*', fragmentGlsl );
  11192. const glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11193. const glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11194. gl.attachShader(program, glVertexShader);
  11195. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11196. if (parameters.index0AttributeName !== undefined) {
  11197. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11198. } else if (parameters.morphTargets === true) {
  11199. // programs with morphTargets displace position out of attribute 0
  11200. gl.bindAttribLocation(program, 0, 'position');
  11201. }
  11202. gl.linkProgram(program); // check for link errors
  11203. if (renderer.debug.checkShaderErrors) {
  11204. const programLog = gl.getProgramInfoLog(program).trim();
  11205. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11206. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11207. let runnable = true;
  11208. let haveDiagnostics = true;
  11209. if (gl.getProgramParameter(program, 35714) === false) {
  11210. runnable = false;
  11211. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11212. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11213. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11214. } else if (programLog !== '') {
  11215. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11216. } else if (vertexLog === '' || fragmentLog === '') {
  11217. haveDiagnostics = false;
  11218. }
  11219. if (haveDiagnostics) {
  11220. this.diagnostics = {
  11221. runnable: runnable,
  11222. programLog: programLog,
  11223. vertexShader: {
  11224. log: vertexLog,
  11225. prefix: prefixVertex
  11226. },
  11227. fragmentShader: {
  11228. log: fragmentLog,
  11229. prefix: prefixFragment
  11230. }
  11231. };
  11232. }
  11233. } // Clean up
  11234. // Crashes in iOS9 and iOS10. #18402
  11235. // gl.detachShader( program, glVertexShader );
  11236. // gl.detachShader( program, glFragmentShader );
  11237. gl.deleteShader(glVertexShader);
  11238. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11239. let cachedUniforms;
  11240. this.getUniforms = function () {
  11241. if (cachedUniforms === undefined) {
  11242. cachedUniforms = new WebGLUniforms(gl, program);
  11243. }
  11244. return cachedUniforms;
  11245. }; // set up caching for attribute locations
  11246. let cachedAttributes;
  11247. this.getAttributes = function () {
  11248. if (cachedAttributes === undefined) {
  11249. cachedAttributes = fetchAttributeLocations(gl, program);
  11250. }
  11251. return cachedAttributes;
  11252. }; // free resource
  11253. this.destroy = function () {
  11254. bindingStates.releaseStatesOfProgram(this);
  11255. gl.deleteProgram(program);
  11256. this.program = undefined;
  11257. }; //
  11258. this.name = parameters.shaderName;
  11259. this.id = programIdCount++;
  11260. this.cacheKey = cacheKey;
  11261. this.usedTimes = 1;
  11262. this.program = program;
  11263. this.vertexShader = glVertexShader;
  11264. this.fragmentShader = glFragmentShader;
  11265. return this;
  11266. }
  11267. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  11268. const programs = [];
  11269. const isWebGL2 = capabilities.isWebGL2;
  11270. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11271. const floatVertexTextures = capabilities.floatVertexTextures;
  11272. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11273. const vertexTextures = capabilities.vertexTextures;
  11274. let precision = capabilities.precision;
  11275. const shaderIDs = {
  11276. MeshDepthMaterial: 'depth',
  11277. MeshDistanceMaterial: 'distanceRGBA',
  11278. MeshNormalMaterial: 'normal',
  11279. MeshBasicMaterial: 'basic',
  11280. MeshLambertMaterial: 'lambert',
  11281. MeshPhongMaterial: 'phong',
  11282. MeshToonMaterial: 'toon',
  11283. MeshStandardMaterial: 'physical',
  11284. MeshPhysicalMaterial: 'physical',
  11285. MeshMatcapMaterial: 'matcap',
  11286. LineBasicMaterial: 'basic',
  11287. LineDashedMaterial: 'dashed',
  11288. PointsMaterial: 'points',
  11289. ShadowMaterial: 'shadow',
  11290. SpriteMaterial: 'sprite'
  11291. };
  11292. const parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "instancingColor", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen", "transmissionMap"];
  11293. function getMaxBones(object) {
  11294. const skeleton = object.skeleton;
  11295. const bones = skeleton.bones;
  11296. if (floatVertexTextures) {
  11297. return 1024;
  11298. } else {
  11299. // default for when object is not specified
  11300. // ( for example when prebuilding shader to be used with multiple objects )
  11301. //
  11302. // - leave some extra space for other uniforms
  11303. // - limit here is ANGLE's 254 max uniform vectors
  11304. // (up to 54 should be safe)
  11305. const nVertexUniforms = maxVertexUniforms;
  11306. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11307. const maxBones = Math.min(nVertexMatrices, bones.length);
  11308. if (maxBones < bones.length) {
  11309. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11310. return 0;
  11311. }
  11312. return maxBones;
  11313. }
  11314. }
  11315. function getTextureEncodingFromMap(map) {
  11316. let encoding;
  11317. if (!map) {
  11318. encoding = LinearEncoding;
  11319. } else if (map.isTexture) {
  11320. encoding = map.encoding;
  11321. } else if (map.isWebGLRenderTarget) {
  11322. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11323. encoding = map.texture.encoding;
  11324. }
  11325. return encoding;
  11326. }
  11327. function getParameters(material, lights, shadows, scene, object) {
  11328. const fog = scene.fog;
  11329. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11330. const envMap = cubemaps.get(material.envMap || environment);
  11331. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11332. // (not to blow over maxLights budget)
  11333. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11334. if (material.precision !== null) {
  11335. precision = capabilities.getMaxPrecision(material.precision);
  11336. if (precision !== material.precision) {
  11337. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11338. }
  11339. }
  11340. let vertexShader, fragmentShader;
  11341. if (shaderID) {
  11342. const shader = ShaderLib[shaderID];
  11343. vertexShader = shader.vertexShader;
  11344. fragmentShader = shader.fragmentShader;
  11345. } else {
  11346. vertexShader = material.vertexShader;
  11347. fragmentShader = material.fragmentShader;
  11348. }
  11349. const currentRenderTarget = renderer.getRenderTarget();
  11350. const parameters = {
  11351. isWebGL2: isWebGL2,
  11352. shaderID: shaderID,
  11353. shaderName: material.type,
  11354. vertexShader: vertexShader,
  11355. fragmentShader: fragmentShader,
  11356. defines: material.defines,
  11357. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11358. glslVersion: material.glslVersion,
  11359. precision: precision,
  11360. instancing: object.isInstancedMesh === true,
  11361. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11362. supportsVertexTextures: vertexTextures,
  11363. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11364. map: !!material.map,
  11365. mapEncoding: getTextureEncodingFromMap(material.map),
  11366. matcap: !!material.matcap,
  11367. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11368. envMap: !!envMap,
  11369. envMapMode: envMap && envMap.mapping,
  11370. envMapEncoding: getTextureEncodingFromMap(envMap),
  11371. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11372. lightMap: !!material.lightMap,
  11373. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11374. aoMap: !!material.aoMap,
  11375. emissiveMap: !!material.emissiveMap,
  11376. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11377. bumpMap: !!material.bumpMap,
  11378. normalMap: !!material.normalMap,
  11379. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11380. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11381. clearcoatMap: !!material.clearcoatMap,
  11382. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11383. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11384. displacementMap: !!material.displacementMap,
  11385. roughnessMap: !!material.roughnessMap,
  11386. metalnessMap: !!material.metalnessMap,
  11387. specularMap: !!material.specularMap,
  11388. alphaMap: !!material.alphaMap,
  11389. gradientMap: !!material.gradientMap,
  11390. sheen: !!material.sheen,
  11391. transmissionMap: !!material.transmissionMap,
  11392. combine: material.combine,
  11393. vertexTangents: material.normalMap && material.vertexTangents,
  11394. vertexColors: material.vertexColors,
  11395. 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,
  11396. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  11397. fog: !!fog,
  11398. useFog: material.fog,
  11399. fogExp2: fog && fog.isFogExp2,
  11400. flatShading: material.flatShading,
  11401. sizeAttenuation: material.sizeAttenuation,
  11402. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11403. skinning: material.skinning && maxBones > 0,
  11404. maxBones: maxBones,
  11405. useVertexTexture: floatVertexTextures,
  11406. morphTargets: material.morphTargets,
  11407. morphNormals: material.morphNormals,
  11408. maxMorphTargets: renderer.maxMorphTargets,
  11409. maxMorphNormals: renderer.maxMorphNormals,
  11410. numDirLights: lights.directional.length,
  11411. numPointLights: lights.point.length,
  11412. numSpotLights: lights.spot.length,
  11413. numRectAreaLights: lights.rectArea.length,
  11414. numHemiLights: lights.hemi.length,
  11415. numDirLightShadows: lights.directionalShadowMap.length,
  11416. numPointLightShadows: lights.pointShadowMap.length,
  11417. numSpotLightShadows: lights.spotShadowMap.length,
  11418. numClippingPlanes: clipping.numPlanes,
  11419. numClipIntersection: clipping.numIntersection,
  11420. dithering: material.dithering,
  11421. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11422. shadowMapType: renderer.shadowMap.type,
  11423. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11424. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11425. premultipliedAlpha: material.premultipliedAlpha,
  11426. alphaTest: material.alphaTest,
  11427. doubleSided: material.side === DoubleSide,
  11428. flipSided: material.side === BackSide,
  11429. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11430. index0AttributeName: material.index0AttributeName,
  11431. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11432. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11433. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11434. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11435. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11436. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11437. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11438. customProgramCacheKey: material.customProgramCacheKey()
  11439. };
  11440. return parameters;
  11441. }
  11442. function getProgramCacheKey(parameters) {
  11443. const array = [];
  11444. if (parameters.shaderID) {
  11445. array.push(parameters.shaderID);
  11446. } else {
  11447. array.push(parameters.fragmentShader);
  11448. array.push(parameters.vertexShader);
  11449. }
  11450. if (parameters.defines !== undefined) {
  11451. for (const name in parameters.defines) {
  11452. array.push(name);
  11453. array.push(parameters.defines[name]);
  11454. }
  11455. }
  11456. if (parameters.isRawShaderMaterial === false) {
  11457. for (let i = 0; i < parameterNames.length; i++) {
  11458. array.push(parameters[parameterNames[i]]);
  11459. }
  11460. array.push(renderer.outputEncoding);
  11461. array.push(renderer.gammaFactor);
  11462. }
  11463. array.push(parameters.customProgramCacheKey);
  11464. return array.join();
  11465. }
  11466. function getUniforms(material) {
  11467. const shaderID = shaderIDs[material.type];
  11468. let uniforms;
  11469. if (shaderID) {
  11470. const shader = ShaderLib[shaderID];
  11471. uniforms = UniformsUtils.clone(shader.uniforms);
  11472. } else {
  11473. uniforms = material.uniforms;
  11474. }
  11475. return uniforms;
  11476. }
  11477. function acquireProgram(parameters, cacheKey) {
  11478. let program; // Check if code has been already compiled
  11479. for (let p = 0, pl = programs.length; p < pl; p++) {
  11480. const preexistingProgram = programs[p];
  11481. if (preexistingProgram.cacheKey === cacheKey) {
  11482. program = preexistingProgram;
  11483. ++program.usedTimes;
  11484. break;
  11485. }
  11486. }
  11487. if (program === undefined) {
  11488. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11489. programs.push(program);
  11490. }
  11491. return program;
  11492. }
  11493. function releaseProgram(program) {
  11494. if (--program.usedTimes === 0) {
  11495. // Remove from unordered set
  11496. const i = programs.indexOf(program);
  11497. programs[i] = programs[programs.length - 1];
  11498. programs.pop(); // Free WebGL resources
  11499. program.destroy();
  11500. }
  11501. }
  11502. return {
  11503. getParameters: getParameters,
  11504. getProgramCacheKey: getProgramCacheKey,
  11505. getUniforms: getUniforms,
  11506. acquireProgram: acquireProgram,
  11507. releaseProgram: releaseProgram,
  11508. // Exposed for resource monitoring & error feedback via renderer.info:
  11509. programs: programs
  11510. };
  11511. }
  11512. function WebGLProperties() {
  11513. let properties = new WeakMap();
  11514. function get(object) {
  11515. let map = properties.get(object);
  11516. if (map === undefined) {
  11517. map = {};
  11518. properties.set(object, map);
  11519. }
  11520. return map;
  11521. }
  11522. function remove(object) {
  11523. properties.delete(object);
  11524. }
  11525. function update(object, key, value) {
  11526. properties.get(object)[key] = value;
  11527. }
  11528. function dispose() {
  11529. properties = new WeakMap();
  11530. }
  11531. return {
  11532. get: get,
  11533. remove: remove,
  11534. update: update,
  11535. dispose: dispose
  11536. };
  11537. }
  11538. function painterSortStable(a, b) {
  11539. if (a.groupOrder !== b.groupOrder) {
  11540. return a.groupOrder - b.groupOrder;
  11541. } else if (a.renderOrder !== b.renderOrder) {
  11542. return a.renderOrder - b.renderOrder;
  11543. } else if (a.program !== b.program) {
  11544. return a.program.id - b.program.id;
  11545. } else if (a.material.id !== b.material.id) {
  11546. return a.material.id - b.material.id;
  11547. } else if (a.z !== b.z) {
  11548. return a.z - b.z;
  11549. } else {
  11550. return a.id - b.id;
  11551. }
  11552. }
  11553. function reversePainterSortStable(a, b) {
  11554. if (a.groupOrder !== b.groupOrder) {
  11555. return a.groupOrder - b.groupOrder;
  11556. } else if (a.renderOrder !== b.renderOrder) {
  11557. return a.renderOrder - b.renderOrder;
  11558. } else if (a.z !== b.z) {
  11559. return b.z - a.z;
  11560. } else {
  11561. return a.id - b.id;
  11562. }
  11563. }
  11564. function WebGLRenderList(properties) {
  11565. const renderItems = [];
  11566. let renderItemsIndex = 0;
  11567. const opaque = [];
  11568. const transparent = [];
  11569. const defaultProgram = {
  11570. id: -1
  11571. };
  11572. function init() {
  11573. renderItemsIndex = 0;
  11574. opaque.length = 0;
  11575. transparent.length = 0;
  11576. }
  11577. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11578. let renderItem = renderItems[renderItemsIndex];
  11579. const materialProperties = properties.get(material);
  11580. if (renderItem === undefined) {
  11581. renderItem = {
  11582. id: object.id,
  11583. object: object,
  11584. geometry: geometry,
  11585. material: material,
  11586. program: materialProperties.program || defaultProgram,
  11587. groupOrder: groupOrder,
  11588. renderOrder: object.renderOrder,
  11589. z: z,
  11590. group: group
  11591. };
  11592. renderItems[renderItemsIndex] = renderItem;
  11593. } else {
  11594. renderItem.id = object.id;
  11595. renderItem.object = object;
  11596. renderItem.geometry = geometry;
  11597. renderItem.material = material;
  11598. renderItem.program = materialProperties.program || defaultProgram;
  11599. renderItem.groupOrder = groupOrder;
  11600. renderItem.renderOrder = object.renderOrder;
  11601. renderItem.z = z;
  11602. renderItem.group = group;
  11603. }
  11604. renderItemsIndex++;
  11605. return renderItem;
  11606. }
  11607. function push(object, geometry, material, groupOrder, z, group) {
  11608. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11609. (material.transparent === true ? transparent : opaque).push(renderItem);
  11610. }
  11611. function unshift(object, geometry, material, groupOrder, z, group) {
  11612. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11613. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  11614. }
  11615. function sort(customOpaqueSort, customTransparentSort) {
  11616. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11617. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11618. }
  11619. function finish() {
  11620. // Clear references from inactive renderItems in the list
  11621. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11622. const renderItem = renderItems[i];
  11623. if (renderItem.id === null) break;
  11624. renderItem.id = null;
  11625. renderItem.object = null;
  11626. renderItem.geometry = null;
  11627. renderItem.material = null;
  11628. renderItem.program = null;
  11629. renderItem.group = null;
  11630. }
  11631. }
  11632. return {
  11633. opaque: opaque,
  11634. transparent: transparent,
  11635. init: init,
  11636. push: push,
  11637. unshift: unshift,
  11638. finish: finish,
  11639. sort: sort
  11640. };
  11641. }
  11642. function WebGLRenderLists(properties) {
  11643. let lists = new WeakMap();
  11644. function get(scene, camera) {
  11645. const cameras = lists.get(scene);
  11646. let list;
  11647. if (cameras === undefined) {
  11648. list = new WebGLRenderList(properties);
  11649. lists.set(scene, new WeakMap());
  11650. lists.get(scene).set(camera, list);
  11651. } else {
  11652. list = cameras.get(camera);
  11653. if (list === undefined) {
  11654. list = new WebGLRenderList(properties);
  11655. cameras.set(camera, list);
  11656. }
  11657. }
  11658. return list;
  11659. }
  11660. function dispose() {
  11661. lists = new WeakMap();
  11662. }
  11663. return {
  11664. get: get,
  11665. dispose: dispose
  11666. };
  11667. }
  11668. function UniformsCache() {
  11669. const lights = {};
  11670. return {
  11671. get: function (light) {
  11672. if (lights[light.id] !== undefined) {
  11673. return lights[light.id];
  11674. }
  11675. let uniforms;
  11676. switch (light.type) {
  11677. case 'DirectionalLight':
  11678. uniforms = {
  11679. direction: new Vector3(),
  11680. color: new Color()
  11681. };
  11682. break;
  11683. case 'SpotLight':
  11684. uniforms = {
  11685. position: new Vector3(),
  11686. direction: new Vector3(),
  11687. color: new Color(),
  11688. distance: 0,
  11689. coneCos: 0,
  11690. penumbraCos: 0,
  11691. decay: 0
  11692. };
  11693. break;
  11694. case 'PointLight':
  11695. uniforms = {
  11696. position: new Vector3(),
  11697. color: new Color(),
  11698. distance: 0,
  11699. decay: 0
  11700. };
  11701. break;
  11702. case 'HemisphereLight':
  11703. uniforms = {
  11704. direction: new Vector3(),
  11705. skyColor: new Color(),
  11706. groundColor: new Color()
  11707. };
  11708. break;
  11709. case 'RectAreaLight':
  11710. uniforms = {
  11711. color: new Color(),
  11712. position: new Vector3(),
  11713. halfWidth: new Vector3(),
  11714. halfHeight: new Vector3()
  11715. };
  11716. break;
  11717. }
  11718. lights[light.id] = uniforms;
  11719. return uniforms;
  11720. }
  11721. };
  11722. }
  11723. function ShadowUniformsCache() {
  11724. const lights = {};
  11725. return {
  11726. get: function (light) {
  11727. if (lights[light.id] !== undefined) {
  11728. return lights[light.id];
  11729. }
  11730. let uniforms;
  11731. switch (light.type) {
  11732. case 'DirectionalLight':
  11733. uniforms = {
  11734. shadowBias: 0,
  11735. shadowNormalBias: 0,
  11736. shadowRadius: 1,
  11737. shadowMapSize: new Vector2()
  11738. };
  11739. break;
  11740. case 'SpotLight':
  11741. uniforms = {
  11742. shadowBias: 0,
  11743. shadowNormalBias: 0,
  11744. shadowRadius: 1,
  11745. shadowMapSize: new Vector2()
  11746. };
  11747. break;
  11748. case 'PointLight':
  11749. uniforms = {
  11750. shadowBias: 0,
  11751. shadowNormalBias: 0,
  11752. shadowRadius: 1,
  11753. shadowMapSize: new Vector2(),
  11754. shadowCameraNear: 1,
  11755. shadowCameraFar: 1000
  11756. };
  11757. break;
  11758. // TODO (abelnation): set RectAreaLight shadow uniforms
  11759. }
  11760. lights[light.id] = uniforms;
  11761. return uniforms;
  11762. }
  11763. };
  11764. }
  11765. let nextVersion = 0;
  11766. function shadowCastingLightsFirst(lightA, lightB) {
  11767. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11768. }
  11769. function WebGLLights(extensions, capabilities) {
  11770. const cache = new UniformsCache();
  11771. const shadowCache = ShadowUniformsCache();
  11772. const state = {
  11773. version: 0,
  11774. hash: {
  11775. directionalLength: -1,
  11776. pointLength: -1,
  11777. spotLength: -1,
  11778. rectAreaLength: -1,
  11779. hemiLength: -1,
  11780. numDirectionalShadows: -1,
  11781. numPointShadows: -1,
  11782. numSpotShadows: -1
  11783. },
  11784. ambient: [0, 0, 0],
  11785. probe: [],
  11786. directional: [],
  11787. directionalShadow: [],
  11788. directionalShadowMap: [],
  11789. directionalShadowMatrix: [],
  11790. spot: [],
  11791. spotShadow: [],
  11792. spotShadowMap: [],
  11793. spotShadowMatrix: [],
  11794. rectArea: [],
  11795. rectAreaLTC1: null,
  11796. rectAreaLTC2: null,
  11797. point: [],
  11798. pointShadow: [],
  11799. pointShadowMap: [],
  11800. pointShadowMatrix: [],
  11801. hemi: []
  11802. };
  11803. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11804. const vector3 = new Vector3();
  11805. const matrix4 = new Matrix4();
  11806. const matrix42 = new Matrix4();
  11807. function setup(lights, shadows, camera) {
  11808. let r = 0,
  11809. g = 0,
  11810. b = 0;
  11811. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11812. let directionalLength = 0;
  11813. let pointLength = 0;
  11814. let spotLength = 0;
  11815. let rectAreaLength = 0;
  11816. let hemiLength = 0;
  11817. let numDirectionalShadows = 0;
  11818. let numPointShadows = 0;
  11819. let numSpotShadows = 0;
  11820. const viewMatrix = camera.matrixWorldInverse;
  11821. lights.sort(shadowCastingLightsFirst);
  11822. for (let i = 0, l = lights.length; i < l; i++) {
  11823. const light = lights[i];
  11824. const color = light.color;
  11825. const intensity = light.intensity;
  11826. const distance = light.distance;
  11827. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11828. if (light.isAmbientLight) {
  11829. r += color.r * intensity;
  11830. g += color.g * intensity;
  11831. b += color.b * intensity;
  11832. } else if (light.isLightProbe) {
  11833. for (let j = 0; j < 9; j++) {
  11834. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11835. }
  11836. } else if (light.isDirectionalLight) {
  11837. const uniforms = cache.get(light);
  11838. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11839. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11840. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11841. uniforms.direction.sub(vector3);
  11842. uniforms.direction.transformDirection(viewMatrix);
  11843. if (light.castShadow) {
  11844. const shadow = light.shadow;
  11845. const shadowUniforms = shadowCache.get(light);
  11846. shadowUniforms.shadowBias = shadow.bias;
  11847. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11848. shadowUniforms.shadowRadius = shadow.radius;
  11849. shadowUniforms.shadowMapSize = shadow.mapSize;
  11850. state.directionalShadow[directionalLength] = shadowUniforms;
  11851. state.directionalShadowMap[directionalLength] = shadowMap;
  11852. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11853. numDirectionalShadows++;
  11854. }
  11855. state.directional[directionalLength] = uniforms;
  11856. directionalLength++;
  11857. } else if (light.isSpotLight) {
  11858. const uniforms = cache.get(light);
  11859. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11860. uniforms.position.applyMatrix4(viewMatrix);
  11861. uniforms.color.copy(color).multiplyScalar(intensity);
  11862. uniforms.distance = distance;
  11863. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11864. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11865. uniforms.direction.sub(vector3);
  11866. uniforms.direction.transformDirection(viewMatrix);
  11867. uniforms.coneCos = Math.cos(light.angle);
  11868. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11869. uniforms.decay = light.decay;
  11870. if (light.castShadow) {
  11871. const shadow = light.shadow;
  11872. const shadowUniforms = shadowCache.get(light);
  11873. shadowUniforms.shadowBias = shadow.bias;
  11874. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11875. shadowUniforms.shadowRadius = shadow.radius;
  11876. shadowUniforms.shadowMapSize = shadow.mapSize;
  11877. state.spotShadow[spotLength] = shadowUniforms;
  11878. state.spotShadowMap[spotLength] = shadowMap;
  11879. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11880. numSpotShadows++;
  11881. }
  11882. state.spot[spotLength] = uniforms;
  11883. spotLength++;
  11884. } else if (light.isRectAreaLight) {
  11885. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11886. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11887. // (b) intensity is the brightness of the light
  11888. uniforms.color.copy(color).multiplyScalar(intensity);
  11889. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11890. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11891. matrix42.identity();
  11892. matrix4.copy(light.matrixWorld);
  11893. matrix4.premultiply(viewMatrix);
  11894. matrix42.extractRotation(matrix4);
  11895. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11896. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11897. uniforms.halfWidth.applyMatrix4(matrix42);
  11898. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  11899. // uniforms.distance = distance;
  11900. state.rectArea[rectAreaLength] = uniforms;
  11901. rectAreaLength++;
  11902. } else if (light.isPointLight) {
  11903. const uniforms = cache.get(light);
  11904. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11905. uniforms.position.applyMatrix4(viewMatrix);
  11906. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11907. uniforms.distance = light.distance;
  11908. uniforms.decay = light.decay;
  11909. if (light.castShadow) {
  11910. const shadow = light.shadow;
  11911. const shadowUniforms = shadowCache.get(light);
  11912. shadowUniforms.shadowBias = shadow.bias;
  11913. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11914. shadowUniforms.shadowRadius = shadow.radius;
  11915. shadowUniforms.shadowMapSize = shadow.mapSize;
  11916. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11917. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11918. state.pointShadow[pointLength] = shadowUniforms;
  11919. state.pointShadowMap[pointLength] = shadowMap;
  11920. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11921. numPointShadows++;
  11922. }
  11923. state.point[pointLength] = uniforms;
  11924. pointLength++;
  11925. } else if (light.isHemisphereLight) {
  11926. const uniforms = cache.get(light);
  11927. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11928. uniforms.direction.transformDirection(viewMatrix);
  11929. uniforms.direction.normalize();
  11930. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11931. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11932. state.hemi[hemiLength] = uniforms;
  11933. hemiLength++;
  11934. }
  11935. }
  11936. if (rectAreaLength > 0) {
  11937. if (capabilities.isWebGL2) {
  11938. // WebGL 2
  11939. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11940. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11941. } else {
  11942. // WebGL 1
  11943. if (extensions.has('OES_texture_float_linear') === true) {
  11944. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11945. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11946. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11947. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11948. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11949. } else {
  11950. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11951. }
  11952. }
  11953. }
  11954. state.ambient[0] = r;
  11955. state.ambient[1] = g;
  11956. state.ambient[2] = b;
  11957. const hash = state.hash;
  11958. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  11959. state.directional.length = directionalLength;
  11960. state.spot.length = spotLength;
  11961. state.rectArea.length = rectAreaLength;
  11962. state.point.length = pointLength;
  11963. state.hemi.length = hemiLength;
  11964. state.directionalShadow.length = numDirectionalShadows;
  11965. state.directionalShadowMap.length = numDirectionalShadows;
  11966. state.pointShadow.length = numPointShadows;
  11967. state.pointShadowMap.length = numPointShadows;
  11968. state.spotShadow.length = numSpotShadows;
  11969. state.spotShadowMap.length = numSpotShadows;
  11970. state.directionalShadowMatrix.length = numDirectionalShadows;
  11971. state.pointShadowMatrix.length = numPointShadows;
  11972. state.spotShadowMatrix.length = numSpotShadows;
  11973. hash.directionalLength = directionalLength;
  11974. hash.pointLength = pointLength;
  11975. hash.spotLength = spotLength;
  11976. hash.rectAreaLength = rectAreaLength;
  11977. hash.hemiLength = hemiLength;
  11978. hash.numDirectionalShadows = numDirectionalShadows;
  11979. hash.numPointShadows = numPointShadows;
  11980. hash.numSpotShadows = numSpotShadows;
  11981. state.version = nextVersion++;
  11982. }
  11983. }
  11984. return {
  11985. setup: setup,
  11986. state: state
  11987. };
  11988. }
  11989. function WebGLRenderState(extensions, capabilities) {
  11990. const lights = new WebGLLights(extensions, capabilities);
  11991. const lightsArray = [];
  11992. const shadowsArray = [];
  11993. function init() {
  11994. lightsArray.length = 0;
  11995. shadowsArray.length = 0;
  11996. }
  11997. function pushLight(light) {
  11998. lightsArray.push(light);
  11999. }
  12000. function pushShadow(shadowLight) {
  12001. shadowsArray.push(shadowLight);
  12002. }
  12003. function setupLights(camera) {
  12004. lights.setup(lightsArray, shadowsArray, camera);
  12005. }
  12006. const state = {
  12007. lightsArray: lightsArray,
  12008. shadowsArray: shadowsArray,
  12009. lights: lights
  12010. };
  12011. return {
  12012. init: init,
  12013. state: state,
  12014. setupLights: setupLights,
  12015. pushLight: pushLight,
  12016. pushShadow: pushShadow
  12017. };
  12018. }
  12019. function WebGLRenderStates(extensions, capabilities) {
  12020. let renderStates = new WeakMap();
  12021. function get(scene, camera) {
  12022. let renderState;
  12023. if (renderStates.has(scene) === false) {
  12024. renderState = new WebGLRenderState(extensions, capabilities);
  12025. renderStates.set(scene, new WeakMap());
  12026. renderStates.get(scene).set(camera, renderState);
  12027. } else {
  12028. if (renderStates.get(scene).has(camera) === false) {
  12029. renderState = new WebGLRenderState(extensions, capabilities);
  12030. renderStates.get(scene).set(camera, renderState);
  12031. } else {
  12032. renderState = renderStates.get(scene).get(camera);
  12033. }
  12034. }
  12035. return renderState;
  12036. }
  12037. function dispose() {
  12038. renderStates = new WeakMap();
  12039. }
  12040. return {
  12041. get: get,
  12042. dispose: dispose
  12043. };
  12044. }
  12045. /**
  12046. * parameters = {
  12047. *
  12048. * opacity: <float>,
  12049. *
  12050. * map: new THREE.Texture( <Image> ),
  12051. *
  12052. * alphaMap: new THREE.Texture( <Image> ),
  12053. *
  12054. * displacementMap: new THREE.Texture( <Image> ),
  12055. * displacementScale: <float>,
  12056. * displacementBias: <float>,
  12057. *
  12058. * wireframe: <boolean>,
  12059. * wireframeLinewidth: <float>
  12060. * }
  12061. */
  12062. function MeshDepthMaterial(parameters) {
  12063. Material.call(this);
  12064. this.type = 'MeshDepthMaterial';
  12065. this.depthPacking = BasicDepthPacking;
  12066. this.skinning = false;
  12067. this.morphTargets = false;
  12068. this.map = null;
  12069. this.alphaMap = null;
  12070. this.displacementMap = null;
  12071. this.displacementScale = 1;
  12072. this.displacementBias = 0;
  12073. this.wireframe = false;
  12074. this.wireframeLinewidth = 1;
  12075. this.fog = false;
  12076. this.setValues(parameters);
  12077. }
  12078. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12079. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12080. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12081. MeshDepthMaterial.prototype.copy = function (source) {
  12082. Material.prototype.copy.call(this, source);
  12083. this.depthPacking = source.depthPacking;
  12084. this.skinning = source.skinning;
  12085. this.morphTargets = source.morphTargets;
  12086. this.map = source.map;
  12087. this.alphaMap = source.alphaMap;
  12088. this.displacementMap = source.displacementMap;
  12089. this.displacementScale = source.displacementScale;
  12090. this.displacementBias = source.displacementBias;
  12091. this.wireframe = source.wireframe;
  12092. this.wireframeLinewidth = source.wireframeLinewidth;
  12093. return this;
  12094. };
  12095. /**
  12096. * parameters = {
  12097. *
  12098. * referencePosition: <float>,
  12099. * nearDistance: <float>,
  12100. * farDistance: <float>,
  12101. *
  12102. * skinning: <bool>,
  12103. * morphTargets: <bool>,
  12104. *
  12105. * map: new THREE.Texture( <Image> ),
  12106. *
  12107. * alphaMap: new THREE.Texture( <Image> ),
  12108. *
  12109. * displacementMap: new THREE.Texture( <Image> ),
  12110. * displacementScale: <float>,
  12111. * displacementBias: <float>
  12112. *
  12113. * }
  12114. */
  12115. function MeshDistanceMaterial(parameters) {
  12116. Material.call(this);
  12117. this.type = 'MeshDistanceMaterial';
  12118. this.referencePosition = new Vector3();
  12119. this.nearDistance = 1;
  12120. this.farDistance = 1000;
  12121. this.skinning = false;
  12122. this.morphTargets = false;
  12123. this.map = null;
  12124. this.alphaMap = null;
  12125. this.displacementMap = null;
  12126. this.displacementScale = 1;
  12127. this.displacementBias = 0;
  12128. this.fog = false;
  12129. this.setValues(parameters);
  12130. }
  12131. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12132. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12133. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12134. MeshDistanceMaterial.prototype.copy = function (source) {
  12135. Material.prototype.copy.call(this, source);
  12136. this.referencePosition.copy(source.referencePosition);
  12137. this.nearDistance = source.nearDistance;
  12138. this.farDistance = source.farDistance;
  12139. this.skinning = source.skinning;
  12140. this.morphTargets = source.morphTargets;
  12141. this.map = source.map;
  12142. this.alphaMap = source.alphaMap;
  12143. this.displacementMap = source.displacementMap;
  12144. this.displacementScale = source.displacementScale;
  12145. this.displacementBias = source.displacementBias;
  12146. return this;
  12147. };
  12148. 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 HORIZONAL_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}";
  12149. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12150. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12151. let _frustum = new Frustum();
  12152. const _shadowMapSize = new Vector2(),
  12153. _viewportSize = new Vector2(),
  12154. _viewport = new Vector4(),
  12155. _depthMaterials = [],
  12156. _distanceMaterials = [],
  12157. _materialCache = {};
  12158. const shadowSide = {
  12159. 0: BackSide,
  12160. 1: FrontSide,
  12161. 2: DoubleSide
  12162. };
  12163. const shadowMaterialVertical = new ShaderMaterial({
  12164. defines: {
  12165. SAMPLE_RATE: 2.0 / 8.0,
  12166. HALF_SAMPLE_RATE: 1.0 / 8.0
  12167. },
  12168. uniforms: {
  12169. shadow_pass: {
  12170. value: null
  12171. },
  12172. resolution: {
  12173. value: new Vector2()
  12174. },
  12175. radius: {
  12176. value: 4.0
  12177. }
  12178. },
  12179. vertexShader: vsm_vert,
  12180. fragmentShader: vsm_frag
  12181. });
  12182. const shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12183. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12184. const fullScreenTri = new BufferGeometry();
  12185. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12186. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12187. const scope = this;
  12188. this.enabled = false;
  12189. this.autoUpdate = true;
  12190. this.needsUpdate = false;
  12191. this.type = PCFShadowMap;
  12192. this.render = function (lights, scene, camera) {
  12193. if (scope.enabled === false) return;
  12194. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12195. if (lights.length === 0) return;
  12196. const currentRenderTarget = _renderer.getRenderTarget();
  12197. const activeCubeFace = _renderer.getActiveCubeFace();
  12198. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12199. const _state = _renderer.state; // Set GL state for depth map.
  12200. _state.setBlending(NoBlending);
  12201. _state.buffers.color.setClear(1, 1, 1, 1);
  12202. _state.buffers.depth.setTest(true);
  12203. _state.setScissorTest(false); // render depth map
  12204. for (let i = 0, il = lights.length; i < il; i++) {
  12205. const light = lights[i];
  12206. const shadow = light.shadow;
  12207. if (shadow === undefined) {
  12208. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12209. continue;
  12210. }
  12211. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12212. _shadowMapSize.copy(shadow.mapSize);
  12213. const shadowFrameExtents = shadow.getFrameExtents();
  12214. _shadowMapSize.multiply(shadowFrameExtents);
  12215. _viewportSize.copy(shadow.mapSize);
  12216. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12217. if (_shadowMapSize.x > maxTextureSize) {
  12218. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12219. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12220. shadow.mapSize.x = _viewportSize.x;
  12221. }
  12222. if (_shadowMapSize.y > maxTextureSize) {
  12223. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12224. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12225. shadow.mapSize.y = _viewportSize.y;
  12226. }
  12227. }
  12228. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12229. const pars = {
  12230. minFilter: LinearFilter,
  12231. magFilter: LinearFilter,
  12232. format: RGBAFormat
  12233. };
  12234. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12235. shadow.map.texture.name = light.name + ".shadowMap";
  12236. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12237. shadow.camera.updateProjectionMatrix();
  12238. }
  12239. if (shadow.map === null) {
  12240. const pars = {
  12241. minFilter: NearestFilter,
  12242. magFilter: NearestFilter,
  12243. format: RGBAFormat
  12244. };
  12245. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12246. shadow.map.texture.name = light.name + ".shadowMap";
  12247. shadow.camera.updateProjectionMatrix();
  12248. }
  12249. _renderer.setRenderTarget(shadow.map);
  12250. _renderer.clear();
  12251. const viewportCount = shadow.getViewportCount();
  12252. for (let vp = 0; vp < viewportCount; vp++) {
  12253. const viewport = shadow.getViewport(vp);
  12254. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12255. _state.viewport(_viewport);
  12256. shadow.updateMatrices(light, vp);
  12257. _frustum = shadow.getFrustum();
  12258. renderObject(scene, camera, shadow.camera, light, this.type);
  12259. } // do blur pass for VSM
  12260. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12261. VSMPass(shadow, camera);
  12262. }
  12263. shadow.needsUpdate = false;
  12264. }
  12265. scope.needsUpdate = false;
  12266. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12267. };
  12268. function VSMPass(shadow, camera) {
  12269. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12270. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12271. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12272. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12273. _renderer.setRenderTarget(shadow.mapPass);
  12274. _renderer.clear();
  12275. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12276. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12277. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12278. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12279. _renderer.setRenderTarget(shadow.map);
  12280. _renderer.clear();
  12281. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12282. }
  12283. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12284. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12285. let material = _depthMaterials[index];
  12286. if (material === undefined) {
  12287. material = new MeshDepthMaterial({
  12288. depthPacking: RGBADepthPacking,
  12289. morphTargets: useMorphing,
  12290. skinning: useSkinning
  12291. });
  12292. _depthMaterials[index] = material;
  12293. }
  12294. return material;
  12295. }
  12296. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12297. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12298. let material = _distanceMaterials[index];
  12299. if (material === undefined) {
  12300. material = new MeshDistanceMaterial({
  12301. morphTargets: useMorphing,
  12302. skinning: useSkinning
  12303. });
  12304. _distanceMaterials[index] = material;
  12305. }
  12306. return material;
  12307. }
  12308. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12309. let result = null;
  12310. let getMaterialVariant = getDepthMaterialVariant;
  12311. let customMaterial = object.customDepthMaterial;
  12312. if (light.isPointLight === true) {
  12313. getMaterialVariant = getDistanceMaterialVariant;
  12314. customMaterial = object.customDistanceMaterial;
  12315. }
  12316. if (customMaterial === undefined) {
  12317. let useMorphing = false;
  12318. if (material.morphTargets === true) {
  12319. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12320. }
  12321. let useSkinning = false;
  12322. if (object.isSkinnedMesh === true) {
  12323. if (material.skinning === true) {
  12324. useSkinning = true;
  12325. } else {
  12326. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12327. }
  12328. }
  12329. const useInstancing = object.isInstancedMesh === true;
  12330. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  12331. } else {
  12332. result = customMaterial;
  12333. }
  12334. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12335. // in this case we need a unique material instance reflecting the
  12336. // appropriate state
  12337. const keyA = result.uuid,
  12338. keyB = material.uuid;
  12339. let materialsForVariant = _materialCache[keyA];
  12340. if (materialsForVariant === undefined) {
  12341. materialsForVariant = {};
  12342. _materialCache[keyA] = materialsForVariant;
  12343. }
  12344. let cachedMaterial = materialsForVariant[keyB];
  12345. if (cachedMaterial === undefined) {
  12346. cachedMaterial = result.clone();
  12347. materialsForVariant[keyB] = cachedMaterial;
  12348. }
  12349. result = cachedMaterial;
  12350. }
  12351. result.visible = material.visible;
  12352. result.wireframe = material.wireframe;
  12353. if (type === VSMShadowMap) {
  12354. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12355. } else {
  12356. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12357. }
  12358. result.clipShadows = material.clipShadows;
  12359. result.clippingPlanes = material.clippingPlanes;
  12360. result.clipIntersection = material.clipIntersection;
  12361. result.wireframeLinewidth = material.wireframeLinewidth;
  12362. result.linewidth = material.linewidth;
  12363. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12364. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12365. result.nearDistance = shadowCameraNear;
  12366. result.farDistance = shadowCameraFar;
  12367. }
  12368. return result;
  12369. }
  12370. function renderObject(object, camera, shadowCamera, light, type) {
  12371. if (object.visible === false) return;
  12372. const visible = object.layers.test(camera.layers);
  12373. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12374. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12375. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12376. const geometry = _objects.update(object);
  12377. const material = object.material;
  12378. if (Array.isArray(material)) {
  12379. const groups = geometry.groups;
  12380. for (let k = 0, kl = groups.length; k < kl; k++) {
  12381. const group = groups[k];
  12382. const groupMaterial = material[group.materialIndex];
  12383. if (groupMaterial && groupMaterial.visible) {
  12384. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12385. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12386. }
  12387. }
  12388. } else if (material.visible) {
  12389. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12390. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12391. }
  12392. }
  12393. }
  12394. const children = object.children;
  12395. for (let i = 0, l = children.length; i < l; i++) {
  12396. renderObject(children[i], camera, shadowCamera, light, type);
  12397. }
  12398. }
  12399. }
  12400. function WebGLState(gl, extensions, capabilities) {
  12401. const isWebGL2 = capabilities.isWebGL2;
  12402. function ColorBuffer() {
  12403. let locked = false;
  12404. const color = new Vector4();
  12405. let currentColorMask = null;
  12406. const currentColorClear = new Vector4(0, 0, 0, 0);
  12407. return {
  12408. setMask: function (colorMask) {
  12409. if (currentColorMask !== colorMask && !locked) {
  12410. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12411. currentColorMask = colorMask;
  12412. }
  12413. },
  12414. setLocked: function (lock) {
  12415. locked = lock;
  12416. },
  12417. setClear: function (r, g, b, a, premultipliedAlpha) {
  12418. if (premultipliedAlpha === true) {
  12419. r *= a;
  12420. g *= a;
  12421. b *= a;
  12422. }
  12423. color.set(r, g, b, a);
  12424. if (currentColorClear.equals(color) === false) {
  12425. gl.clearColor(r, g, b, a);
  12426. currentColorClear.copy(color);
  12427. }
  12428. },
  12429. reset: function () {
  12430. locked = false;
  12431. currentColorMask = null;
  12432. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12433. }
  12434. };
  12435. }
  12436. function DepthBuffer() {
  12437. let locked = false;
  12438. let currentDepthMask = null;
  12439. let currentDepthFunc = null;
  12440. let currentDepthClear = null;
  12441. return {
  12442. setTest: function (depthTest) {
  12443. if (depthTest) {
  12444. enable(2929);
  12445. } else {
  12446. disable(2929);
  12447. }
  12448. },
  12449. setMask: function (depthMask) {
  12450. if (currentDepthMask !== depthMask && !locked) {
  12451. gl.depthMask(depthMask);
  12452. currentDepthMask = depthMask;
  12453. }
  12454. },
  12455. setFunc: function (depthFunc) {
  12456. if (currentDepthFunc !== depthFunc) {
  12457. if (depthFunc) {
  12458. switch (depthFunc) {
  12459. case NeverDepth:
  12460. gl.depthFunc(512);
  12461. break;
  12462. case AlwaysDepth:
  12463. gl.depthFunc(519);
  12464. break;
  12465. case LessDepth:
  12466. gl.depthFunc(513);
  12467. break;
  12468. case LessEqualDepth:
  12469. gl.depthFunc(515);
  12470. break;
  12471. case EqualDepth:
  12472. gl.depthFunc(514);
  12473. break;
  12474. case GreaterEqualDepth:
  12475. gl.depthFunc(518);
  12476. break;
  12477. case GreaterDepth:
  12478. gl.depthFunc(516);
  12479. break;
  12480. case NotEqualDepth:
  12481. gl.depthFunc(517);
  12482. break;
  12483. default:
  12484. gl.depthFunc(515);
  12485. }
  12486. } else {
  12487. gl.depthFunc(515);
  12488. }
  12489. currentDepthFunc = depthFunc;
  12490. }
  12491. },
  12492. setLocked: function (lock) {
  12493. locked = lock;
  12494. },
  12495. setClear: function (depth) {
  12496. if (currentDepthClear !== depth) {
  12497. gl.clearDepth(depth);
  12498. currentDepthClear = depth;
  12499. }
  12500. },
  12501. reset: function () {
  12502. locked = false;
  12503. currentDepthMask = null;
  12504. currentDepthFunc = null;
  12505. currentDepthClear = null;
  12506. }
  12507. };
  12508. }
  12509. function StencilBuffer() {
  12510. let locked = false;
  12511. let currentStencilMask = null;
  12512. let currentStencilFunc = null;
  12513. let currentStencilRef = null;
  12514. let currentStencilFuncMask = null;
  12515. let currentStencilFail = null;
  12516. let currentStencilZFail = null;
  12517. let currentStencilZPass = null;
  12518. let currentStencilClear = null;
  12519. return {
  12520. setTest: function (stencilTest) {
  12521. if (!locked) {
  12522. if (stencilTest) {
  12523. enable(2960);
  12524. } else {
  12525. disable(2960);
  12526. }
  12527. }
  12528. },
  12529. setMask: function (stencilMask) {
  12530. if (currentStencilMask !== stencilMask && !locked) {
  12531. gl.stencilMask(stencilMask);
  12532. currentStencilMask = stencilMask;
  12533. }
  12534. },
  12535. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12536. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12537. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12538. currentStencilFunc = stencilFunc;
  12539. currentStencilRef = stencilRef;
  12540. currentStencilFuncMask = stencilMask;
  12541. }
  12542. },
  12543. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12544. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12545. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12546. currentStencilFail = stencilFail;
  12547. currentStencilZFail = stencilZFail;
  12548. currentStencilZPass = stencilZPass;
  12549. }
  12550. },
  12551. setLocked: function (lock) {
  12552. locked = lock;
  12553. },
  12554. setClear: function (stencil) {
  12555. if (currentStencilClear !== stencil) {
  12556. gl.clearStencil(stencil);
  12557. currentStencilClear = stencil;
  12558. }
  12559. },
  12560. reset: function () {
  12561. locked = false;
  12562. currentStencilMask = null;
  12563. currentStencilFunc = null;
  12564. currentStencilRef = null;
  12565. currentStencilFuncMask = null;
  12566. currentStencilFail = null;
  12567. currentStencilZFail = null;
  12568. currentStencilZPass = null;
  12569. currentStencilClear = null;
  12570. }
  12571. };
  12572. } //
  12573. const colorBuffer = new ColorBuffer();
  12574. const depthBuffer = new DepthBuffer();
  12575. const stencilBuffer = new StencilBuffer();
  12576. let enabledCapabilities = {};
  12577. let currentProgram = null;
  12578. let currentBlendingEnabled = null;
  12579. let currentBlending = null;
  12580. let currentBlendEquation = null;
  12581. let currentBlendSrc = null;
  12582. let currentBlendDst = null;
  12583. let currentBlendEquationAlpha = null;
  12584. let currentBlendSrcAlpha = null;
  12585. let currentBlendDstAlpha = null;
  12586. let currentPremultipledAlpha = false;
  12587. let currentFlipSided = null;
  12588. let currentCullFace = null;
  12589. let currentLineWidth = null;
  12590. let currentPolygonOffsetFactor = null;
  12591. let currentPolygonOffsetUnits = null;
  12592. const maxTextures = gl.getParameter(35661);
  12593. let lineWidthAvailable = false;
  12594. let version = 0;
  12595. const glVersion = gl.getParameter(7938);
  12596. if (glVersion.indexOf('WebGL') !== -1) {
  12597. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  12598. lineWidthAvailable = version >= 1.0;
  12599. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12600. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  12601. lineWidthAvailable = version >= 2.0;
  12602. }
  12603. let currentTextureSlot = null;
  12604. let currentBoundTextures = {};
  12605. const currentScissor = new Vector4();
  12606. const currentViewport = new Vector4();
  12607. function createTexture(type, target, count) {
  12608. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12609. const texture = gl.createTexture();
  12610. gl.bindTexture(type, texture);
  12611. gl.texParameteri(type, 10241, 9728);
  12612. gl.texParameteri(type, 10240, 9728);
  12613. for (let i = 0; i < count; i++) {
  12614. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  12615. }
  12616. return texture;
  12617. }
  12618. const emptyTextures = {};
  12619. emptyTextures[3553] = createTexture(3553, 3553, 1);
  12620. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  12621. colorBuffer.setClear(0, 0, 0, 1);
  12622. depthBuffer.setClear(1);
  12623. stencilBuffer.setClear(0);
  12624. enable(2929);
  12625. depthBuffer.setFunc(LessEqualDepth);
  12626. setFlipSided(false);
  12627. setCullFace(CullFaceBack);
  12628. enable(2884);
  12629. setBlending(NoBlending); //
  12630. function enable(id) {
  12631. if (enabledCapabilities[id] !== true) {
  12632. gl.enable(id);
  12633. enabledCapabilities[id] = true;
  12634. }
  12635. }
  12636. function disable(id) {
  12637. if (enabledCapabilities[id] !== false) {
  12638. gl.disable(id);
  12639. enabledCapabilities[id] = false;
  12640. }
  12641. }
  12642. function useProgram(program) {
  12643. if (currentProgram !== program) {
  12644. gl.useProgram(program);
  12645. currentProgram = program;
  12646. return true;
  12647. }
  12648. return false;
  12649. }
  12650. const equationToGL = {
  12651. [AddEquation]: 32774,
  12652. [SubtractEquation]: 32778,
  12653. [ReverseSubtractEquation]: 32779
  12654. };
  12655. if (isWebGL2) {
  12656. equationToGL[MinEquation] = 32775;
  12657. equationToGL[MaxEquation] = 32776;
  12658. } else {
  12659. const extension = extensions.get('EXT_blend_minmax');
  12660. if (extension !== null) {
  12661. equationToGL[MinEquation] = extension.MIN_EXT;
  12662. equationToGL[MaxEquation] = extension.MAX_EXT;
  12663. }
  12664. }
  12665. const factorToGL = {
  12666. [ZeroFactor]: 0,
  12667. [OneFactor]: 1,
  12668. [SrcColorFactor]: 768,
  12669. [SrcAlphaFactor]: 770,
  12670. [SrcAlphaSaturateFactor]: 776,
  12671. [DstColorFactor]: 774,
  12672. [DstAlphaFactor]: 772,
  12673. [OneMinusSrcColorFactor]: 769,
  12674. [OneMinusSrcAlphaFactor]: 771,
  12675. [OneMinusDstColorFactor]: 775,
  12676. [OneMinusDstAlphaFactor]: 773
  12677. };
  12678. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12679. if (blending === NoBlending) {
  12680. if (currentBlendingEnabled) {
  12681. disable(3042);
  12682. currentBlendingEnabled = false;
  12683. }
  12684. return;
  12685. }
  12686. if (!currentBlendingEnabled) {
  12687. enable(3042);
  12688. currentBlendingEnabled = true;
  12689. }
  12690. if (blending !== CustomBlending) {
  12691. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12692. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12693. gl.blendEquation(32774);
  12694. currentBlendEquation = AddEquation;
  12695. currentBlendEquationAlpha = AddEquation;
  12696. }
  12697. if (premultipliedAlpha) {
  12698. switch (blending) {
  12699. case NormalBlending:
  12700. gl.blendFuncSeparate(1, 771, 1, 771);
  12701. break;
  12702. case AdditiveBlending:
  12703. gl.blendFunc(1, 1);
  12704. break;
  12705. case SubtractiveBlending:
  12706. gl.blendFuncSeparate(0, 0, 769, 771);
  12707. break;
  12708. case MultiplyBlending:
  12709. gl.blendFuncSeparate(0, 768, 0, 770);
  12710. break;
  12711. default:
  12712. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12713. break;
  12714. }
  12715. } else {
  12716. switch (blending) {
  12717. case NormalBlending:
  12718. gl.blendFuncSeparate(770, 771, 1, 771);
  12719. break;
  12720. case AdditiveBlending:
  12721. gl.blendFunc(770, 1);
  12722. break;
  12723. case SubtractiveBlending:
  12724. gl.blendFunc(0, 769);
  12725. break;
  12726. case MultiplyBlending:
  12727. gl.blendFunc(0, 768);
  12728. break;
  12729. default:
  12730. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12731. break;
  12732. }
  12733. }
  12734. currentBlendSrc = null;
  12735. currentBlendDst = null;
  12736. currentBlendSrcAlpha = null;
  12737. currentBlendDstAlpha = null;
  12738. currentBlending = blending;
  12739. currentPremultipledAlpha = premultipliedAlpha;
  12740. }
  12741. return;
  12742. } // custom blending
  12743. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12744. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12745. blendDstAlpha = blendDstAlpha || blendDst;
  12746. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12747. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12748. currentBlendEquation = blendEquation;
  12749. currentBlendEquationAlpha = blendEquationAlpha;
  12750. }
  12751. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12752. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12753. currentBlendSrc = blendSrc;
  12754. currentBlendDst = blendDst;
  12755. currentBlendSrcAlpha = blendSrcAlpha;
  12756. currentBlendDstAlpha = blendDstAlpha;
  12757. }
  12758. currentBlending = blending;
  12759. currentPremultipledAlpha = null;
  12760. }
  12761. function setMaterial(material, frontFaceCW) {
  12762. material.side === DoubleSide ? disable(2884) : enable(2884);
  12763. let flipSided = material.side === BackSide;
  12764. if (frontFaceCW) flipSided = !flipSided;
  12765. setFlipSided(flipSided);
  12766. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  12767. depthBuffer.setFunc(material.depthFunc);
  12768. depthBuffer.setTest(material.depthTest);
  12769. depthBuffer.setMask(material.depthWrite);
  12770. colorBuffer.setMask(material.colorWrite);
  12771. const stencilWrite = material.stencilWrite;
  12772. stencilBuffer.setTest(stencilWrite);
  12773. if (stencilWrite) {
  12774. stencilBuffer.setMask(material.stencilWriteMask);
  12775. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12776. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12777. }
  12778. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12779. } //
  12780. function setFlipSided(flipSided) {
  12781. if (currentFlipSided !== flipSided) {
  12782. if (flipSided) {
  12783. gl.frontFace(2304);
  12784. } else {
  12785. gl.frontFace(2305);
  12786. }
  12787. currentFlipSided = flipSided;
  12788. }
  12789. }
  12790. function setCullFace(cullFace) {
  12791. if (cullFace !== CullFaceNone) {
  12792. enable(2884);
  12793. if (cullFace !== currentCullFace) {
  12794. if (cullFace === CullFaceBack) {
  12795. gl.cullFace(1029);
  12796. } else if (cullFace === CullFaceFront) {
  12797. gl.cullFace(1028);
  12798. } else {
  12799. gl.cullFace(1032);
  12800. }
  12801. }
  12802. } else {
  12803. disable(2884);
  12804. }
  12805. currentCullFace = cullFace;
  12806. }
  12807. function setLineWidth(width) {
  12808. if (width !== currentLineWidth) {
  12809. if (lineWidthAvailable) gl.lineWidth(width);
  12810. currentLineWidth = width;
  12811. }
  12812. }
  12813. function setPolygonOffset(polygonOffset, factor, units) {
  12814. if (polygonOffset) {
  12815. enable(32823);
  12816. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12817. gl.polygonOffset(factor, units);
  12818. currentPolygonOffsetFactor = factor;
  12819. currentPolygonOffsetUnits = units;
  12820. }
  12821. } else {
  12822. disable(32823);
  12823. }
  12824. }
  12825. function setScissorTest(scissorTest) {
  12826. if (scissorTest) {
  12827. enable(3089);
  12828. } else {
  12829. disable(3089);
  12830. }
  12831. } // texture
  12832. function activeTexture(webglSlot) {
  12833. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  12834. if (currentTextureSlot !== webglSlot) {
  12835. gl.activeTexture(webglSlot);
  12836. currentTextureSlot = webglSlot;
  12837. }
  12838. }
  12839. function bindTexture(webglType, webglTexture) {
  12840. if (currentTextureSlot === null) {
  12841. activeTexture();
  12842. }
  12843. let boundTexture = currentBoundTextures[currentTextureSlot];
  12844. if (boundTexture === undefined) {
  12845. boundTexture = {
  12846. type: undefined,
  12847. texture: undefined
  12848. };
  12849. currentBoundTextures[currentTextureSlot] = boundTexture;
  12850. }
  12851. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12852. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12853. boundTexture.type = webglType;
  12854. boundTexture.texture = webglTexture;
  12855. }
  12856. }
  12857. function unbindTexture() {
  12858. const boundTexture = currentBoundTextures[currentTextureSlot];
  12859. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12860. gl.bindTexture(boundTexture.type, null);
  12861. boundTexture.type = undefined;
  12862. boundTexture.texture = undefined;
  12863. }
  12864. }
  12865. function compressedTexImage2D() {
  12866. try {
  12867. gl.compressedTexImage2D.apply(gl, arguments);
  12868. } catch (error) {
  12869. console.error('THREE.WebGLState:', error);
  12870. }
  12871. }
  12872. function texImage2D() {
  12873. try {
  12874. gl.texImage2D.apply(gl, arguments);
  12875. } catch (error) {
  12876. console.error('THREE.WebGLState:', error);
  12877. }
  12878. }
  12879. function texImage3D() {
  12880. try {
  12881. gl.texImage3D.apply(gl, arguments);
  12882. } catch (error) {
  12883. console.error('THREE.WebGLState:', error);
  12884. }
  12885. } //
  12886. function scissor(scissor) {
  12887. if (currentScissor.equals(scissor) === false) {
  12888. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12889. currentScissor.copy(scissor);
  12890. }
  12891. }
  12892. function viewport(viewport) {
  12893. if (currentViewport.equals(viewport) === false) {
  12894. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12895. currentViewport.copy(viewport);
  12896. }
  12897. } //
  12898. function reset() {
  12899. enabledCapabilities = {};
  12900. currentTextureSlot = null;
  12901. currentBoundTextures = {};
  12902. currentProgram = null;
  12903. currentBlendingEnabled = null;
  12904. currentBlending = null;
  12905. currentBlendEquation = null;
  12906. currentBlendSrc = null;
  12907. currentBlendDst = null;
  12908. currentBlendEquationAlpha = null;
  12909. currentBlendSrcAlpha = null;
  12910. currentBlendDstAlpha = null;
  12911. currentPremultipledAlpha = false;
  12912. currentFlipSided = null;
  12913. currentCullFace = null;
  12914. currentLineWidth = null;
  12915. currentPolygonOffsetFactor = null;
  12916. currentPolygonOffsetUnits = null;
  12917. colorBuffer.reset();
  12918. depthBuffer.reset();
  12919. stencilBuffer.reset();
  12920. }
  12921. return {
  12922. buffers: {
  12923. color: colorBuffer,
  12924. depth: depthBuffer,
  12925. stencil: stencilBuffer
  12926. },
  12927. enable: enable,
  12928. disable: disable,
  12929. useProgram: useProgram,
  12930. setBlending: setBlending,
  12931. setMaterial: setMaterial,
  12932. setFlipSided: setFlipSided,
  12933. setCullFace: setCullFace,
  12934. setLineWidth: setLineWidth,
  12935. setPolygonOffset: setPolygonOffset,
  12936. setScissorTest: setScissorTest,
  12937. activeTexture: activeTexture,
  12938. bindTexture: bindTexture,
  12939. unbindTexture: unbindTexture,
  12940. compressedTexImage2D: compressedTexImage2D,
  12941. texImage2D: texImage2D,
  12942. texImage3D: texImage3D,
  12943. scissor: scissor,
  12944. viewport: viewport,
  12945. reset: reset
  12946. };
  12947. }
  12948. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12949. const isWebGL2 = capabilities.isWebGL2;
  12950. const maxTextures = capabilities.maxTextures;
  12951. const maxCubemapSize = capabilities.maxCubemapSize;
  12952. const maxTextureSize = capabilities.maxTextureSize;
  12953. const maxSamples = capabilities.maxSamples;
  12954. const _videoTextures = new WeakMap();
  12955. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12956. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12957. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12958. let useOffscreenCanvas = false;
  12959. try {
  12960. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  12961. } catch (err) {// Ignore any errors
  12962. }
  12963. function createCanvas(width, height) {
  12964. // Use OffscreenCanvas when available. Specially needed in web workers
  12965. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12966. }
  12967. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12968. let scale = 1; // handle case if texture exceeds max size
  12969. if (image.width > maxSize || image.height > maxSize) {
  12970. scale = maxSize / Math.max(image.width, image.height);
  12971. } // only perform resize if necessary
  12972. if (scale < 1 || needsPowerOfTwo === true) {
  12973. // only perform resize for certain image types
  12974. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12975. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  12976. const width = floor(scale * image.width);
  12977. const height = floor(scale * image.height);
  12978. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12979. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12980. canvas.width = width;
  12981. canvas.height = height;
  12982. const context = canvas.getContext('2d');
  12983. context.drawImage(image, 0, 0, width, height);
  12984. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12985. return canvas;
  12986. } else {
  12987. if ('data' in image) {
  12988. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12989. }
  12990. return image;
  12991. }
  12992. }
  12993. return image;
  12994. }
  12995. function isPowerOfTwo(image) {
  12996. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  12997. }
  12998. function textureNeedsPowerOfTwo(texture) {
  12999. if (isWebGL2) return false;
  13000. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13001. }
  13002. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13003. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13004. }
  13005. function generateMipmap(target, texture, width, height) {
  13006. _gl.generateMipmap(target);
  13007. const textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13008. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13009. }
  13010. function getInternalFormat(internalFormatName, glFormat, glType) {
  13011. if (isWebGL2 === false) return glFormat;
  13012. if (internalFormatName !== null) {
  13013. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13014. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13015. }
  13016. let internalFormat = glFormat;
  13017. if (glFormat === 6403) {
  13018. if (glType === 5126) internalFormat = 33326;
  13019. if (glType === 5131) internalFormat = 33325;
  13020. if (glType === 5121) internalFormat = 33321;
  13021. }
  13022. if (glFormat === 6407) {
  13023. if (glType === 5126) internalFormat = 34837;
  13024. if (glType === 5131) internalFormat = 34843;
  13025. if (glType === 5121) internalFormat = 32849;
  13026. }
  13027. if (glFormat === 6408) {
  13028. if (glType === 5126) internalFormat = 34836;
  13029. if (glType === 5131) internalFormat = 34842;
  13030. if (glType === 5121) internalFormat = 32856;
  13031. }
  13032. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13033. extensions.get('EXT_color_buffer_float');
  13034. }
  13035. return internalFormat;
  13036. } // Fallback filters for non-power-of-2 textures
  13037. function filterFallback(f) {
  13038. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13039. return 9728;
  13040. }
  13041. return 9729;
  13042. } //
  13043. function onTextureDispose(event) {
  13044. const texture = event.target;
  13045. texture.removeEventListener('dispose', onTextureDispose);
  13046. deallocateTexture(texture);
  13047. if (texture.isVideoTexture) {
  13048. _videoTextures.delete(texture);
  13049. }
  13050. info.memory.textures--;
  13051. }
  13052. function onRenderTargetDispose(event) {
  13053. const renderTarget = event.target;
  13054. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13055. deallocateRenderTarget(renderTarget);
  13056. info.memory.textures--;
  13057. } //
  13058. function deallocateTexture(texture) {
  13059. const textureProperties = properties.get(texture);
  13060. if (textureProperties.__webglInit === undefined) return;
  13061. _gl.deleteTexture(textureProperties.__webglTexture);
  13062. properties.remove(texture);
  13063. }
  13064. function deallocateRenderTarget(renderTarget) {
  13065. const renderTargetProperties = properties.get(renderTarget);
  13066. const textureProperties = properties.get(renderTarget.texture);
  13067. if (!renderTarget) return;
  13068. if (textureProperties.__webglTexture !== undefined) {
  13069. _gl.deleteTexture(textureProperties.__webglTexture);
  13070. }
  13071. if (renderTarget.depthTexture) {
  13072. renderTarget.depthTexture.dispose();
  13073. }
  13074. if (renderTarget.isWebGLCubeRenderTarget) {
  13075. for (let i = 0; i < 6; i++) {
  13076. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13077. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13078. }
  13079. } else {
  13080. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13081. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13082. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13083. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13084. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13085. }
  13086. properties.remove(renderTarget.texture);
  13087. properties.remove(renderTarget);
  13088. } //
  13089. let textureUnits = 0;
  13090. function resetTextureUnits() {
  13091. textureUnits = 0;
  13092. }
  13093. function allocateTextureUnit() {
  13094. const textureUnit = textureUnits;
  13095. if (textureUnit >= maxTextures) {
  13096. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13097. }
  13098. textureUnits += 1;
  13099. return textureUnit;
  13100. } //
  13101. function setTexture2D(texture, slot) {
  13102. const textureProperties = properties.get(texture);
  13103. if (texture.isVideoTexture) updateVideoTexture(texture);
  13104. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13105. const image = texture.image;
  13106. if (image === undefined) {
  13107. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13108. } else if (image.complete === false) {
  13109. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13110. } else {
  13111. uploadTexture(textureProperties, texture, slot);
  13112. return;
  13113. }
  13114. }
  13115. state.activeTexture(33984 + slot);
  13116. state.bindTexture(3553, textureProperties.__webglTexture);
  13117. }
  13118. function setTexture2DArray(texture, slot) {
  13119. const textureProperties = properties.get(texture);
  13120. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13121. uploadTexture(textureProperties, texture, slot);
  13122. return;
  13123. }
  13124. state.activeTexture(33984 + slot);
  13125. state.bindTexture(35866, textureProperties.__webglTexture);
  13126. }
  13127. function setTexture3D(texture, slot) {
  13128. const textureProperties = properties.get(texture);
  13129. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13130. uploadTexture(textureProperties, texture, slot);
  13131. return;
  13132. }
  13133. state.activeTexture(33984 + slot);
  13134. state.bindTexture(32879, textureProperties.__webglTexture);
  13135. }
  13136. function setTextureCube(texture, slot) {
  13137. const textureProperties = properties.get(texture);
  13138. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13139. uploadCubeTexture(textureProperties, texture, slot);
  13140. return;
  13141. }
  13142. state.activeTexture(33984 + slot);
  13143. state.bindTexture(34067, textureProperties.__webglTexture);
  13144. }
  13145. const wrappingToGL = {
  13146. [RepeatWrapping]: 10497,
  13147. [ClampToEdgeWrapping]: 33071,
  13148. [MirroredRepeatWrapping]: 33648
  13149. };
  13150. const filterToGL = {
  13151. [NearestFilter]: 9728,
  13152. [NearestMipmapNearestFilter]: 9984,
  13153. [NearestMipmapLinearFilter]: 9986,
  13154. [LinearFilter]: 9729,
  13155. [LinearMipmapNearestFilter]: 9985,
  13156. [LinearMipmapLinearFilter]: 9987
  13157. };
  13158. function setTextureParameters(textureType, texture, supportsMips) {
  13159. if (supportsMips) {
  13160. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  13161. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  13162. if (textureType === 32879 || textureType === 35866) {
  13163. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  13164. }
  13165. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  13166. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  13167. } else {
  13168. _gl.texParameteri(textureType, 10242, 33071);
  13169. _gl.texParameteri(textureType, 10243, 33071);
  13170. if (textureType === 32879 || textureType === 35866) {
  13171. _gl.texParameteri(textureType, 32882, 33071);
  13172. }
  13173. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13174. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13175. }
  13176. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13177. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13178. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13179. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13180. }
  13181. }
  13182. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13183. if (extension) {
  13184. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13185. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13186. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13187. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13188. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13189. }
  13190. }
  13191. }
  13192. function initTexture(textureProperties, texture) {
  13193. if (textureProperties.__webglInit === undefined) {
  13194. textureProperties.__webglInit = true;
  13195. texture.addEventListener('dispose', onTextureDispose);
  13196. textureProperties.__webglTexture = _gl.createTexture();
  13197. info.memory.textures++;
  13198. }
  13199. }
  13200. function uploadTexture(textureProperties, texture, slot) {
  13201. let textureType = 3553;
  13202. if (texture.isDataTexture2DArray) textureType = 35866;
  13203. if (texture.isDataTexture3D) textureType = 32879;
  13204. initTexture(textureProperties, texture);
  13205. state.activeTexture(33984 + slot);
  13206. state.bindTexture(textureType, textureProperties.__webglTexture);
  13207. _gl.pixelStorei(37440, texture.flipY);
  13208. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13209. _gl.pixelStorei(3317, texture.unpackAlignment);
  13210. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13211. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13212. const supportsMips = isPowerOfTwo(image) || isWebGL2,
  13213. glFormat = utils.convert(texture.format);
  13214. let glType = utils.convert(texture.type),
  13215. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13216. setTextureParameters(textureType, texture, supportsMips);
  13217. let mipmap;
  13218. const mipmaps = texture.mipmaps;
  13219. if (texture.isDepthTexture) {
  13220. // populate depth texture with dummy data
  13221. glInternalFormat = 6402;
  13222. if (isWebGL2) {
  13223. if (texture.type === FloatType) {
  13224. glInternalFormat = 36012;
  13225. } else if (texture.type === UnsignedIntType) {
  13226. glInternalFormat = 33190;
  13227. } else if (texture.type === UnsignedInt248Type) {
  13228. glInternalFormat = 35056;
  13229. } else {
  13230. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13231. }
  13232. } else {
  13233. if (texture.type === FloatType) {
  13234. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13235. }
  13236. } // validation checks for WebGL 1
  13237. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13238. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13239. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13240. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13241. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13242. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13243. texture.type = UnsignedShortType;
  13244. glType = utils.convert(texture.type);
  13245. }
  13246. }
  13247. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  13248. // Depth stencil textures need the DEPTH_STENCIL internal format
  13249. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13250. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13251. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13252. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13253. if (texture.type !== UnsignedInt248Type) {
  13254. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13255. texture.type = UnsignedInt248Type;
  13256. glType = utils.convert(texture.type);
  13257. }
  13258. } //
  13259. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13260. } else if (texture.isDataTexture) {
  13261. // use manually created mipmaps if available
  13262. // if there are no manual mipmaps
  13263. // set 0 level mipmap and then use GL to generate other mipmap levels
  13264. if (mipmaps.length > 0 && supportsMips) {
  13265. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13266. mipmap = mipmaps[i];
  13267. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13268. }
  13269. texture.generateMipmaps = false;
  13270. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13271. } else {
  13272. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13273. textureProperties.__maxMipLevel = 0;
  13274. }
  13275. } else if (texture.isCompressedTexture) {
  13276. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13277. mipmap = mipmaps[i];
  13278. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13279. if (glFormat !== null) {
  13280. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13281. } else {
  13282. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13283. }
  13284. } else {
  13285. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13286. }
  13287. }
  13288. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13289. } else if (texture.isDataTexture2DArray) {
  13290. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13291. textureProperties.__maxMipLevel = 0;
  13292. } else if (texture.isDataTexture3D) {
  13293. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13294. textureProperties.__maxMipLevel = 0;
  13295. } else {
  13296. // regular Texture (image, video, canvas)
  13297. // use manually created mipmaps if available
  13298. // if there are no manual mipmaps
  13299. // set 0 level mipmap and then use GL to generate other mipmap levels
  13300. if (mipmaps.length > 0 && supportsMips) {
  13301. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13302. mipmap = mipmaps[i];
  13303. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13304. }
  13305. texture.generateMipmaps = false;
  13306. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13307. } else {
  13308. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13309. textureProperties.__maxMipLevel = 0;
  13310. }
  13311. }
  13312. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13313. generateMipmap(textureType, texture, image.width, image.height);
  13314. }
  13315. textureProperties.__version = texture.version;
  13316. if (texture.onUpdate) texture.onUpdate(texture);
  13317. }
  13318. function uploadCubeTexture(textureProperties, texture, slot) {
  13319. if (texture.image.length !== 6) return;
  13320. initTexture(textureProperties, texture);
  13321. state.activeTexture(33984 + slot);
  13322. state.bindTexture(34067, textureProperties.__webglTexture);
  13323. _gl.pixelStorei(37440, texture.flipY);
  13324. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13325. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13326. const cubeImage = [];
  13327. for (let i = 0; i < 6; i++) {
  13328. if (!isCompressed && !isDataTexture) {
  13329. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13330. } else {
  13331. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13332. }
  13333. }
  13334. const image = cubeImage[0],
  13335. supportsMips = isPowerOfTwo(image) || isWebGL2,
  13336. glFormat = utils.convert(texture.format),
  13337. glType = utils.convert(texture.type),
  13338. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13339. setTextureParameters(34067, texture, supportsMips);
  13340. let mipmaps;
  13341. if (isCompressed) {
  13342. for (let i = 0; i < 6; i++) {
  13343. mipmaps = cubeImage[i].mipmaps;
  13344. for (let j = 0; j < mipmaps.length; j++) {
  13345. const mipmap = mipmaps[j];
  13346. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13347. if (glFormat !== null) {
  13348. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13349. } else {
  13350. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13351. }
  13352. } else {
  13353. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13354. }
  13355. }
  13356. }
  13357. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13358. } else {
  13359. mipmaps = texture.mipmaps;
  13360. for (let i = 0; i < 6; i++) {
  13361. if (isDataTexture) {
  13362. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13363. for (let j = 0; j < mipmaps.length; j++) {
  13364. const mipmap = mipmaps[j];
  13365. const mipmapImage = mipmap.image[i].image;
  13366. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13367. }
  13368. } else {
  13369. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13370. for (let j = 0; j < mipmaps.length; j++) {
  13371. const mipmap = mipmaps[j];
  13372. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13373. }
  13374. }
  13375. }
  13376. textureProperties.__maxMipLevel = mipmaps.length;
  13377. }
  13378. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13379. // We assume images for cube map have the same size.
  13380. generateMipmap(34067, texture, image.width, image.height);
  13381. }
  13382. textureProperties.__version = texture.version;
  13383. if (texture.onUpdate) texture.onUpdate(texture);
  13384. } // Render targets
  13385. // Setup storage for target texture and bind it to correct framebuffer
  13386. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13387. const glFormat = utils.convert(renderTarget.texture.format);
  13388. const glType = utils.convert(renderTarget.texture.type);
  13389. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13390. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13391. _gl.bindFramebuffer(36160, framebuffer);
  13392. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13393. _gl.bindFramebuffer(36160, null);
  13394. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13395. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13396. _gl.bindRenderbuffer(36161, renderbuffer);
  13397. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13398. let glInternalFormat = 33189;
  13399. if (isMultisample) {
  13400. const depthTexture = renderTarget.depthTexture;
  13401. if (depthTexture && depthTexture.isDepthTexture) {
  13402. if (depthTexture.type === FloatType) {
  13403. glInternalFormat = 36012;
  13404. } else if (depthTexture.type === UnsignedIntType) {
  13405. glInternalFormat = 33190;
  13406. }
  13407. }
  13408. const samples = getRenderTargetSamples(renderTarget);
  13409. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13410. } else {
  13411. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13412. }
  13413. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13414. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13415. if (isMultisample) {
  13416. const samples = getRenderTargetSamples(renderTarget);
  13417. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13418. } else {
  13419. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13420. }
  13421. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13422. } else {
  13423. const glFormat = utils.convert(renderTarget.texture.format);
  13424. const glType = utils.convert(renderTarget.texture.type);
  13425. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13426. if (isMultisample) {
  13427. const samples = getRenderTargetSamples(renderTarget);
  13428. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13429. } else {
  13430. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13431. }
  13432. }
  13433. _gl.bindRenderbuffer(36161, null);
  13434. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13435. function setupDepthTexture(framebuffer, renderTarget) {
  13436. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13437. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13438. _gl.bindFramebuffer(36160, framebuffer);
  13439. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13440. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13441. } // upload an empty depth texture with framebuffer size
  13442. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13443. renderTarget.depthTexture.image.width = renderTarget.width;
  13444. renderTarget.depthTexture.image.height = renderTarget.height;
  13445. renderTarget.depthTexture.needsUpdate = true;
  13446. }
  13447. setTexture2D(renderTarget.depthTexture, 0);
  13448. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13449. if (renderTarget.depthTexture.format === DepthFormat) {
  13450. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13451. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13452. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13453. } else {
  13454. throw new Error('Unknown depthTexture format');
  13455. }
  13456. } // Setup GL resources for a non-texture depth buffer
  13457. function setupDepthRenderbuffer(renderTarget) {
  13458. const renderTargetProperties = properties.get(renderTarget);
  13459. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13460. if (renderTarget.depthTexture) {
  13461. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13462. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13463. } else {
  13464. if (isCube) {
  13465. renderTargetProperties.__webglDepthbuffer = [];
  13466. for (let i = 0; i < 6; i++) {
  13467. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13468. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13469. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13470. }
  13471. } else {
  13472. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13473. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13474. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13475. }
  13476. }
  13477. _gl.bindFramebuffer(36160, null);
  13478. } // Set up GL resources for the render target
  13479. function setupRenderTarget(renderTarget) {
  13480. const renderTargetProperties = properties.get(renderTarget);
  13481. const textureProperties = properties.get(renderTarget.texture);
  13482. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13483. textureProperties.__webglTexture = _gl.createTexture();
  13484. info.memory.textures++;
  13485. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13486. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13487. const supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13488. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  13489. renderTarget.texture.format = RGBAFormat;
  13490. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13491. } // Setup framebuffer
  13492. if (isCube) {
  13493. renderTargetProperties.__webglFramebuffer = [];
  13494. for (let i = 0; i < 6; i++) {
  13495. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13496. }
  13497. } else {
  13498. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13499. if (isMultisample) {
  13500. if (isWebGL2) {
  13501. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13502. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13503. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13504. const glFormat = utils.convert(renderTarget.texture.format);
  13505. const glType = utils.convert(renderTarget.texture.type);
  13506. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13507. const samples = getRenderTargetSamples(renderTarget);
  13508. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13509. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  13510. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  13511. _gl.bindRenderbuffer(36161, null);
  13512. if (renderTarget.depthBuffer) {
  13513. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13514. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13515. }
  13516. _gl.bindFramebuffer(36160, null);
  13517. } else {
  13518. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13519. }
  13520. }
  13521. } // Setup color buffer
  13522. if (isCube) {
  13523. state.bindTexture(34067, textureProperties.__webglTexture);
  13524. setTextureParameters(34067, renderTarget.texture, supportsMips);
  13525. for (let i = 0; i < 6; i++) {
  13526. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  13527. }
  13528. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13529. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  13530. }
  13531. state.bindTexture(34067, null);
  13532. } else {
  13533. state.bindTexture(3553, textureProperties.__webglTexture);
  13534. setTextureParameters(3553, renderTarget.texture, supportsMips);
  13535. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  13536. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13537. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  13538. }
  13539. state.bindTexture(3553, null);
  13540. } // Setup depth and stencil buffers
  13541. if (renderTarget.depthBuffer) {
  13542. setupDepthRenderbuffer(renderTarget);
  13543. }
  13544. }
  13545. function updateRenderTargetMipmap(renderTarget) {
  13546. const texture = renderTarget.texture;
  13547. const supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  13548. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13549. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13550. const webglTexture = properties.get(texture).__webglTexture;
  13551. state.bindTexture(target, webglTexture);
  13552. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13553. state.bindTexture(target, null);
  13554. }
  13555. }
  13556. function updateMultisampleRenderTarget(renderTarget) {
  13557. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13558. if (isWebGL2) {
  13559. const renderTargetProperties = properties.get(renderTarget);
  13560. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  13561. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  13562. const width = renderTarget.width;
  13563. const height = renderTarget.height;
  13564. let mask = 16384;
  13565. if (renderTarget.depthBuffer) mask |= 256;
  13566. if (renderTarget.stencilBuffer) mask |= 1024;
  13567. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  13568. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  13569. } else {
  13570. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13571. }
  13572. }
  13573. }
  13574. function getRenderTargetSamples(renderTarget) {
  13575. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13576. }
  13577. function updateVideoTexture(texture) {
  13578. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13579. if (_videoTextures.get(texture) !== frame) {
  13580. _videoTextures.set(texture, frame);
  13581. texture.update();
  13582. }
  13583. } // backwards compatibility
  13584. let warnedTexture2D = false;
  13585. let warnedTextureCube = false;
  13586. function safeSetTexture2D(texture, slot) {
  13587. if (texture && texture.isWebGLRenderTarget) {
  13588. if (warnedTexture2D === false) {
  13589. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  13590. warnedTexture2D = true;
  13591. }
  13592. texture = texture.texture;
  13593. }
  13594. setTexture2D(texture, slot);
  13595. }
  13596. function safeSetTextureCube(texture, slot) {
  13597. if (texture && texture.isWebGLCubeRenderTarget) {
  13598. if (warnedTextureCube === false) {
  13599. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  13600. warnedTextureCube = true;
  13601. }
  13602. texture = texture.texture;
  13603. }
  13604. setTextureCube(texture, slot);
  13605. } //
  13606. this.allocateTextureUnit = allocateTextureUnit;
  13607. this.resetTextureUnits = resetTextureUnits;
  13608. this.setTexture2D = setTexture2D;
  13609. this.setTexture2DArray = setTexture2DArray;
  13610. this.setTexture3D = setTexture3D;
  13611. this.setTextureCube = setTextureCube;
  13612. this.setupRenderTarget = setupRenderTarget;
  13613. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13614. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13615. this.safeSetTexture2D = safeSetTexture2D;
  13616. this.safeSetTextureCube = safeSetTextureCube;
  13617. }
  13618. function WebGLUtils(gl, extensions, capabilities) {
  13619. const isWebGL2 = capabilities.isWebGL2;
  13620. function convert(p) {
  13621. let extension;
  13622. if (p === UnsignedByteType) return 5121;
  13623. if (p === UnsignedShort4444Type) return 32819;
  13624. if (p === UnsignedShort5551Type) return 32820;
  13625. if (p === UnsignedShort565Type) return 33635;
  13626. if (p === ByteType) return 5120;
  13627. if (p === ShortType) return 5122;
  13628. if (p === UnsignedShortType) return 5123;
  13629. if (p === IntType) return 5124;
  13630. if (p === UnsignedIntType) return 5125;
  13631. if (p === FloatType) return 5126;
  13632. if (p === HalfFloatType) {
  13633. if (isWebGL2) return 5131;
  13634. extension = extensions.get('OES_texture_half_float');
  13635. if (extension !== null) {
  13636. return extension.HALF_FLOAT_OES;
  13637. } else {
  13638. return null;
  13639. }
  13640. }
  13641. if (p === AlphaFormat) return 6406;
  13642. if (p === RGBFormat) return 6407;
  13643. if (p === RGBAFormat) return 6408;
  13644. if (p === LuminanceFormat) return 6409;
  13645. if (p === LuminanceAlphaFormat) return 6410;
  13646. if (p === DepthFormat) return 6402;
  13647. if (p === DepthStencilFormat) return 34041;
  13648. if (p === RedFormat) return 6403; // WebGL2 formats.
  13649. if (p === RedIntegerFormat) return 36244;
  13650. if (p === RGFormat) return 33319;
  13651. if (p === RGIntegerFormat) return 33320;
  13652. if (p === RGBIntegerFormat) return 36248;
  13653. if (p === RGBAIntegerFormat) return 36249;
  13654. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13655. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13656. if (extension !== null) {
  13657. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13658. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13659. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13660. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13661. } else {
  13662. return null;
  13663. }
  13664. }
  13665. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13666. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13667. if (extension !== null) {
  13668. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13669. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13670. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13671. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13672. } else {
  13673. return null;
  13674. }
  13675. }
  13676. if (p === RGB_ETC1_Format) {
  13677. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13678. if (extension !== null) {
  13679. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13680. } else {
  13681. return null;
  13682. }
  13683. }
  13684. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13685. extension = extensions.get('WEBGL_compressed_texture_etc');
  13686. if (extension !== null) {
  13687. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13688. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13689. }
  13690. }
  13691. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  13692. extension = extensions.get('WEBGL_compressed_texture_astc');
  13693. if (extension !== null) {
  13694. // TODO Complete?
  13695. return p;
  13696. } else {
  13697. return null;
  13698. }
  13699. }
  13700. if (p === RGBA_BPTC_Format) {
  13701. extension = extensions.get('EXT_texture_compression_bptc');
  13702. if (extension !== null) {
  13703. // TODO Complete?
  13704. return p;
  13705. } else {
  13706. return null;
  13707. }
  13708. }
  13709. if (p === UnsignedInt248Type) {
  13710. if (isWebGL2) return 34042;
  13711. extension = extensions.get('WEBGL_depth_texture');
  13712. if (extension !== null) {
  13713. return extension.UNSIGNED_INT_24_8_WEBGL;
  13714. } else {
  13715. return null;
  13716. }
  13717. }
  13718. }
  13719. return {
  13720. convert: convert
  13721. };
  13722. }
  13723. function ArrayCamera(array = []) {
  13724. PerspectiveCamera.call(this);
  13725. this.cameras = array;
  13726. }
  13727. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  13728. constructor: ArrayCamera,
  13729. isArrayCamera: true
  13730. });
  13731. function Group() {
  13732. Object3D.call(this);
  13733. this.type = 'Group';
  13734. }
  13735. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  13736. constructor: Group,
  13737. isGroup: true
  13738. });
  13739. function WebXRController() {
  13740. this._targetRay = null;
  13741. this._grip = null;
  13742. this._hand = null;
  13743. }
  13744. Object.assign(WebXRController.prototype, {
  13745. constructor: WebXRController,
  13746. getHandSpace: function () {
  13747. if (this._hand === null) {
  13748. this._hand = new Group();
  13749. this._hand.matrixAutoUpdate = false;
  13750. this._hand.visible = false;
  13751. this._hand.joints = [];
  13752. this._hand.inputState = {
  13753. pinching: false
  13754. };
  13755. if (window.XRHand) {
  13756. for (let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  13757. // The transform of this joint will be updated with the joint pose on each frame
  13758. const joint = new Group();
  13759. joint.matrixAutoUpdate = false;
  13760. joint.visible = false;
  13761. this._hand.joints.push(joint); // ??
  13762. this._hand.add(joint);
  13763. }
  13764. }
  13765. }
  13766. return this._hand;
  13767. },
  13768. getTargetRaySpace: function () {
  13769. if (this._targetRay === null) {
  13770. this._targetRay = new Group();
  13771. this._targetRay.matrixAutoUpdate = false;
  13772. this._targetRay.visible = false;
  13773. }
  13774. return this._targetRay;
  13775. },
  13776. getGripSpace: function () {
  13777. if (this._grip === null) {
  13778. this._grip = new Group();
  13779. this._grip.matrixAutoUpdate = false;
  13780. this._grip.visible = false;
  13781. }
  13782. return this._grip;
  13783. },
  13784. dispatchEvent: function (event) {
  13785. if (this._targetRay !== null) {
  13786. this._targetRay.dispatchEvent(event);
  13787. }
  13788. if (this._grip !== null) {
  13789. this._grip.dispatchEvent(event);
  13790. }
  13791. if (this._hand !== null) {
  13792. this._hand.dispatchEvent(event);
  13793. }
  13794. return this;
  13795. },
  13796. disconnect: function (inputSource) {
  13797. this.dispatchEvent({
  13798. type: 'disconnected',
  13799. data: inputSource
  13800. });
  13801. if (this._targetRay !== null) {
  13802. this._targetRay.visible = false;
  13803. }
  13804. if (this._grip !== null) {
  13805. this._grip.visible = false;
  13806. }
  13807. if (this._hand !== null) {
  13808. this._hand.visible = false;
  13809. }
  13810. return this;
  13811. },
  13812. update: function (inputSource, frame, referenceSpace) {
  13813. let inputPose = null;
  13814. let gripPose = null;
  13815. let handPose = null;
  13816. const targetRay = this._targetRay;
  13817. const grip = this._grip;
  13818. const hand = this._hand;
  13819. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13820. if (hand && inputSource.hand) {
  13821. handPose = true;
  13822. for (let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  13823. if (inputSource.hand[i]) {
  13824. // Update the joints groups with the XRJoint poses
  13825. const jointPose = frame.getJointPose(inputSource.hand[i], referenceSpace);
  13826. const joint = hand.joints[i];
  13827. if (jointPose !== null) {
  13828. joint.matrix.fromArray(jointPose.transform.matrix);
  13829. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13830. joint.jointRadius = jointPose.radius;
  13831. }
  13832. joint.visible = jointPose !== null; // Custom events
  13833. // Check pinch
  13834. const indexTip = hand.joints[window.XRHand.INDEX_PHALANX_TIP];
  13835. const thumbTip = hand.joints[window.XRHand.THUMB_PHALANX_TIP];
  13836. const distance = indexTip.position.distanceTo(thumbTip.position);
  13837. const distanceToPinch = 0.02;
  13838. const threshold = 0.005;
  13839. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13840. hand.inputState.pinching = false;
  13841. this.dispatchEvent({
  13842. type: "pinchend",
  13843. handedness: inputSource.handedness,
  13844. target: this
  13845. });
  13846. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13847. hand.inputState.pinching = true;
  13848. this.dispatchEvent({
  13849. type: "pinchstart",
  13850. handedness: inputSource.handedness,
  13851. target: this
  13852. });
  13853. }
  13854. }
  13855. }
  13856. } else {
  13857. if (targetRay !== null) {
  13858. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13859. if (inputPose !== null) {
  13860. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13861. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13862. }
  13863. }
  13864. if (grip !== null && inputSource.gripSpace) {
  13865. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13866. if (gripPose !== null) {
  13867. grip.matrix.fromArray(gripPose.transform.matrix);
  13868. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13869. }
  13870. }
  13871. }
  13872. }
  13873. if (targetRay !== null) {
  13874. targetRay.visible = inputPose !== null;
  13875. }
  13876. if (grip !== null) {
  13877. grip.visible = gripPose !== null;
  13878. }
  13879. if (hand !== null) {
  13880. hand.visible = handPose !== null;
  13881. }
  13882. return this;
  13883. }
  13884. });
  13885. function WebXRManager(renderer, gl) {
  13886. const scope = this;
  13887. let session = null;
  13888. let framebufferScaleFactor = 1.0;
  13889. let referenceSpace = null;
  13890. let referenceSpaceType = 'local-floor';
  13891. let pose = null;
  13892. const controllers = [];
  13893. const inputSourcesMap = new Map(); //
  13894. const cameraL = new PerspectiveCamera();
  13895. cameraL.layers.enable(1);
  13896. cameraL.viewport = new Vector4();
  13897. const cameraR = new PerspectiveCamera();
  13898. cameraR.layers.enable(2);
  13899. cameraR.viewport = new Vector4();
  13900. const cameras = [cameraL, cameraR];
  13901. const cameraVR = new ArrayCamera();
  13902. cameraVR.layers.enable(1);
  13903. cameraVR.layers.enable(2);
  13904. let _currentDepthNear = null;
  13905. let _currentDepthFar = null; //
  13906. this.enabled = false;
  13907. this.isPresenting = false;
  13908. this.getController = function (index) {
  13909. let controller = controllers[index];
  13910. if (controller === undefined) {
  13911. controller = new WebXRController();
  13912. controllers[index] = controller;
  13913. }
  13914. return controller.getTargetRaySpace();
  13915. };
  13916. this.getControllerGrip = function (index) {
  13917. let controller = controllers[index];
  13918. if (controller === undefined) {
  13919. controller = new WebXRController();
  13920. controllers[index] = controller;
  13921. }
  13922. return controller.getGripSpace();
  13923. };
  13924. this.getHand = function (index) {
  13925. let controller = controllers[index];
  13926. if (controller === undefined) {
  13927. controller = new WebXRController();
  13928. controllers[index] = controller;
  13929. }
  13930. return controller.getHandSpace();
  13931. }; //
  13932. function onSessionEvent(event) {
  13933. const controller = inputSourcesMap.get(event.inputSource);
  13934. if (controller) {
  13935. controller.dispatchEvent({
  13936. type: event.type,
  13937. data: event.inputSource
  13938. });
  13939. }
  13940. }
  13941. function onSessionEnd() {
  13942. inputSourcesMap.forEach(function (controller, inputSource) {
  13943. controller.disconnect(inputSource);
  13944. });
  13945. inputSourcesMap.clear(); //
  13946. renderer.setFramebuffer(null);
  13947. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  13948. animation.stop();
  13949. scope.isPresenting = false;
  13950. scope.dispatchEvent({
  13951. type: 'sessionend'
  13952. });
  13953. }
  13954. function onRequestReferenceSpace(value) {
  13955. referenceSpace = value;
  13956. animation.setContext(session);
  13957. animation.start();
  13958. scope.isPresenting = true;
  13959. scope.dispatchEvent({
  13960. type: 'sessionstart'
  13961. });
  13962. }
  13963. this.setFramebufferScaleFactor = function (value) {
  13964. framebufferScaleFactor = value;
  13965. if (scope.isPresenting === true) {
  13966. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13967. }
  13968. };
  13969. this.setReferenceSpaceType = function (value) {
  13970. referenceSpaceType = value;
  13971. if (scope.isPresenting === true) {
  13972. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13973. }
  13974. };
  13975. this.getReferenceSpace = function () {
  13976. return referenceSpace;
  13977. };
  13978. this.getSession = function () {
  13979. return session;
  13980. };
  13981. this.setSession = function (value) {
  13982. session = value;
  13983. if (session !== null) {
  13984. session.addEventListener('select', onSessionEvent);
  13985. session.addEventListener('selectstart', onSessionEvent);
  13986. session.addEventListener('selectend', onSessionEvent);
  13987. session.addEventListener('squeeze', onSessionEvent);
  13988. session.addEventListener('squeezestart', onSessionEvent);
  13989. session.addEventListener('squeezeend', onSessionEvent);
  13990. session.addEventListener('end', onSessionEnd);
  13991. const attributes = gl.getContextAttributes();
  13992. if (attributes.xrCompatible !== true) {
  13993. gl.makeXRCompatible();
  13994. }
  13995. const layerInit = {
  13996. antialias: attributes.antialias,
  13997. alpha: attributes.alpha,
  13998. depth: attributes.depth,
  13999. stencil: attributes.stencil,
  14000. framebufferScaleFactor: framebufferScaleFactor
  14001. }; // eslint-disable-next-line no-undef
  14002. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  14003. session.updateRenderState({
  14004. baseLayer: baseLayer
  14005. });
  14006. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14007. session.addEventListener('inputsourceschange', updateInputSources);
  14008. }
  14009. };
  14010. function updateInputSources(event) {
  14011. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14012. for (let i = 0; i < controllers.length; i++) {
  14013. inputSourcesMap.set(inputSources[i], controllers[i]);
  14014. } // Notify disconnected
  14015. for (let i = 0; i < event.removed.length; i++) {
  14016. const inputSource = event.removed[i];
  14017. const controller = inputSourcesMap.get(inputSource);
  14018. if (controller) {
  14019. controller.dispatchEvent({
  14020. type: 'disconnected',
  14021. data: inputSource
  14022. });
  14023. inputSourcesMap.delete(inputSource);
  14024. }
  14025. } // Notify connected
  14026. for (let i = 0; i < event.added.length; i++) {
  14027. const inputSource = event.added[i];
  14028. const controller = inputSourcesMap.get(inputSource);
  14029. if (controller) {
  14030. controller.dispatchEvent({
  14031. type: 'connected',
  14032. data: inputSource
  14033. });
  14034. }
  14035. }
  14036. } //
  14037. const cameraLPos = new Vector3();
  14038. const cameraRPos = new Vector3();
  14039. /**
  14040. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14041. * the cameras' projection and world matrices have already been set.
  14042. * And that near and far planes are identical for both cameras.
  14043. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14044. */
  14045. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14046. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14047. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14048. const ipd = cameraLPos.distanceTo(cameraRPos);
  14049. const projL = cameraL.projectionMatrix.elements;
  14050. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14051. // most likely identical top and bottom frustum extents.
  14052. // Use the left camera for these values.
  14053. const near = projL[14] / (projL[10] - 1);
  14054. const far = projL[14] / (projL[10] + 1);
  14055. const topFov = (projL[9] + 1) / projL[5];
  14056. const bottomFov = (projL[9] - 1) / projL[5];
  14057. const leftFov = (projL[8] - 1) / projL[0];
  14058. const rightFov = (projR[8] + 1) / projR[0];
  14059. const left = near * leftFov;
  14060. const right = near * rightFov; // Calculate the new camera's position offset from the
  14061. // left camera. xOffset should be roughly half `ipd`.
  14062. const zOffset = ipd / (-leftFov + rightFov);
  14063. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14064. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14065. camera.translateX(xOffset);
  14066. camera.translateZ(zOffset);
  14067. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14068. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14069. // the values so that the near plane's position does not change in world space,
  14070. // although must now be relative to the new union camera.
  14071. const near2 = near + zOffset;
  14072. const far2 = far + zOffset;
  14073. const left2 = left - xOffset;
  14074. const right2 = right + (ipd - xOffset);
  14075. const top2 = topFov * far / far2 * near2;
  14076. const bottom2 = bottomFov * far / far2 * near2;
  14077. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14078. }
  14079. function updateCamera(camera, parent) {
  14080. if (parent === null) {
  14081. camera.matrixWorld.copy(camera.matrix);
  14082. } else {
  14083. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14084. }
  14085. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14086. }
  14087. this.getCamera = function (camera) {
  14088. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14089. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14090. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14091. // Note that the new renderState won't apply until the next frame. See #18320
  14092. session.updateRenderState({
  14093. depthNear: cameraVR.near,
  14094. depthFar: cameraVR.far
  14095. });
  14096. _currentDepthNear = cameraVR.near;
  14097. _currentDepthFar = cameraVR.far;
  14098. }
  14099. const parent = camera.parent;
  14100. const cameras = cameraVR.cameras;
  14101. updateCamera(cameraVR, parent);
  14102. for (let i = 0; i < cameras.length; i++) {
  14103. updateCamera(cameras[i], parent);
  14104. } // update camera and its children
  14105. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14106. const children = camera.children;
  14107. for (let i = 0, l = children.length; i < l; i++) {
  14108. children[i].updateMatrixWorld(true);
  14109. } // update projection matrix for proper view frustum culling
  14110. if (cameras.length === 2) {
  14111. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14112. } else {
  14113. // assume single camera setup (AR)
  14114. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14115. }
  14116. return cameraVR;
  14117. }; // Animation Loop
  14118. let onAnimationFrameCallback = null;
  14119. function onAnimationFrame(time, frame) {
  14120. pose = frame.getViewerPose(referenceSpace);
  14121. if (pose !== null) {
  14122. const views = pose.views;
  14123. const baseLayer = session.renderState.baseLayer;
  14124. renderer.setFramebuffer(baseLayer.framebuffer);
  14125. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14126. if (views.length !== cameraVR.cameras.length) {
  14127. cameraVR.cameras.length = 0;
  14128. cameraVRNeedsUpdate = true;
  14129. }
  14130. for (let i = 0; i < views.length; i++) {
  14131. const view = views[i];
  14132. const viewport = baseLayer.getViewport(view);
  14133. const camera = cameras[i];
  14134. camera.matrix.fromArray(view.transform.matrix);
  14135. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14136. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14137. if (i === 0) {
  14138. cameraVR.matrix.copy(camera.matrix);
  14139. }
  14140. if (cameraVRNeedsUpdate === true) {
  14141. cameraVR.cameras.push(camera);
  14142. }
  14143. }
  14144. } //
  14145. const inputSources = session.inputSources;
  14146. for (let i = 0; i < controllers.length; i++) {
  14147. const controller = controllers[i];
  14148. const inputSource = inputSources[i];
  14149. controller.update(inputSource, frame, referenceSpace);
  14150. }
  14151. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14152. }
  14153. const animation = new WebGLAnimation();
  14154. animation.setAnimationLoop(onAnimationFrame);
  14155. this.setAnimationLoop = function (callback) {
  14156. onAnimationFrameCallback = callback;
  14157. };
  14158. this.dispose = function () {};
  14159. }
  14160. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14161. function WebGLMaterials(properties) {
  14162. function refreshFogUniforms(uniforms, fog) {
  14163. uniforms.fogColor.value.copy(fog.color);
  14164. if (fog.isFog) {
  14165. uniforms.fogNear.value = fog.near;
  14166. uniforms.fogFar.value = fog.far;
  14167. } else if (fog.isFogExp2) {
  14168. uniforms.fogDensity.value = fog.density;
  14169. }
  14170. }
  14171. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  14172. if (material.isMeshBasicMaterial) {
  14173. refreshUniformsCommon(uniforms, material);
  14174. } else if (material.isMeshLambertMaterial) {
  14175. refreshUniformsCommon(uniforms, material);
  14176. refreshUniformsLambert(uniforms, material);
  14177. } else if (material.isMeshToonMaterial) {
  14178. refreshUniformsCommon(uniforms, material);
  14179. refreshUniformsToon(uniforms, material);
  14180. } else if (material.isMeshPhongMaterial) {
  14181. refreshUniformsCommon(uniforms, material);
  14182. refreshUniformsPhong(uniforms, material);
  14183. } else if (material.isMeshStandardMaterial) {
  14184. refreshUniformsCommon(uniforms, material);
  14185. if (material.isMeshPhysicalMaterial) {
  14186. refreshUniformsPhysical(uniforms, material);
  14187. } else {
  14188. refreshUniformsStandard(uniforms, material);
  14189. }
  14190. } else if (material.isMeshMatcapMaterial) {
  14191. refreshUniformsCommon(uniforms, material);
  14192. refreshUniformsMatcap(uniforms, material);
  14193. } else if (material.isMeshDepthMaterial) {
  14194. refreshUniformsCommon(uniforms, material);
  14195. refreshUniformsDepth(uniforms, material);
  14196. } else if (material.isMeshDistanceMaterial) {
  14197. refreshUniformsCommon(uniforms, material);
  14198. refreshUniformsDistance(uniforms, material);
  14199. } else if (material.isMeshNormalMaterial) {
  14200. refreshUniformsCommon(uniforms, material);
  14201. refreshUniformsNormal(uniforms, material);
  14202. } else if (material.isLineBasicMaterial) {
  14203. refreshUniformsLine(uniforms, material);
  14204. if (material.isLineDashedMaterial) {
  14205. refreshUniformsDash(uniforms, material);
  14206. }
  14207. } else if (material.isPointsMaterial) {
  14208. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14209. } else if (material.isSpriteMaterial) {
  14210. refreshUniformsSprites(uniforms, material);
  14211. } else if (material.isShadowMaterial) {
  14212. uniforms.color.value.copy(material.color);
  14213. uniforms.opacity.value = material.opacity;
  14214. } else if (material.isShaderMaterial) {
  14215. material.uniformsNeedUpdate = false; // #15581
  14216. }
  14217. }
  14218. function refreshUniformsCommon(uniforms, material) {
  14219. uniforms.opacity.value = material.opacity;
  14220. if (material.color) {
  14221. uniforms.diffuse.value.copy(material.color);
  14222. }
  14223. if (material.emissive) {
  14224. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14225. }
  14226. if (material.map) {
  14227. uniforms.map.value = material.map;
  14228. }
  14229. if (material.alphaMap) {
  14230. uniforms.alphaMap.value = material.alphaMap;
  14231. }
  14232. if (material.specularMap) {
  14233. uniforms.specularMap.value = material.specularMap;
  14234. }
  14235. const envMap = properties.get(material).envMap;
  14236. if (envMap) {
  14237. uniforms.envMap.value = envMap;
  14238. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  14239. uniforms.reflectivity.value = material.reflectivity;
  14240. uniforms.refractionRatio.value = material.refractionRatio;
  14241. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14242. if (maxMipLevel !== undefined) {
  14243. uniforms.maxMipLevel.value = maxMipLevel;
  14244. }
  14245. }
  14246. if (material.lightMap) {
  14247. uniforms.lightMap.value = material.lightMap;
  14248. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14249. }
  14250. if (material.aoMap) {
  14251. uniforms.aoMap.value = material.aoMap;
  14252. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14253. } // uv repeat and offset setting priorities
  14254. // 1. color map
  14255. // 2. specular map
  14256. // 3. displacementMap map
  14257. // 4. normal map
  14258. // 5. bump map
  14259. // 6. roughnessMap map
  14260. // 7. metalnessMap map
  14261. // 8. alphaMap map
  14262. // 9. emissiveMap map
  14263. // 10. clearcoat map
  14264. // 11. clearcoat normal map
  14265. // 12. clearcoat roughnessMap map
  14266. let uvScaleMap;
  14267. if (material.map) {
  14268. uvScaleMap = material.map;
  14269. } else if (material.specularMap) {
  14270. uvScaleMap = material.specularMap;
  14271. } else if (material.displacementMap) {
  14272. uvScaleMap = material.displacementMap;
  14273. } else if (material.normalMap) {
  14274. uvScaleMap = material.normalMap;
  14275. } else if (material.bumpMap) {
  14276. uvScaleMap = material.bumpMap;
  14277. } else if (material.roughnessMap) {
  14278. uvScaleMap = material.roughnessMap;
  14279. } else if (material.metalnessMap) {
  14280. uvScaleMap = material.metalnessMap;
  14281. } else if (material.alphaMap) {
  14282. uvScaleMap = material.alphaMap;
  14283. } else if (material.emissiveMap) {
  14284. uvScaleMap = material.emissiveMap;
  14285. } else if (material.clearcoatMap) {
  14286. uvScaleMap = material.clearcoatMap;
  14287. } else if (material.clearcoatNormalMap) {
  14288. uvScaleMap = material.clearcoatNormalMap;
  14289. } else if (material.clearcoatRoughnessMap) {
  14290. uvScaleMap = material.clearcoatRoughnessMap;
  14291. }
  14292. if (uvScaleMap !== undefined) {
  14293. // backwards compatibility
  14294. if (uvScaleMap.isWebGLRenderTarget) {
  14295. uvScaleMap = uvScaleMap.texture;
  14296. }
  14297. if (uvScaleMap.matrixAutoUpdate === true) {
  14298. uvScaleMap.updateMatrix();
  14299. }
  14300. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14301. } // uv repeat and offset setting priorities for uv2
  14302. // 1. ao map
  14303. // 2. light map
  14304. let uv2ScaleMap;
  14305. if (material.aoMap) {
  14306. uv2ScaleMap = material.aoMap;
  14307. } else if (material.lightMap) {
  14308. uv2ScaleMap = material.lightMap;
  14309. }
  14310. if (uv2ScaleMap !== undefined) {
  14311. // backwards compatibility
  14312. if (uv2ScaleMap.isWebGLRenderTarget) {
  14313. uv2ScaleMap = uv2ScaleMap.texture;
  14314. }
  14315. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14316. uv2ScaleMap.updateMatrix();
  14317. }
  14318. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14319. }
  14320. }
  14321. function refreshUniformsLine(uniforms, material) {
  14322. uniforms.diffuse.value.copy(material.color);
  14323. uniforms.opacity.value = material.opacity;
  14324. }
  14325. function refreshUniformsDash(uniforms, material) {
  14326. uniforms.dashSize.value = material.dashSize;
  14327. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14328. uniforms.scale.value = material.scale;
  14329. }
  14330. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14331. uniforms.diffuse.value.copy(material.color);
  14332. uniforms.opacity.value = material.opacity;
  14333. uniforms.size.value = material.size * pixelRatio;
  14334. uniforms.scale.value = height * 0.5;
  14335. if (material.map) {
  14336. uniforms.map.value = material.map;
  14337. }
  14338. if (material.alphaMap) {
  14339. uniforms.alphaMap.value = material.alphaMap;
  14340. } // uv repeat and offset setting priorities
  14341. // 1. color map
  14342. // 2. alpha map
  14343. let uvScaleMap;
  14344. if (material.map) {
  14345. uvScaleMap = material.map;
  14346. } else if (material.alphaMap) {
  14347. uvScaleMap = material.alphaMap;
  14348. }
  14349. if (uvScaleMap !== undefined) {
  14350. if (uvScaleMap.matrixAutoUpdate === true) {
  14351. uvScaleMap.updateMatrix();
  14352. }
  14353. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14354. }
  14355. }
  14356. function refreshUniformsSprites(uniforms, material) {
  14357. uniforms.diffuse.value.copy(material.color);
  14358. uniforms.opacity.value = material.opacity;
  14359. uniforms.rotation.value = material.rotation;
  14360. if (material.map) {
  14361. uniforms.map.value = material.map;
  14362. }
  14363. if (material.alphaMap) {
  14364. uniforms.alphaMap.value = material.alphaMap;
  14365. } // uv repeat and offset setting priorities
  14366. // 1. color map
  14367. // 2. alpha map
  14368. let uvScaleMap;
  14369. if (material.map) {
  14370. uvScaleMap = material.map;
  14371. } else if (material.alphaMap) {
  14372. uvScaleMap = material.alphaMap;
  14373. }
  14374. if (uvScaleMap !== undefined) {
  14375. if (uvScaleMap.matrixAutoUpdate === true) {
  14376. uvScaleMap.updateMatrix();
  14377. }
  14378. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14379. }
  14380. }
  14381. function refreshUniformsLambert(uniforms, material) {
  14382. if (material.emissiveMap) {
  14383. uniforms.emissiveMap.value = material.emissiveMap;
  14384. }
  14385. }
  14386. function refreshUniformsPhong(uniforms, material) {
  14387. uniforms.specular.value.copy(material.specular);
  14388. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14389. if (material.emissiveMap) {
  14390. uniforms.emissiveMap.value = material.emissiveMap;
  14391. }
  14392. if (material.bumpMap) {
  14393. uniforms.bumpMap.value = material.bumpMap;
  14394. uniforms.bumpScale.value = material.bumpScale;
  14395. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14396. }
  14397. if (material.normalMap) {
  14398. uniforms.normalMap.value = material.normalMap;
  14399. uniforms.normalScale.value.copy(material.normalScale);
  14400. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14401. }
  14402. if (material.displacementMap) {
  14403. uniforms.displacementMap.value = material.displacementMap;
  14404. uniforms.displacementScale.value = material.displacementScale;
  14405. uniforms.displacementBias.value = material.displacementBias;
  14406. }
  14407. }
  14408. function refreshUniformsToon(uniforms, material) {
  14409. if (material.gradientMap) {
  14410. uniforms.gradientMap.value = material.gradientMap;
  14411. }
  14412. if (material.emissiveMap) {
  14413. uniforms.emissiveMap.value = material.emissiveMap;
  14414. }
  14415. if (material.bumpMap) {
  14416. uniforms.bumpMap.value = material.bumpMap;
  14417. uniforms.bumpScale.value = material.bumpScale;
  14418. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14419. }
  14420. if (material.normalMap) {
  14421. uniforms.normalMap.value = material.normalMap;
  14422. uniforms.normalScale.value.copy(material.normalScale);
  14423. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14424. }
  14425. if (material.displacementMap) {
  14426. uniforms.displacementMap.value = material.displacementMap;
  14427. uniforms.displacementScale.value = material.displacementScale;
  14428. uniforms.displacementBias.value = material.displacementBias;
  14429. }
  14430. }
  14431. function refreshUniformsStandard(uniforms, material) {
  14432. uniforms.roughness.value = material.roughness;
  14433. uniforms.metalness.value = material.metalness;
  14434. if (material.roughnessMap) {
  14435. uniforms.roughnessMap.value = material.roughnessMap;
  14436. }
  14437. if (material.metalnessMap) {
  14438. uniforms.metalnessMap.value = material.metalnessMap;
  14439. }
  14440. if (material.emissiveMap) {
  14441. uniforms.emissiveMap.value = material.emissiveMap;
  14442. }
  14443. if (material.bumpMap) {
  14444. uniforms.bumpMap.value = material.bumpMap;
  14445. uniforms.bumpScale.value = material.bumpScale;
  14446. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14447. }
  14448. if (material.normalMap) {
  14449. uniforms.normalMap.value = material.normalMap;
  14450. uniforms.normalScale.value.copy(material.normalScale);
  14451. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14452. }
  14453. if (material.displacementMap) {
  14454. uniforms.displacementMap.value = material.displacementMap;
  14455. uniforms.displacementScale.value = material.displacementScale;
  14456. uniforms.displacementBias.value = material.displacementBias;
  14457. }
  14458. const envMap = properties.get(material).envMap;
  14459. if (envMap) {
  14460. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14461. uniforms.envMapIntensity.value = material.envMapIntensity;
  14462. }
  14463. }
  14464. function refreshUniformsPhysical(uniforms, material) {
  14465. refreshUniformsStandard(uniforms, material);
  14466. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14467. uniforms.clearcoat.value = material.clearcoat;
  14468. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14469. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14470. if (material.clearcoatMap) {
  14471. uniforms.clearcoatMap.value = material.clearcoatMap;
  14472. }
  14473. if (material.clearcoatRoughnessMap) {
  14474. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14475. }
  14476. if (material.clearcoatNormalMap) {
  14477. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14478. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14479. if (material.side === BackSide) {
  14480. uniforms.clearcoatNormalScale.value.negate();
  14481. }
  14482. }
  14483. uniforms.transmission.value = material.transmission;
  14484. if (material.transmissionMap) {
  14485. uniforms.transmissionMap.value = material.transmissionMap;
  14486. }
  14487. }
  14488. function refreshUniformsMatcap(uniforms, material) {
  14489. if (material.matcap) {
  14490. uniforms.matcap.value = material.matcap;
  14491. }
  14492. if (material.bumpMap) {
  14493. uniforms.bumpMap.value = material.bumpMap;
  14494. uniforms.bumpScale.value = material.bumpScale;
  14495. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14496. }
  14497. if (material.normalMap) {
  14498. uniforms.normalMap.value = material.normalMap;
  14499. uniforms.normalScale.value.copy(material.normalScale);
  14500. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14501. }
  14502. if (material.displacementMap) {
  14503. uniforms.displacementMap.value = material.displacementMap;
  14504. uniforms.displacementScale.value = material.displacementScale;
  14505. uniforms.displacementBias.value = material.displacementBias;
  14506. }
  14507. }
  14508. function refreshUniformsDepth(uniforms, material) {
  14509. if (material.displacementMap) {
  14510. uniforms.displacementMap.value = material.displacementMap;
  14511. uniforms.displacementScale.value = material.displacementScale;
  14512. uniforms.displacementBias.value = material.displacementBias;
  14513. }
  14514. }
  14515. function refreshUniformsDistance(uniforms, material) {
  14516. if (material.displacementMap) {
  14517. uniforms.displacementMap.value = material.displacementMap;
  14518. uniforms.displacementScale.value = material.displacementScale;
  14519. uniforms.displacementBias.value = material.displacementBias;
  14520. }
  14521. uniforms.referencePosition.value.copy(material.referencePosition);
  14522. uniforms.nearDistance.value = material.nearDistance;
  14523. uniforms.farDistance.value = material.farDistance;
  14524. }
  14525. function refreshUniformsNormal(uniforms, material) {
  14526. if (material.bumpMap) {
  14527. uniforms.bumpMap.value = material.bumpMap;
  14528. uniforms.bumpScale.value = material.bumpScale;
  14529. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14530. }
  14531. if (material.normalMap) {
  14532. uniforms.normalMap.value = material.normalMap;
  14533. uniforms.normalScale.value.copy(material.normalScale);
  14534. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14535. }
  14536. if (material.displacementMap) {
  14537. uniforms.displacementMap.value = material.displacementMap;
  14538. uniforms.displacementScale.value = material.displacementScale;
  14539. uniforms.displacementBias.value = material.displacementBias;
  14540. }
  14541. }
  14542. return {
  14543. refreshFogUniforms: refreshFogUniforms,
  14544. refreshMaterialUniforms: refreshMaterialUniforms
  14545. };
  14546. }
  14547. function createCanvasElement() {
  14548. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14549. canvas.style.display = 'block';
  14550. return canvas;
  14551. }
  14552. function WebGLRenderer(parameters) {
  14553. parameters = parameters || {};
  14554. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14555. _context = parameters.context !== undefined ? parameters.context : null,
  14556. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14557. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14558. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14559. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14560. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14561. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14562. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14563. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14564. let currentRenderList = null;
  14565. let currentRenderState = null; // public properties
  14566. this.domElement = _canvas; // Debug configuration container
  14567. this.debug = {
  14568. /**
  14569. * Enables error checking and reporting when shader programs are being compiled
  14570. * @type {boolean}
  14571. */
  14572. checkShaderErrors: true
  14573. }; // clearing
  14574. this.autoClear = true;
  14575. this.autoClearColor = true;
  14576. this.autoClearDepth = true;
  14577. this.autoClearStencil = true; // scene graph
  14578. this.sortObjects = true; // user-defined clipping
  14579. this.clippingPlanes = [];
  14580. this.localClippingEnabled = false; // physically based shading
  14581. this.gammaFactor = 2.0; // for backwards compatibility
  14582. this.outputEncoding = LinearEncoding; // physical lights
  14583. this.physicallyCorrectLights = false; // tone mapping
  14584. this.toneMapping = NoToneMapping;
  14585. this.toneMappingExposure = 1.0; // morphs
  14586. this.maxMorphTargets = 8;
  14587. this.maxMorphNormals = 4; // internal properties
  14588. const _this = this;
  14589. let _isContextLost = false; // internal state cache
  14590. let _framebuffer = null;
  14591. let _currentActiveCubeFace = 0;
  14592. let _currentActiveMipmapLevel = 0;
  14593. let _currentRenderTarget = null;
  14594. let _currentFramebuffer = null;
  14595. let _currentMaterialId = -1;
  14596. let _currentCamera = null;
  14597. let _currentArrayCamera = null;
  14598. const _currentViewport = new Vector4();
  14599. const _currentScissor = new Vector4();
  14600. let _currentScissorTest = null; //
  14601. let _width = _canvas.width;
  14602. let _height = _canvas.height;
  14603. let _pixelRatio = 1;
  14604. let _opaqueSort = null;
  14605. let _transparentSort = null;
  14606. const _viewport = new Vector4(0, 0, _width, _height);
  14607. const _scissor = new Vector4(0, 0, _width, _height);
  14608. let _scissorTest = false; // frustum
  14609. const _frustum = new Frustum(); // clipping
  14610. let _clippingEnabled = false;
  14611. let _localClippingEnabled = false; // camera matrices cache
  14612. const _projScreenMatrix = new Matrix4();
  14613. const _vector3 = new Vector3();
  14614. const _emptyScene = {
  14615. background: null,
  14616. fog: null,
  14617. environment: null,
  14618. overrideMaterial: null,
  14619. isScene: true
  14620. };
  14621. function getTargetPixelRatio() {
  14622. return _currentRenderTarget === null ? _pixelRatio : 1;
  14623. } // initialize
  14624. let _gl = _context;
  14625. function getContext(contextNames, contextAttributes) {
  14626. for (let i = 0; i < contextNames.length; i++) {
  14627. const contextName = contextNames[i];
  14628. const context = _canvas.getContext(contextName, contextAttributes);
  14629. if (context !== null) return context;
  14630. }
  14631. return null;
  14632. }
  14633. try {
  14634. const contextAttributes = {
  14635. alpha: _alpha,
  14636. depth: _depth,
  14637. stencil: _stencil,
  14638. antialias: _antialias,
  14639. premultipliedAlpha: _premultipliedAlpha,
  14640. preserveDrawingBuffer: _preserveDrawingBuffer,
  14641. powerPreference: _powerPreference,
  14642. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14643. }; // event listeners must be registered before WebGL context is created, see #12753
  14644. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14645. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14646. if (_gl === null) {
  14647. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14648. if (_this.isWebGL1Renderer === true) {
  14649. contextNames.shift();
  14650. }
  14651. _gl = getContext(contextNames, contextAttributes);
  14652. if (_gl === null) {
  14653. if (getContext(contextNames)) {
  14654. throw new Error('Error creating WebGL context with your selected attributes.');
  14655. } else {
  14656. throw new Error('Error creating WebGL context.');
  14657. }
  14658. }
  14659. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14660. if (_gl.getShaderPrecisionFormat === undefined) {
  14661. _gl.getShaderPrecisionFormat = function () {
  14662. return {
  14663. 'rangeMin': 1,
  14664. 'rangeMax': 1,
  14665. 'precision': 1
  14666. };
  14667. };
  14668. }
  14669. } catch (error) {
  14670. console.error('THREE.WebGLRenderer: ' + error.message);
  14671. throw error;
  14672. }
  14673. let extensions, capabilities, state, info;
  14674. let properties, textures, cubemaps, attributes, geometries, objects;
  14675. let programCache, materials, renderLists, renderStates, clipping;
  14676. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14677. let utils, bindingStates;
  14678. function initGLContext() {
  14679. extensions = new WebGLExtensions(_gl);
  14680. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14681. if (capabilities.isWebGL2 === false) {
  14682. extensions.get('WEBGL_depth_texture');
  14683. extensions.get('OES_texture_float');
  14684. extensions.get('OES_texture_half_float');
  14685. extensions.get('OES_texture_half_float_linear');
  14686. extensions.get('OES_standard_derivatives');
  14687. extensions.get('OES_element_index_uint');
  14688. extensions.get('OES_vertex_array_object');
  14689. extensions.get('ANGLE_instanced_arrays');
  14690. }
  14691. extensions.get('OES_texture_float_linear');
  14692. utils = new WebGLUtils(_gl, extensions, capabilities);
  14693. state = new WebGLState(_gl, extensions, capabilities);
  14694. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14695. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14696. info = new WebGLInfo(_gl);
  14697. properties = new WebGLProperties();
  14698. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14699. cubemaps = new WebGLCubeMaps(_this);
  14700. attributes = new WebGLAttributes(_gl, capabilities);
  14701. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14702. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14703. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14704. morphtargets = new WebGLMorphtargets(_gl);
  14705. clipping = new WebGLClipping(properties);
  14706. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14707. materials = new WebGLMaterials(properties);
  14708. renderLists = new WebGLRenderLists(properties);
  14709. renderStates = new WebGLRenderStates(extensions, capabilities);
  14710. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14711. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14712. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14713. info.programs = programCache.programs;
  14714. _this.capabilities = capabilities;
  14715. _this.extensions = extensions;
  14716. _this.properties = properties;
  14717. _this.renderLists = renderLists;
  14718. _this.state = state;
  14719. _this.info = info;
  14720. }
  14721. initGLContext(); // xr
  14722. const xr = new WebXRManager(_this, _gl);
  14723. this.xr = xr; // shadow map
  14724. const shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14725. this.shadowMap = shadowMap; // API
  14726. this.getContext = function () {
  14727. return _gl;
  14728. };
  14729. this.getContextAttributes = function () {
  14730. return _gl.getContextAttributes();
  14731. };
  14732. this.forceContextLoss = function () {
  14733. const extension = extensions.get('WEBGL_lose_context');
  14734. if (extension) extension.loseContext();
  14735. };
  14736. this.forceContextRestore = function () {
  14737. const extension = extensions.get('WEBGL_lose_context');
  14738. if (extension) extension.restoreContext();
  14739. };
  14740. this.getPixelRatio = function () {
  14741. return _pixelRatio;
  14742. };
  14743. this.setPixelRatio = function (value) {
  14744. if (value === undefined) return;
  14745. _pixelRatio = value;
  14746. this.setSize(_width, _height, false);
  14747. };
  14748. this.getSize = function (target) {
  14749. if (target === undefined) {
  14750. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14751. target = new Vector2();
  14752. }
  14753. return target.set(_width, _height);
  14754. };
  14755. this.setSize = function (width, height, updateStyle) {
  14756. if (xr.isPresenting) {
  14757. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14758. return;
  14759. }
  14760. _width = width;
  14761. _height = height;
  14762. _canvas.width = Math.floor(width * _pixelRatio);
  14763. _canvas.height = Math.floor(height * _pixelRatio);
  14764. if (updateStyle !== false) {
  14765. _canvas.style.width = width + 'px';
  14766. _canvas.style.height = height + 'px';
  14767. }
  14768. this.setViewport(0, 0, width, height);
  14769. };
  14770. this.getDrawingBufferSize = function (target) {
  14771. if (target === undefined) {
  14772. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14773. target = new Vector2();
  14774. }
  14775. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14776. };
  14777. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14778. _width = width;
  14779. _height = height;
  14780. _pixelRatio = pixelRatio;
  14781. _canvas.width = Math.floor(width * pixelRatio);
  14782. _canvas.height = Math.floor(height * pixelRatio);
  14783. this.setViewport(0, 0, width, height);
  14784. };
  14785. this.getCurrentViewport = function (target) {
  14786. if (target === undefined) {
  14787. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14788. target = new Vector4();
  14789. }
  14790. return target.copy(_currentViewport);
  14791. };
  14792. this.getViewport = function (target) {
  14793. return target.copy(_viewport);
  14794. };
  14795. this.setViewport = function (x, y, width, height) {
  14796. if (x.isVector4) {
  14797. _viewport.set(x.x, x.y, x.z, x.w);
  14798. } else {
  14799. _viewport.set(x, y, width, height);
  14800. }
  14801. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14802. };
  14803. this.getScissor = function (target) {
  14804. return target.copy(_scissor);
  14805. };
  14806. this.setScissor = function (x, y, width, height) {
  14807. if (x.isVector4) {
  14808. _scissor.set(x.x, x.y, x.z, x.w);
  14809. } else {
  14810. _scissor.set(x, y, width, height);
  14811. }
  14812. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14813. };
  14814. this.getScissorTest = function () {
  14815. return _scissorTest;
  14816. };
  14817. this.setScissorTest = function (boolean) {
  14818. state.setScissorTest(_scissorTest = boolean);
  14819. };
  14820. this.setOpaqueSort = function (method) {
  14821. _opaqueSort = method;
  14822. };
  14823. this.setTransparentSort = function (method) {
  14824. _transparentSort = method;
  14825. }; // Clearing
  14826. this.getClearColor = function () {
  14827. return background.getClearColor();
  14828. };
  14829. this.setClearColor = function () {
  14830. background.setClearColor.apply(background, arguments);
  14831. };
  14832. this.getClearAlpha = function () {
  14833. return background.getClearAlpha();
  14834. };
  14835. this.setClearAlpha = function () {
  14836. background.setClearAlpha.apply(background, arguments);
  14837. };
  14838. this.clear = function (color, depth, stencil) {
  14839. let bits = 0;
  14840. if (color === undefined || color) bits |= 16384;
  14841. if (depth === undefined || depth) bits |= 256;
  14842. if (stencil === undefined || stencil) bits |= 1024;
  14843. _gl.clear(bits);
  14844. };
  14845. this.clearColor = function () {
  14846. this.clear(true, false, false);
  14847. };
  14848. this.clearDepth = function () {
  14849. this.clear(false, true, false);
  14850. };
  14851. this.clearStencil = function () {
  14852. this.clear(false, false, true);
  14853. }; //
  14854. this.dispose = function () {
  14855. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14856. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14857. renderLists.dispose();
  14858. renderStates.dispose();
  14859. properties.dispose();
  14860. cubemaps.dispose();
  14861. objects.dispose();
  14862. bindingStates.dispose();
  14863. xr.dispose();
  14864. animation.stop();
  14865. }; // Events
  14866. function onContextLost(event) {
  14867. event.preventDefault();
  14868. console.log('THREE.WebGLRenderer: Context Lost.');
  14869. _isContextLost = true;
  14870. }
  14871. function onContextRestore()
  14872. /* event */
  14873. {
  14874. console.log('THREE.WebGLRenderer: Context Restored.');
  14875. _isContextLost = false;
  14876. initGLContext();
  14877. }
  14878. function onMaterialDispose(event) {
  14879. const material = event.target;
  14880. material.removeEventListener('dispose', onMaterialDispose);
  14881. deallocateMaterial(material);
  14882. } // Buffer deallocation
  14883. function deallocateMaterial(material) {
  14884. releaseMaterialProgramReference(material);
  14885. properties.remove(material);
  14886. }
  14887. function releaseMaterialProgramReference(material) {
  14888. const programInfo = properties.get(material).program;
  14889. if (programInfo !== undefined) {
  14890. programCache.releaseProgram(programInfo);
  14891. }
  14892. } // Buffer rendering
  14893. function renderObjectImmediate(object, program) {
  14894. object.render(function (object) {
  14895. _this.renderBufferImmediate(object, program);
  14896. });
  14897. }
  14898. this.renderBufferImmediate = function (object, program) {
  14899. bindingStates.initAttributes();
  14900. const buffers = properties.get(object);
  14901. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14902. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14903. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14904. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14905. const programAttributes = program.getAttributes();
  14906. if (object.hasPositions) {
  14907. _gl.bindBuffer(34962, buffers.position);
  14908. _gl.bufferData(34962, object.positionArray, 35048);
  14909. bindingStates.enableAttribute(programAttributes.position);
  14910. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14911. }
  14912. if (object.hasNormals) {
  14913. _gl.bindBuffer(34962, buffers.normal);
  14914. _gl.bufferData(34962, object.normalArray, 35048);
  14915. bindingStates.enableAttribute(programAttributes.normal);
  14916. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14917. }
  14918. if (object.hasUvs) {
  14919. _gl.bindBuffer(34962, buffers.uv);
  14920. _gl.bufferData(34962, object.uvArray, 35048);
  14921. bindingStates.enableAttribute(programAttributes.uv);
  14922. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14923. }
  14924. if (object.hasColors) {
  14925. _gl.bindBuffer(34962, buffers.color);
  14926. _gl.bufferData(34962, object.colorArray, 35048);
  14927. bindingStates.enableAttribute(programAttributes.color);
  14928. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14929. }
  14930. bindingStates.disableUnusedAttributes();
  14931. _gl.drawArrays(4, 0, object.count);
  14932. object.count = 0;
  14933. };
  14934. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14935. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14936. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14937. const program = setProgram(camera, scene, material, object);
  14938. state.setMaterial(material, frontFaceCW); //
  14939. let index = geometry.index;
  14940. const position = geometry.attributes.position; //
  14941. if (index === null) {
  14942. if (position === undefined || position.count === 0) return;
  14943. } else if (index.count === 0) {
  14944. return;
  14945. } //
  14946. let rangeFactor = 1;
  14947. if (material.wireframe === true) {
  14948. index = geometries.getWireframeAttribute(geometry);
  14949. rangeFactor = 2;
  14950. }
  14951. if (material.morphTargets || material.morphNormals) {
  14952. morphtargets.update(object, geometry, material, program);
  14953. }
  14954. bindingStates.setup(object, material, program, geometry, index);
  14955. let attribute;
  14956. let renderer = bufferRenderer;
  14957. if (index !== null) {
  14958. attribute = attributes.get(index);
  14959. renderer = indexedBufferRenderer;
  14960. renderer.setIndex(attribute);
  14961. } //
  14962. const dataCount = index !== null ? index.count : position.count;
  14963. const rangeStart = geometry.drawRange.start * rangeFactor;
  14964. const rangeCount = geometry.drawRange.count * rangeFactor;
  14965. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14966. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14967. const drawStart = Math.max(rangeStart, groupStart);
  14968. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14969. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14970. if (drawCount === 0) return; //
  14971. if (object.isMesh) {
  14972. if (material.wireframe === true) {
  14973. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14974. renderer.setMode(1);
  14975. } else {
  14976. renderer.setMode(4);
  14977. }
  14978. } else if (object.isLine) {
  14979. let lineWidth = material.linewidth;
  14980. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14981. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14982. if (object.isLineSegments) {
  14983. renderer.setMode(1);
  14984. } else if (object.isLineLoop) {
  14985. renderer.setMode(2);
  14986. } else {
  14987. renderer.setMode(3);
  14988. }
  14989. } else if (object.isPoints) {
  14990. renderer.setMode(0);
  14991. } else if (object.isSprite) {
  14992. renderer.setMode(4);
  14993. }
  14994. if (object.isInstancedMesh) {
  14995. renderer.renderInstances(drawStart, drawCount, object.count);
  14996. } else if (geometry.isInstancedBufferGeometry) {
  14997. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14998. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14999. } else {
  15000. renderer.render(drawStart, drawCount);
  15001. }
  15002. }; // Compile
  15003. this.compile = function (scene, camera) {
  15004. currentRenderState = renderStates.get(scene, camera);
  15005. currentRenderState.init();
  15006. scene.traverseVisible(function (object) {
  15007. if (object.isLight && object.layers.test(camera.layers)) {
  15008. currentRenderState.pushLight(object);
  15009. if (object.castShadow) {
  15010. currentRenderState.pushShadow(object);
  15011. }
  15012. }
  15013. });
  15014. currentRenderState.setupLights(camera);
  15015. const compiled = new WeakMap();
  15016. scene.traverse(function (object) {
  15017. const material = object.material;
  15018. if (material) {
  15019. if (Array.isArray(material)) {
  15020. for (let i = 0; i < material.length; i++) {
  15021. const material2 = material[i];
  15022. if (compiled.has(material2) === false) {
  15023. initMaterial(material2, scene, object);
  15024. compiled.set(material2);
  15025. }
  15026. }
  15027. } else if (compiled.has(material) === false) {
  15028. initMaterial(material, scene, object);
  15029. compiled.set(material);
  15030. }
  15031. }
  15032. });
  15033. }; // Animation Loop
  15034. let onAnimationFrameCallback = null;
  15035. function onAnimationFrame(time) {
  15036. if (xr.isPresenting) return;
  15037. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15038. }
  15039. const animation = new WebGLAnimation();
  15040. animation.setAnimationLoop(onAnimationFrame);
  15041. if (typeof window !== 'undefined') animation.setContext(window);
  15042. this.setAnimationLoop = function (callback) {
  15043. onAnimationFrameCallback = callback;
  15044. xr.setAnimationLoop(callback);
  15045. callback === null ? animation.stop() : animation.start();
  15046. }; // Rendering
  15047. this.render = function (scene, camera) {
  15048. let renderTarget, forceClear;
  15049. if (arguments[2] !== undefined) {
  15050. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15051. renderTarget = arguments[2];
  15052. }
  15053. if (arguments[3] !== undefined) {
  15054. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15055. forceClear = arguments[3];
  15056. }
  15057. if (camera !== undefined && camera.isCamera !== true) {
  15058. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15059. return;
  15060. }
  15061. if (_isContextLost === true) return; // reset caching for this frame
  15062. bindingStates.resetDefaultState();
  15063. _currentMaterialId = -1;
  15064. _currentCamera = null; // update scene graph
  15065. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15066. if (camera.parent === null) camera.updateMatrixWorld();
  15067. if (xr.enabled === true && xr.isPresenting === true) {
  15068. camera = xr.getCamera(camera);
  15069. } //
  15070. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15071. currentRenderState = renderStates.get(scene, camera);
  15072. currentRenderState.init();
  15073. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15074. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15075. _localClippingEnabled = this.localClippingEnabled;
  15076. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15077. currentRenderList = renderLists.get(scene, camera);
  15078. currentRenderList.init();
  15079. projectObject(scene, camera, 0, _this.sortObjects);
  15080. currentRenderList.finish();
  15081. if (_this.sortObjects === true) {
  15082. currentRenderList.sort(_opaqueSort, _transparentSort);
  15083. } //
  15084. if (_clippingEnabled === true) clipping.beginShadows();
  15085. const shadowsArray = currentRenderState.state.shadowsArray;
  15086. shadowMap.render(shadowsArray, scene, camera);
  15087. currentRenderState.setupLights(camera);
  15088. if (_clippingEnabled === true) clipping.endShadows(); //
  15089. if (this.info.autoReset === true) this.info.reset();
  15090. if (renderTarget !== undefined) {
  15091. this.setRenderTarget(renderTarget);
  15092. } //
  15093. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15094. const opaqueObjects = currentRenderList.opaque;
  15095. const transparentObjects = currentRenderList.transparent;
  15096. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15097. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  15098. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
  15099. if (_currentRenderTarget !== null) {
  15100. // Generate mipmap if we're using any kind of mipmap filtering
  15101. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15102. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15103. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15104. state.buffers.depth.setTest(true);
  15105. state.buffers.depth.setMask(true);
  15106. state.buffers.color.setMask(true);
  15107. state.setPolygonOffset(false); // _gl.finish();
  15108. currentRenderList = null;
  15109. currentRenderState = null;
  15110. };
  15111. function projectObject(object, camera, groupOrder, sortObjects) {
  15112. if (object.visible === false) return;
  15113. const visible = object.layers.test(camera.layers);
  15114. if (visible) {
  15115. if (object.isGroup) {
  15116. groupOrder = object.renderOrder;
  15117. } else if (object.isLOD) {
  15118. if (object.autoUpdate === true) object.update(camera);
  15119. } else if (object.isLight) {
  15120. currentRenderState.pushLight(object);
  15121. if (object.castShadow) {
  15122. currentRenderState.pushShadow(object);
  15123. }
  15124. } else if (object.isSprite) {
  15125. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15126. if (sortObjects) {
  15127. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15128. }
  15129. const geometry = objects.update(object);
  15130. const material = object.material;
  15131. if (material.visible) {
  15132. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15133. }
  15134. }
  15135. } else if (object.isImmediateRenderObject) {
  15136. if (sortObjects) {
  15137. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15138. }
  15139. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15140. } else if (object.isMesh || object.isLine || object.isPoints) {
  15141. if (object.isSkinnedMesh) {
  15142. // update skeleton only once in a frame
  15143. if (object.skeleton.frame !== info.render.frame) {
  15144. object.skeleton.update();
  15145. object.skeleton.frame = info.render.frame;
  15146. }
  15147. }
  15148. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15149. if (sortObjects) {
  15150. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15151. }
  15152. const geometry = objects.update(object);
  15153. const material = object.material;
  15154. if (Array.isArray(material)) {
  15155. const groups = geometry.groups;
  15156. for (let i = 0, l = groups.length; i < l; i++) {
  15157. const group = groups[i];
  15158. const groupMaterial = material[group.materialIndex];
  15159. if (groupMaterial && groupMaterial.visible) {
  15160. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15161. }
  15162. }
  15163. } else if (material.visible) {
  15164. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15165. }
  15166. }
  15167. }
  15168. }
  15169. const children = object.children;
  15170. for (let i = 0, l = children.length; i < l; i++) {
  15171. projectObject(children[i], camera, groupOrder, sortObjects);
  15172. }
  15173. }
  15174. function renderObjects(renderList, scene, camera) {
  15175. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15176. for (let i = 0, l = renderList.length; i < l; i++) {
  15177. const renderItem = renderList[i];
  15178. const object = renderItem.object;
  15179. const geometry = renderItem.geometry;
  15180. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15181. const group = renderItem.group;
  15182. if (camera.isArrayCamera) {
  15183. _currentArrayCamera = camera;
  15184. const cameras = camera.cameras;
  15185. for (let j = 0, jl = cameras.length; j < jl; j++) {
  15186. const camera2 = cameras[j];
  15187. if (object.layers.test(camera2.layers)) {
  15188. state.viewport(_currentViewport.copy(camera2.viewport));
  15189. currentRenderState.setupLights(camera2);
  15190. renderObject(object, scene, camera2, geometry, material, group);
  15191. }
  15192. }
  15193. } else {
  15194. _currentArrayCamera = null;
  15195. renderObject(object, scene, camera, geometry, material, group);
  15196. }
  15197. }
  15198. }
  15199. function renderObject(object, scene, camera, geometry, material, group) {
  15200. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15201. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15202. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15203. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15204. if (object.isImmediateRenderObject) {
  15205. const program = setProgram(camera, scene, material, object);
  15206. state.setMaterial(material);
  15207. bindingStates.reset();
  15208. renderObjectImmediate(object, program);
  15209. } else {
  15210. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15211. }
  15212. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15213. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15214. }
  15215. function initMaterial(material, scene, object) {
  15216. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15217. const materialProperties = properties.get(material);
  15218. const lights = currentRenderState.state.lights;
  15219. const shadowsArray = currentRenderState.state.shadowsArray;
  15220. const lightsStateVersion = lights.state.version;
  15221. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15222. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15223. let program = materialProperties.program;
  15224. let programChange = true;
  15225. if (program === undefined) {
  15226. // new material
  15227. material.addEventListener('dispose', onMaterialDispose);
  15228. } else if (program.cacheKey !== programCacheKey) {
  15229. // changed glsl or parameters
  15230. releaseMaterialProgramReference(material);
  15231. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15232. programChange = false;
  15233. } else if (parameters.shaderID !== undefined) {
  15234. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15235. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15236. materialProperties.envMap = cubemaps.get(material.envMap || environment);
  15237. return;
  15238. } else {
  15239. // only rebuild uniform list
  15240. programChange = false;
  15241. }
  15242. if (programChange) {
  15243. parameters.uniforms = programCache.getUniforms(material);
  15244. material.onBeforeCompile(parameters, _this);
  15245. program = programCache.acquireProgram(parameters, programCacheKey);
  15246. materialProperties.program = program;
  15247. materialProperties.uniforms = parameters.uniforms;
  15248. materialProperties.outputEncoding = parameters.outputEncoding;
  15249. }
  15250. const uniforms = materialProperties.uniforms;
  15251. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15252. materialProperties.numClippingPlanes = clipping.numPlanes;
  15253. materialProperties.numIntersection = clipping.numIntersection;
  15254. uniforms.clippingPlanes = clipping.uniform;
  15255. }
  15256. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15257. materialProperties.fog = scene.fog;
  15258. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment); // store the light setup it was created for
  15259. materialProperties.needsLights = materialNeedsLights(material);
  15260. materialProperties.lightsStateVersion = lightsStateVersion;
  15261. if (materialProperties.needsLights) {
  15262. // wire up the material to this renderer's lighting state
  15263. uniforms.ambientLightColor.value = lights.state.ambient;
  15264. uniforms.lightProbe.value = lights.state.probe;
  15265. uniforms.directionalLights.value = lights.state.directional;
  15266. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15267. uniforms.spotLights.value = lights.state.spot;
  15268. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15269. uniforms.rectAreaLights.value = lights.state.rectArea;
  15270. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15271. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15272. uniforms.pointLights.value = lights.state.point;
  15273. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15274. uniforms.hemisphereLights.value = lights.state.hemi;
  15275. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15276. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15277. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15278. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15279. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15280. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15281. }
  15282. const progUniforms = materialProperties.program.getUniforms();
  15283. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15284. materialProperties.uniformsList = uniformsList;
  15285. }
  15286. function setProgram(camera, scene, material, object) {
  15287. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15288. textures.resetTextureUnits();
  15289. const fog = scene.fog;
  15290. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15291. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15292. const envMap = cubemaps.get(material.envMap || environment);
  15293. const materialProperties = properties.get(material);
  15294. const lights = currentRenderState.state.lights;
  15295. if (_clippingEnabled === true) {
  15296. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15297. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15298. // object instead of the material, once it becomes feasible
  15299. // (#8465, #8379)
  15300. clipping.setState(material, camera, useCache);
  15301. }
  15302. }
  15303. if (material.version === materialProperties.__version) {
  15304. if (material.fog && materialProperties.fog !== fog) {
  15305. initMaterial(material, scene, object);
  15306. } else if (materialProperties.environment !== environment) {
  15307. initMaterial(material, scene, object);
  15308. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15309. initMaterial(material, scene, object);
  15310. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  15311. initMaterial(material, scene, object);
  15312. } else if (materialProperties.outputEncoding !== encoding) {
  15313. initMaterial(material, scene, object);
  15314. } else if (materialProperties.envMap !== envMap) {
  15315. initMaterial(material, scene, object);
  15316. }
  15317. } else {
  15318. initMaterial(material, scene, object);
  15319. materialProperties.__version = material.version;
  15320. }
  15321. let refreshProgram = false;
  15322. let refreshMaterial = false;
  15323. let refreshLights = false;
  15324. const program = materialProperties.program,
  15325. p_uniforms = program.getUniforms(),
  15326. m_uniforms = materialProperties.uniforms;
  15327. if (state.useProgram(program.program)) {
  15328. refreshProgram = true;
  15329. refreshMaterial = true;
  15330. refreshLights = true;
  15331. }
  15332. if (material.id !== _currentMaterialId) {
  15333. _currentMaterialId = material.id;
  15334. refreshMaterial = true;
  15335. }
  15336. if (refreshProgram || _currentCamera !== camera) {
  15337. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15338. if (capabilities.logarithmicDepthBuffer) {
  15339. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15340. }
  15341. if (_currentCamera !== camera) {
  15342. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15343. // now, in case this material supports lights - or later, when
  15344. // the next material that does gets activated:
  15345. refreshMaterial = true; // set to true on material change
  15346. refreshLights = true; // remains set until update done
  15347. } // load material specific uniforms
  15348. // (shader material also gets them for the sake of genericity)
  15349. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15350. const uCamPos = p_uniforms.map.cameraPosition;
  15351. if (uCamPos !== undefined) {
  15352. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15353. }
  15354. }
  15355. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15356. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15357. }
  15358. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  15359. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15360. }
  15361. } // skinning uniforms must be set even if material didn't change
  15362. // auto-setting of texture unit for bone texture must go before other textures
  15363. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15364. if (material.skinning) {
  15365. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15366. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15367. const skeleton = object.skeleton;
  15368. if (skeleton) {
  15369. const bones = skeleton.bones;
  15370. if (capabilities.floatVertexTextures) {
  15371. if (skeleton.boneTexture === null) {
  15372. // layout (1 matrix = 4 pixels)
  15373. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15374. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15375. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15376. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15377. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15378. let size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15379. size = MathUtils.ceilPowerOfTwo(size);
  15380. size = Math.max(size, 4);
  15381. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15382. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15383. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15384. skeleton.boneMatrices = boneMatrices;
  15385. skeleton.boneTexture = boneTexture;
  15386. skeleton.boneTextureSize = size;
  15387. }
  15388. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15389. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15390. } else {
  15391. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15392. }
  15393. }
  15394. }
  15395. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15396. materialProperties.receiveShadow = object.receiveShadow;
  15397. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15398. }
  15399. if (refreshMaterial) {
  15400. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15401. if (materialProperties.needsLights) {
  15402. // the current material requires lighting info
  15403. // note: all lighting uniforms are always set correctly
  15404. // they simply reference the renderer's state for their
  15405. // values
  15406. //
  15407. // use the current material's .needsUpdate flags to set
  15408. // the GL state when required
  15409. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15410. } // refresh uniforms common to several materials
  15411. if (fog && material.fog) {
  15412. materials.refreshFogUniforms(m_uniforms, fog);
  15413. }
  15414. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  15415. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15416. }
  15417. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15418. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15419. material.uniformsNeedUpdate = false;
  15420. }
  15421. if (material.isSpriteMaterial) {
  15422. p_uniforms.setValue(_gl, 'center', object.center);
  15423. } // common matrices
  15424. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15425. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15426. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15427. return program;
  15428. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15429. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15430. uniforms.ambientLightColor.needsUpdate = value;
  15431. uniforms.lightProbe.needsUpdate = value;
  15432. uniforms.directionalLights.needsUpdate = value;
  15433. uniforms.directionalLightShadows.needsUpdate = value;
  15434. uniforms.pointLights.needsUpdate = value;
  15435. uniforms.pointLightShadows.needsUpdate = value;
  15436. uniforms.spotLights.needsUpdate = value;
  15437. uniforms.spotLightShadows.needsUpdate = value;
  15438. uniforms.rectAreaLights.needsUpdate = value;
  15439. uniforms.hemisphereLights.needsUpdate = value;
  15440. }
  15441. function materialNeedsLights(material) {
  15442. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15443. } //
  15444. this.setFramebuffer = function (value) {
  15445. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  15446. _framebuffer = value;
  15447. };
  15448. this.getActiveCubeFace = function () {
  15449. return _currentActiveCubeFace;
  15450. };
  15451. this.getActiveMipmapLevel = function () {
  15452. return _currentActiveMipmapLevel;
  15453. };
  15454. this.getRenderList = function () {
  15455. return currentRenderList;
  15456. };
  15457. this.setRenderList = function (renderList) {
  15458. currentRenderList = renderList;
  15459. };
  15460. this.getRenderState = function () {
  15461. return currentRenderState;
  15462. };
  15463. this.setRenderState = function (renderState) {
  15464. currentRenderState = renderState;
  15465. };
  15466. this.getRenderTarget = function () {
  15467. return _currentRenderTarget;
  15468. };
  15469. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15470. _currentRenderTarget = renderTarget;
  15471. _currentActiveCubeFace = activeCubeFace;
  15472. _currentActiveMipmapLevel = activeMipmapLevel;
  15473. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15474. textures.setupRenderTarget(renderTarget);
  15475. }
  15476. let framebuffer = _framebuffer;
  15477. let isCube = false;
  15478. if (renderTarget) {
  15479. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15480. if (renderTarget.isWebGLCubeRenderTarget) {
  15481. framebuffer = __webglFramebuffer[activeCubeFace];
  15482. isCube = true;
  15483. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15484. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15485. } else {
  15486. framebuffer = __webglFramebuffer;
  15487. }
  15488. _currentViewport.copy(renderTarget.viewport);
  15489. _currentScissor.copy(renderTarget.scissor);
  15490. _currentScissorTest = renderTarget.scissorTest;
  15491. } else {
  15492. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15493. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15494. _currentScissorTest = _scissorTest;
  15495. }
  15496. if (_currentFramebuffer !== framebuffer) {
  15497. _gl.bindFramebuffer(36160, framebuffer);
  15498. _currentFramebuffer = framebuffer;
  15499. }
  15500. state.viewport(_currentViewport);
  15501. state.scissor(_currentScissor);
  15502. state.setScissorTest(_currentScissorTest);
  15503. if (isCube) {
  15504. const textureProperties = properties.get(renderTarget.texture);
  15505. _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15506. }
  15507. };
  15508. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15509. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15510. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15511. return;
  15512. }
  15513. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15514. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15515. framebuffer = framebuffer[activeCubeFaceIndex];
  15516. }
  15517. if (framebuffer) {
  15518. let restore = false;
  15519. if (framebuffer !== _currentFramebuffer) {
  15520. _gl.bindFramebuffer(36160, framebuffer);
  15521. restore = true;
  15522. }
  15523. try {
  15524. const texture = renderTarget.texture;
  15525. const textureFormat = texture.format;
  15526. const textureType = texture.type;
  15527. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  15528. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15529. return;
  15530. }
  15531. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15532. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15533. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  15534. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15535. return;
  15536. }
  15537. if (_gl.checkFramebufferStatus(36160) === 36053) {
  15538. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15539. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15540. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15541. }
  15542. } else {
  15543. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15544. }
  15545. } finally {
  15546. if (restore) {
  15547. _gl.bindFramebuffer(36160, _currentFramebuffer);
  15548. }
  15549. }
  15550. }
  15551. };
  15552. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15553. const levelScale = Math.pow(2, -level);
  15554. const width = Math.floor(texture.image.width * levelScale);
  15555. const height = Math.floor(texture.image.height * levelScale);
  15556. const glFormat = utils.convert(texture.format);
  15557. textures.setTexture2D(texture, 0);
  15558. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  15559. state.unbindTexture();
  15560. };
  15561. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15562. const width = srcTexture.image.width;
  15563. const height = srcTexture.image.height;
  15564. const glFormat = utils.convert(dstTexture.format);
  15565. const glType = utils.convert(dstTexture.type);
  15566. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15567. // parameters, make sure they are correct for the dstTexture
  15568. _gl.pixelStorei(37440, dstTexture.flipY);
  15569. _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
  15570. _gl.pixelStorei(3317, dstTexture.unpackAlignment);
  15571. if (srcTexture.isDataTexture) {
  15572. _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15573. } else {
  15574. if (srcTexture.isCompressedTexture) {
  15575. _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15576. } else {
  15577. _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15578. }
  15579. } // Generate mipmaps only when copying level 0
  15580. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
  15581. state.unbindTexture();
  15582. };
  15583. this.initTexture = function (texture) {
  15584. textures.setTexture2D(texture, 0);
  15585. state.unbindTexture();
  15586. };
  15587. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15588. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15589. detail: this
  15590. })); // eslint-disable-line no-undef
  15591. }
  15592. }
  15593. function WebGL1Renderer(parameters) {
  15594. WebGLRenderer.call(this, parameters);
  15595. }
  15596. WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
  15597. constructor: WebGL1Renderer,
  15598. isWebGL1Renderer: true
  15599. });
  15600. class FogExp2 {
  15601. constructor(color, density) {
  15602. Object.defineProperty(this, 'isFogExp2', {
  15603. value: true
  15604. });
  15605. this.name = '';
  15606. this.color = new Color(color);
  15607. this.density = density !== undefined ? density : 0.00025;
  15608. }
  15609. clone() {
  15610. return new FogExp2(this.color, this.density);
  15611. }
  15612. toJSON()
  15613. /* meta */
  15614. {
  15615. return {
  15616. type: 'FogExp2',
  15617. color: this.color.getHex(),
  15618. density: this.density
  15619. };
  15620. }
  15621. }
  15622. exports.FogExp2 = FogExp2;
  15623. class Fog {
  15624. constructor(color, near, far) {
  15625. Object.defineProperty(this, 'isFog', {
  15626. value: true
  15627. });
  15628. this.name = '';
  15629. this.color = new Color(color);
  15630. this.near = near !== undefined ? near : 1;
  15631. this.far = far !== undefined ? far : 1000;
  15632. }
  15633. clone() {
  15634. return new Fog(this.color, this.near, this.far);
  15635. }
  15636. toJSON()
  15637. /* meta */
  15638. {
  15639. return {
  15640. type: 'Fog',
  15641. color: this.color.getHex(),
  15642. near: this.near,
  15643. far: this.far
  15644. };
  15645. }
  15646. }
  15647. exports.Fog = Fog;
  15648. class Scene extends Object3D {
  15649. constructor() {
  15650. super();
  15651. Object.defineProperty(this, 'isScene', {
  15652. value: true
  15653. });
  15654. this.type = 'Scene';
  15655. this.background = null;
  15656. this.environment = null;
  15657. this.fog = null;
  15658. this.overrideMaterial = null;
  15659. this.autoUpdate = true; // checked by the renderer
  15660. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15661. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15662. detail: this
  15663. })); // eslint-disable-line no-undef
  15664. }
  15665. }
  15666. copy(source, recursive) {
  15667. super.copy(source, recursive);
  15668. if (source.background !== null) this.background = source.background.clone();
  15669. if (source.environment !== null) this.environment = source.environment.clone();
  15670. if (source.fog !== null) this.fog = source.fog.clone();
  15671. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15672. this.autoUpdate = source.autoUpdate;
  15673. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15674. return this;
  15675. }
  15676. toJSON(meta) {
  15677. const data = super.toJSON(meta);
  15678. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15679. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15680. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15681. return data;
  15682. }
  15683. }
  15684. exports.Scene = Scene;
  15685. function InterleavedBuffer(array, stride) {
  15686. this.array = array;
  15687. this.stride = stride;
  15688. this.count = array !== undefined ? array.length / stride : 0;
  15689. this.usage = StaticDrawUsage;
  15690. this.updateRange = {
  15691. offset: 0,
  15692. count: -1
  15693. };
  15694. this.version = 0;
  15695. this.uuid = MathUtils.generateUUID();
  15696. }
  15697. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  15698. set: function (value) {
  15699. if (value === true) this.version++;
  15700. }
  15701. });
  15702. Object.assign(InterleavedBuffer.prototype, {
  15703. isInterleavedBuffer: true,
  15704. onUploadCallback: function () {},
  15705. setUsage: function (value) {
  15706. this.usage = value;
  15707. return this;
  15708. },
  15709. copy: function (source) {
  15710. this.array = new source.array.constructor(source.array);
  15711. this.count = source.count;
  15712. this.stride = source.stride;
  15713. this.usage = source.usage;
  15714. return this;
  15715. },
  15716. copyAt: function (index1, attribute, index2) {
  15717. index1 *= this.stride;
  15718. index2 *= attribute.stride;
  15719. for (let i = 0, l = this.stride; i < l; i++) {
  15720. this.array[index1 + i] = attribute.array[index2 + i];
  15721. }
  15722. return this;
  15723. },
  15724. set: function (value, offset = 0) {
  15725. this.array.set(value, offset);
  15726. return this;
  15727. },
  15728. clone: function (data) {
  15729. if (data.arrayBuffers === undefined) {
  15730. data.arrayBuffers = {};
  15731. }
  15732. if (this.array.buffer._uuid === undefined) {
  15733. this.array.buffer._uuid = MathUtils.generateUUID();
  15734. }
  15735. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15736. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15737. }
  15738. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15739. const ib = new InterleavedBuffer(array, this.stride);
  15740. ib.setUsage(this.usage);
  15741. return ib;
  15742. },
  15743. onUpload: function (callback) {
  15744. this.onUploadCallback = callback;
  15745. return this;
  15746. },
  15747. toJSON: function (data) {
  15748. if (data.arrayBuffers === undefined) {
  15749. data.arrayBuffers = {};
  15750. } // generate UUID for array buffer if necessary
  15751. if (this.array.buffer._uuid === undefined) {
  15752. this.array.buffer._uuid = MathUtils.generateUUID();
  15753. }
  15754. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15755. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15756. } //
  15757. return {
  15758. uuid: this.uuid,
  15759. buffer: this.array.buffer._uuid,
  15760. type: this.array.constructor.name,
  15761. stride: this.stride
  15762. };
  15763. }
  15764. });
  15765. const _vector$6 = new Vector3();
  15766. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  15767. this.name = '';
  15768. this.data = interleavedBuffer;
  15769. this.itemSize = itemSize;
  15770. this.offset = offset;
  15771. this.normalized = normalized === true;
  15772. }
  15773. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  15774. count: {
  15775. get: function () {
  15776. return this.data.count;
  15777. }
  15778. },
  15779. array: {
  15780. get: function () {
  15781. return this.data.array;
  15782. }
  15783. },
  15784. needsUpdate: {
  15785. set: function (value) {
  15786. this.data.needsUpdate = value;
  15787. }
  15788. }
  15789. });
  15790. Object.assign(InterleavedBufferAttribute.prototype, {
  15791. isInterleavedBufferAttribute: true,
  15792. applyMatrix4: function (m) {
  15793. for (let i = 0, l = this.data.count; i < l; i++) {
  15794. _vector$6.x = this.getX(i);
  15795. _vector$6.y = this.getY(i);
  15796. _vector$6.z = this.getZ(i);
  15797. _vector$6.applyMatrix4(m);
  15798. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15799. }
  15800. return this;
  15801. },
  15802. setX: function (index, x) {
  15803. this.data.array[index * this.data.stride + this.offset] = x;
  15804. return this;
  15805. },
  15806. setY: function (index, y) {
  15807. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15808. return this;
  15809. },
  15810. setZ: function (index, z) {
  15811. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15812. return this;
  15813. },
  15814. setW: function (index, w) {
  15815. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15816. return this;
  15817. },
  15818. getX: function (index) {
  15819. return this.data.array[index * this.data.stride + this.offset];
  15820. },
  15821. getY: function (index) {
  15822. return this.data.array[index * this.data.stride + this.offset + 1];
  15823. },
  15824. getZ: function (index) {
  15825. return this.data.array[index * this.data.stride + this.offset + 2];
  15826. },
  15827. getW: function (index) {
  15828. return this.data.array[index * this.data.stride + this.offset + 3];
  15829. },
  15830. setXY: function (index, x, y) {
  15831. index = index * this.data.stride + this.offset;
  15832. this.data.array[index + 0] = x;
  15833. this.data.array[index + 1] = y;
  15834. return this;
  15835. },
  15836. setXYZ: function (index, x, y, z) {
  15837. index = index * this.data.stride + this.offset;
  15838. this.data.array[index + 0] = x;
  15839. this.data.array[index + 1] = y;
  15840. this.data.array[index + 2] = z;
  15841. return this;
  15842. },
  15843. setXYZW: function (index, x, y, z, w) {
  15844. index = index * this.data.stride + this.offset;
  15845. this.data.array[index + 0] = x;
  15846. this.data.array[index + 1] = y;
  15847. this.data.array[index + 2] = z;
  15848. this.data.array[index + 3] = w;
  15849. return this;
  15850. },
  15851. clone: function (data) {
  15852. if (data === undefined) {
  15853. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15854. const array = [];
  15855. for (let i = 0; i < this.count; i++) {
  15856. const index = i * this.data.stride + this.offset;
  15857. for (let j = 0; j < this.itemSize; j++) {
  15858. array.push(this.data.array[index + j]);
  15859. }
  15860. }
  15861. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15862. } else {
  15863. if (data.interleavedBuffers === undefined) {
  15864. data.interleavedBuffers = {};
  15865. }
  15866. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15867. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15868. }
  15869. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15870. }
  15871. },
  15872. toJSON: function (data) {
  15873. if (data === undefined) {
  15874. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15875. const array = [];
  15876. for (let i = 0; i < this.count; i++) {
  15877. const index = i * this.data.stride + this.offset;
  15878. for (let j = 0; j < this.itemSize; j++) {
  15879. array.push(this.data.array[index + j]);
  15880. }
  15881. } // deinterleave data and save it as an ordinary buffer attribute for now
  15882. return {
  15883. itemSize: this.itemSize,
  15884. type: this.array.constructor.name,
  15885. array: array,
  15886. normalized: this.normalized
  15887. };
  15888. } else {
  15889. // save as true interlaved attribtue
  15890. if (data.interleavedBuffers === undefined) {
  15891. data.interleavedBuffers = {};
  15892. }
  15893. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15894. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15895. }
  15896. return {
  15897. isInterleavedBufferAttribute: true,
  15898. itemSize: this.itemSize,
  15899. data: this.data.uuid,
  15900. offset: this.offset,
  15901. normalized: this.normalized
  15902. };
  15903. }
  15904. }
  15905. });
  15906. /**
  15907. * parameters = {
  15908. * color: <hex>,
  15909. * map: new THREE.Texture( <Image> ),
  15910. * alphaMap: new THREE.Texture( <Image> ),
  15911. * rotation: <float>,
  15912. * sizeAttenuation: <bool>
  15913. * }
  15914. */
  15915. function SpriteMaterial(parameters) {
  15916. Material.call(this);
  15917. this.type = 'SpriteMaterial';
  15918. this.color = new Color(0xffffff);
  15919. this.map = null;
  15920. this.alphaMap = null;
  15921. this.rotation = 0;
  15922. this.sizeAttenuation = true;
  15923. this.transparent = true;
  15924. this.setValues(parameters);
  15925. }
  15926. SpriteMaterial.prototype = Object.create(Material.prototype);
  15927. SpriteMaterial.prototype.constructor = SpriteMaterial;
  15928. SpriteMaterial.prototype.isSpriteMaterial = true;
  15929. SpriteMaterial.prototype.copy = function (source) {
  15930. Material.prototype.copy.call(this, source);
  15931. this.color.copy(source.color);
  15932. this.map = source.map;
  15933. this.alphaMap = source.alphaMap;
  15934. this.rotation = source.rotation;
  15935. this.sizeAttenuation = source.sizeAttenuation;
  15936. return this;
  15937. };
  15938. let _geometry;
  15939. const _intersectPoint = new Vector3();
  15940. const _worldScale = new Vector3();
  15941. const _mvPosition = new Vector3();
  15942. const _alignedPosition = new Vector2();
  15943. const _rotatedPosition = new Vector2();
  15944. const _viewWorldMatrix = new Matrix4();
  15945. const _vA$1 = new Vector3();
  15946. const _vB$1 = new Vector3();
  15947. const _vC$1 = new Vector3();
  15948. const _uvA$1 = new Vector2();
  15949. const _uvB$1 = new Vector2();
  15950. const _uvC$1 = new Vector2();
  15951. function Sprite(material) {
  15952. Object3D.call(this);
  15953. this.type = 'Sprite';
  15954. if (_geometry === undefined) {
  15955. _geometry = new BufferGeometry();
  15956. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  15957. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15958. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15959. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15960. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15961. }
  15962. this.geometry = _geometry;
  15963. this.material = material !== undefined ? material : new SpriteMaterial();
  15964. this.center = new Vector2(0.5, 0.5);
  15965. }
  15966. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  15967. constructor: Sprite,
  15968. isSprite: true,
  15969. raycast: function (raycaster, intersects) {
  15970. if (raycaster.camera === null) {
  15971. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15972. }
  15973. _worldScale.setFromMatrixScale(this.matrixWorld);
  15974. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15975. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15976. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15977. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15978. _worldScale.multiplyScalar(-_mvPosition.z);
  15979. }
  15980. const rotation = this.material.rotation;
  15981. let sin, cos;
  15982. if (rotation !== 0) {
  15983. cos = Math.cos(rotation);
  15984. sin = Math.sin(rotation);
  15985. }
  15986. const center = this.center;
  15987. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15988. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15989. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15990. _uvA$1.set(0, 0);
  15991. _uvB$1.set(1, 0);
  15992. _uvC$1.set(1, 1); // check first triangle
  15993. let intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  15994. if (intersect === null) {
  15995. // check second triangle
  15996. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15997. _uvB$1.set(0, 1);
  15998. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  15999. if (intersect === null) {
  16000. return;
  16001. }
  16002. }
  16003. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16004. if (distance < raycaster.near || distance > raycaster.far) return;
  16005. intersects.push({
  16006. distance: distance,
  16007. point: _intersectPoint.clone(),
  16008. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16009. face: null,
  16010. object: this
  16011. });
  16012. },
  16013. copy: function (source) {
  16014. Object3D.prototype.copy.call(this, source);
  16015. if (source.center !== undefined) this.center.copy(source.center);
  16016. this.material = source.material;
  16017. return this;
  16018. }
  16019. });
  16020. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16021. // compute position in camera space
  16022. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16023. if (sin !== undefined) {
  16024. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16025. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16026. } else {
  16027. _rotatedPosition.copy(_alignedPosition);
  16028. }
  16029. vertexPosition.copy(mvPosition);
  16030. vertexPosition.x += _rotatedPosition.x;
  16031. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16032. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16033. }
  16034. const _v1$4 = new Vector3();
  16035. const _v2$2 = new Vector3();
  16036. function LOD() {
  16037. Object3D.call(this);
  16038. this._currentLevel = 0;
  16039. this.type = 'LOD';
  16040. Object.defineProperties(this, {
  16041. levels: {
  16042. enumerable: true,
  16043. value: []
  16044. }
  16045. });
  16046. this.autoUpdate = true;
  16047. }
  16048. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16049. constructor: LOD,
  16050. isLOD: true,
  16051. copy: function (source) {
  16052. Object3D.prototype.copy.call(this, source, false);
  16053. const levels = source.levels;
  16054. for (let i = 0, l = levels.length; i < l; i++) {
  16055. const level = levels[i];
  16056. this.addLevel(level.object.clone(), level.distance);
  16057. }
  16058. this.autoUpdate = source.autoUpdate;
  16059. return this;
  16060. },
  16061. addLevel: function (object, distance = 0) {
  16062. distance = Math.abs(distance);
  16063. const levels = this.levels;
  16064. let l;
  16065. for (l = 0; l < levels.length; l++) {
  16066. if (distance < levels[l].distance) {
  16067. break;
  16068. }
  16069. }
  16070. levels.splice(l, 0, {
  16071. distance: distance,
  16072. object: object
  16073. });
  16074. this.add(object);
  16075. return this;
  16076. },
  16077. getCurrentLevel: function () {
  16078. return this._currentLevel;
  16079. },
  16080. getObjectForDistance: function (distance) {
  16081. const levels = this.levels;
  16082. if (levels.length > 0) {
  16083. let i, l;
  16084. for (i = 1, l = levels.length; i < l; i++) {
  16085. if (distance < levels[i].distance) {
  16086. break;
  16087. }
  16088. }
  16089. return levels[i - 1].object;
  16090. }
  16091. return null;
  16092. },
  16093. raycast: function (raycaster, intersects) {
  16094. const levels = this.levels;
  16095. if (levels.length > 0) {
  16096. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16097. const distance = raycaster.ray.origin.distanceTo(_v1$4);
  16098. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16099. }
  16100. },
  16101. update: function (camera) {
  16102. const levels = this.levels;
  16103. if (levels.length > 1) {
  16104. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16105. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16106. const distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  16107. levels[0].object.visible = true;
  16108. let i, l;
  16109. for (i = 1, l = levels.length; i < l; i++) {
  16110. if (distance >= levels[i].distance) {
  16111. levels[i - 1].object.visible = false;
  16112. levels[i].object.visible = true;
  16113. } else {
  16114. break;
  16115. }
  16116. }
  16117. this._currentLevel = i - 1;
  16118. for (; i < l; i++) {
  16119. levels[i].object.visible = false;
  16120. }
  16121. }
  16122. },
  16123. toJSON: function (meta) {
  16124. const data = Object3D.prototype.toJSON.call(this, meta);
  16125. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16126. data.object.levels = [];
  16127. const levels = this.levels;
  16128. for (let i = 0, l = levels.length; i < l; i++) {
  16129. const level = levels[i];
  16130. data.object.levels.push({
  16131. object: level.object.uuid,
  16132. distance: level.distance
  16133. });
  16134. }
  16135. return data;
  16136. }
  16137. });
  16138. function SkinnedMesh(geometry, material) {
  16139. if (geometry && geometry.isGeometry) {
  16140. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16141. }
  16142. Mesh.call(this, geometry, material);
  16143. this.type = 'SkinnedMesh';
  16144. this.bindMode = 'attached';
  16145. this.bindMatrix = new Matrix4();
  16146. this.bindMatrixInverse = new Matrix4();
  16147. }
  16148. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16149. constructor: SkinnedMesh,
  16150. isSkinnedMesh: true,
  16151. copy: function (source) {
  16152. Mesh.prototype.copy.call(this, source);
  16153. this.bindMode = source.bindMode;
  16154. this.bindMatrix.copy(source.bindMatrix);
  16155. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16156. this.skeleton = source.skeleton;
  16157. return this;
  16158. },
  16159. bind: function (skeleton, bindMatrix) {
  16160. this.skeleton = skeleton;
  16161. if (bindMatrix === undefined) {
  16162. this.updateMatrixWorld(true);
  16163. this.skeleton.calculateInverses();
  16164. bindMatrix = this.matrixWorld;
  16165. }
  16166. this.bindMatrix.copy(bindMatrix);
  16167. this.bindMatrixInverse.copy(bindMatrix).invert();
  16168. },
  16169. pose: function () {
  16170. this.skeleton.pose();
  16171. },
  16172. normalizeSkinWeights: function () {
  16173. const vector = new Vector4();
  16174. const skinWeight = this.geometry.attributes.skinWeight;
  16175. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16176. vector.x = skinWeight.getX(i);
  16177. vector.y = skinWeight.getY(i);
  16178. vector.z = skinWeight.getZ(i);
  16179. vector.w = skinWeight.getW(i);
  16180. const scale = 1.0 / vector.manhattanLength();
  16181. if (scale !== Infinity) {
  16182. vector.multiplyScalar(scale);
  16183. } else {
  16184. vector.set(1, 0, 0, 0); // do something reasonable
  16185. }
  16186. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16187. }
  16188. },
  16189. updateMatrixWorld: function (force) {
  16190. Mesh.prototype.updateMatrixWorld.call(this, force);
  16191. if (this.bindMode === 'attached') {
  16192. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16193. } else if (this.bindMode === 'detached') {
  16194. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16195. } else {
  16196. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16197. }
  16198. },
  16199. boneTransform: function () {
  16200. const basePosition = new Vector3();
  16201. const skinIndex = new Vector4();
  16202. const skinWeight = new Vector4();
  16203. const vector = new Vector3();
  16204. const matrix = new Matrix4();
  16205. return function (index, target) {
  16206. const skeleton = this.skeleton;
  16207. const geometry = this.geometry;
  16208. skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16209. skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16210. basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  16211. target.set(0, 0, 0);
  16212. for (let i = 0; i < 4; i++) {
  16213. const weight = skinWeight.getComponent(i);
  16214. if (weight !== 0) {
  16215. const boneIndex = skinIndex.getComponent(i);
  16216. matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16217. target.addScaledVector(vector.copy(basePosition).applyMatrix4(matrix), weight);
  16218. }
  16219. }
  16220. return target.applyMatrix4(this.bindMatrixInverse);
  16221. };
  16222. }()
  16223. });
  16224. function Bone() {
  16225. Object3D.call(this);
  16226. this.type = 'Bone';
  16227. }
  16228. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16229. constructor: Bone,
  16230. isBone: true
  16231. });
  16232. const _offsetMatrix = new Matrix4();
  16233. const _identityMatrix = new Matrix4();
  16234. function Skeleton(bones = [], boneInverses = []) {
  16235. this.uuid = MathUtils.generateUUID();
  16236. this.bones = bones.slice(0);
  16237. this.boneInverses = boneInverses;
  16238. this.boneMatrices = null;
  16239. this.boneTexture = null;
  16240. this.boneTextureSize = 0;
  16241. this.frame = -1;
  16242. this.init();
  16243. }
  16244. Object.assign(Skeleton.prototype, {
  16245. init: function () {
  16246. const bones = this.bones;
  16247. const boneInverses = this.boneInverses;
  16248. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  16249. if (boneInverses.length === 0) {
  16250. this.calculateInverses();
  16251. } else {
  16252. // handle special case
  16253. if (bones.length !== boneInverses.length) {
  16254. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  16255. this.boneInverses = [];
  16256. for (let i = 0, il = this.bones.length; i < il; i++) {
  16257. this.boneInverses.push(new Matrix4());
  16258. }
  16259. }
  16260. }
  16261. },
  16262. calculateInverses: function () {
  16263. this.boneInverses.length = 0;
  16264. for (let i = 0, il = this.bones.length; i < il; i++) {
  16265. const inverse = new Matrix4();
  16266. if (this.bones[i]) {
  16267. inverse.copy(this.bones[i].matrixWorld).invert();
  16268. }
  16269. this.boneInverses.push(inverse);
  16270. }
  16271. },
  16272. pose: function () {
  16273. // recover the bind-time world matrices
  16274. for (let i = 0, il = this.bones.length; i < il; i++) {
  16275. const bone = this.bones[i];
  16276. if (bone) {
  16277. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  16278. }
  16279. } // compute the local matrices, positions, rotations and scales
  16280. for (let i = 0, il = this.bones.length; i < il; i++) {
  16281. const bone = this.bones[i];
  16282. if (bone) {
  16283. if (bone.parent && bone.parent.isBone) {
  16284. bone.matrix.copy(bone.parent.matrixWorld).invert();
  16285. bone.matrix.multiply(bone.matrixWorld);
  16286. } else {
  16287. bone.matrix.copy(bone.matrixWorld);
  16288. }
  16289. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16290. }
  16291. }
  16292. },
  16293. update: function () {
  16294. const bones = this.bones;
  16295. const boneInverses = this.boneInverses;
  16296. const boneMatrices = this.boneMatrices;
  16297. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16298. for (let i = 0, il = bones.length; i < il; i++) {
  16299. // compute the offset between the current and the original transform
  16300. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16301. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16302. _offsetMatrix.toArray(boneMatrices, i * 16);
  16303. }
  16304. if (boneTexture !== null) {
  16305. boneTexture.needsUpdate = true;
  16306. }
  16307. },
  16308. clone: function () {
  16309. return new Skeleton(this.bones, this.boneInverses);
  16310. },
  16311. getBoneByName: function (name) {
  16312. for (let i = 0, il = this.bones.length; i < il; i++) {
  16313. const bone = this.bones[i];
  16314. if (bone.name === name) {
  16315. return bone;
  16316. }
  16317. }
  16318. return undefined;
  16319. },
  16320. dispose: function () {
  16321. if (this.boneTexture !== null) {
  16322. this.boneTexture.dispose();
  16323. this.boneTexture = null;
  16324. }
  16325. },
  16326. fromJSON: function (json, bones) {
  16327. this.uuid = json.uuid;
  16328. for (let i = 0, l = json.bones.length; i < l; i++) {
  16329. const uuid = json.bones[i];
  16330. let bone = bones[uuid];
  16331. if (bone === undefined) {
  16332. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16333. bone = new Bone();
  16334. }
  16335. this.bones.push(bone);
  16336. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16337. }
  16338. this.init();
  16339. return this;
  16340. },
  16341. toJSON: function () {
  16342. const data = {
  16343. metadata: {
  16344. version: 4.5,
  16345. type: 'Skeleton',
  16346. generator: 'Skeleton.toJSON'
  16347. },
  16348. bones: [],
  16349. boneInverses: []
  16350. };
  16351. data.uuid = this.uuid;
  16352. const bones = this.bones;
  16353. const boneInverses = this.boneInverses;
  16354. for (let i = 0, l = bones.length; i < l; i++) {
  16355. const bone = bones[i];
  16356. data.bones.push(bone.uuid);
  16357. const boneInverse = boneInverses[i];
  16358. data.boneInverses.push(boneInverse.toArray());
  16359. }
  16360. return data;
  16361. }
  16362. });
  16363. const _instanceLocalMatrix = new Matrix4();
  16364. const _instanceWorldMatrix = new Matrix4();
  16365. const _instanceIntersects = [];
  16366. const _mesh = new Mesh();
  16367. function InstancedMesh(geometry, material, count) {
  16368. Mesh.call(this, geometry, material);
  16369. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16370. this.instanceColor = null;
  16371. this.count = count;
  16372. this.frustumCulled = false;
  16373. }
  16374. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16375. constructor: InstancedMesh,
  16376. isInstancedMesh: true,
  16377. copy: function (source) {
  16378. Mesh.prototype.copy.call(this, source);
  16379. this.instanceMatrix.copy(source.instanceMatrix);
  16380. this.count = source.count;
  16381. return this;
  16382. },
  16383. getColorAt: function (index, color) {
  16384. color.fromArray(this.instanceColor.array, index * 3);
  16385. },
  16386. getMatrixAt: function (index, matrix) {
  16387. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16388. },
  16389. raycast: function (raycaster, intersects) {
  16390. const matrixWorld = this.matrixWorld;
  16391. const raycastTimes = this.count;
  16392. _mesh.geometry = this.geometry;
  16393. _mesh.material = this.material;
  16394. if (_mesh.material === undefined) return;
  16395. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16396. // calculate the world matrix for each instance
  16397. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16398. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16399. _mesh.matrixWorld = _instanceWorldMatrix;
  16400. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16401. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16402. const intersect = _instanceIntersects[i];
  16403. intersect.instanceId = instanceId;
  16404. intersect.object = this;
  16405. intersects.push(intersect);
  16406. }
  16407. _instanceIntersects.length = 0;
  16408. }
  16409. },
  16410. setColorAt: function (index, color) {
  16411. if (this.instanceColor === null) {
  16412. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16413. }
  16414. color.toArray(this.instanceColor.array, index * 3);
  16415. },
  16416. setMatrixAt: function (index, matrix) {
  16417. matrix.toArray(this.instanceMatrix.array, index * 16);
  16418. },
  16419. updateMorphTargets: function () {}
  16420. });
  16421. /**
  16422. * parameters = {
  16423. * color: <hex>,
  16424. * opacity: <float>,
  16425. *
  16426. * linewidth: <float>,
  16427. * linecap: "round",
  16428. * linejoin: "round"
  16429. * }
  16430. */
  16431. function LineBasicMaterial(parameters) {
  16432. Material.call(this);
  16433. this.type = 'LineBasicMaterial';
  16434. this.color = new Color(0xffffff);
  16435. this.linewidth = 1;
  16436. this.linecap = 'round';
  16437. this.linejoin = 'round';
  16438. this.morphTargets = false;
  16439. this.setValues(parameters);
  16440. }
  16441. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16442. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16443. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16444. LineBasicMaterial.prototype.copy = function (source) {
  16445. Material.prototype.copy.call(this, source);
  16446. this.color.copy(source.color);
  16447. this.linewidth = source.linewidth;
  16448. this.linecap = source.linecap;
  16449. this.linejoin = source.linejoin;
  16450. this.morphTargets = source.morphTargets;
  16451. return this;
  16452. };
  16453. const _start = new Vector3();
  16454. const _end = new Vector3();
  16455. const _inverseMatrix$1 = new Matrix4();
  16456. const _ray$1 = new Ray();
  16457. const _sphere$2 = new Sphere();
  16458. function Line(geometry, material, mode) {
  16459. if (mode === 1) {
  16460. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16461. }
  16462. Object3D.call(this);
  16463. this.type = 'Line';
  16464. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16465. this.material = material !== undefined ? material : new LineBasicMaterial();
  16466. this.updateMorphTargets();
  16467. }
  16468. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16469. constructor: Line,
  16470. isLine: true,
  16471. copy: function (source) {
  16472. Object3D.prototype.copy.call(this, source);
  16473. this.material = source.material;
  16474. this.geometry = source.geometry;
  16475. return this;
  16476. },
  16477. computeLineDistances: function () {
  16478. const geometry = this.geometry;
  16479. if (geometry.isBufferGeometry) {
  16480. // we assume non-indexed geometry
  16481. if (geometry.index === null) {
  16482. const positionAttribute = geometry.attributes.position;
  16483. const lineDistances = [0];
  16484. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16485. _start.fromBufferAttribute(positionAttribute, i - 1);
  16486. _end.fromBufferAttribute(positionAttribute, i);
  16487. lineDistances[i] = lineDistances[i - 1];
  16488. lineDistances[i] += _start.distanceTo(_end);
  16489. }
  16490. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16491. } else {
  16492. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16493. }
  16494. } else if (geometry.isGeometry) {
  16495. const vertices = geometry.vertices;
  16496. const lineDistances = geometry.lineDistances;
  16497. lineDistances[0] = 0;
  16498. for (let i = 1, l = vertices.length; i < l; i++) {
  16499. lineDistances[i] = lineDistances[i - 1];
  16500. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16501. }
  16502. }
  16503. return this;
  16504. },
  16505. raycast: function (raycaster, intersects) {
  16506. const geometry = this.geometry;
  16507. const matrixWorld = this.matrixWorld;
  16508. const threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  16509. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16510. _sphere$2.copy(geometry.boundingSphere);
  16511. _sphere$2.applyMatrix4(matrixWorld);
  16512. _sphere$2.radius += threshold;
  16513. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16514. _inverseMatrix$1.copy(matrixWorld).invert();
  16515. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16516. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16517. const localThresholdSq = localThreshold * localThreshold;
  16518. const vStart = new Vector3();
  16519. const vEnd = new Vector3();
  16520. const interSegment = new Vector3();
  16521. const interRay = new Vector3();
  16522. const step = this.isLineSegments ? 2 : 1;
  16523. if (geometry.isBufferGeometry) {
  16524. const index = geometry.index;
  16525. const attributes = geometry.attributes;
  16526. const positionAttribute = attributes.position;
  16527. if (index !== null) {
  16528. const indices = index.array;
  16529. for (let i = 0, l = indices.length - 1; i < l; i += step) {
  16530. const a = indices[i];
  16531. const b = indices[i + 1];
  16532. vStart.fromBufferAttribute(positionAttribute, a);
  16533. vEnd.fromBufferAttribute(positionAttribute, b);
  16534. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16535. if (distSq > localThresholdSq) continue;
  16536. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16537. const distance = raycaster.ray.origin.distanceTo(interRay);
  16538. if (distance < raycaster.near || distance > raycaster.far) continue;
  16539. intersects.push({
  16540. distance: distance,
  16541. // What do we want? intersection point on the ray or on the segment??
  16542. // point: raycaster.ray.at( distance ),
  16543. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16544. index: i,
  16545. face: null,
  16546. faceIndex: null,
  16547. object: this
  16548. });
  16549. }
  16550. } else {
  16551. for (let i = 0, l = positionAttribute.count - 1; i < l; i += step) {
  16552. vStart.fromBufferAttribute(positionAttribute, i);
  16553. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16554. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16555. if (distSq > localThresholdSq) continue;
  16556. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16557. const distance = raycaster.ray.origin.distanceTo(interRay);
  16558. if (distance < raycaster.near || distance > raycaster.far) continue;
  16559. intersects.push({
  16560. distance: distance,
  16561. // What do we want? intersection point on the ray or on the segment??
  16562. // point: raycaster.ray.at( distance ),
  16563. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16564. index: i,
  16565. face: null,
  16566. faceIndex: null,
  16567. object: this
  16568. });
  16569. }
  16570. }
  16571. } else if (geometry.isGeometry) {
  16572. const vertices = geometry.vertices;
  16573. const nbVertices = vertices.length;
  16574. for (let i = 0; i < nbVertices - 1; i += step) {
  16575. const distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16576. if (distSq > localThresholdSq) continue;
  16577. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16578. const distance = raycaster.ray.origin.distanceTo(interRay);
  16579. if (distance < raycaster.near || distance > raycaster.far) continue;
  16580. intersects.push({
  16581. distance: distance,
  16582. // What do we want? intersection point on the ray or on the segment??
  16583. // point: raycaster.ray.at( distance ),
  16584. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16585. index: i,
  16586. face: null,
  16587. faceIndex: null,
  16588. object: this
  16589. });
  16590. }
  16591. }
  16592. },
  16593. updateMorphTargets: function () {
  16594. const geometry = this.geometry;
  16595. if (geometry.isBufferGeometry) {
  16596. const morphAttributes = geometry.morphAttributes;
  16597. const keys = Object.keys(morphAttributes);
  16598. if (keys.length > 0) {
  16599. const morphAttribute = morphAttributes[keys[0]];
  16600. if (morphAttribute !== undefined) {
  16601. this.morphTargetInfluences = [];
  16602. this.morphTargetDictionary = {};
  16603. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16604. const name = morphAttribute[m].name || String(m);
  16605. this.morphTargetInfluences.push(0);
  16606. this.morphTargetDictionary[name] = m;
  16607. }
  16608. }
  16609. }
  16610. } else {
  16611. const morphTargets = geometry.morphTargets;
  16612. if (morphTargets !== undefined && morphTargets.length > 0) {
  16613. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16614. }
  16615. }
  16616. }
  16617. });
  16618. const _start$1 = new Vector3();
  16619. const _end$1 = new Vector3();
  16620. function LineSegments(geometry, material) {
  16621. Line.call(this, geometry, material);
  16622. this.type = 'LineSegments';
  16623. }
  16624. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16625. constructor: LineSegments,
  16626. isLineSegments: true,
  16627. computeLineDistances: function () {
  16628. const geometry = this.geometry;
  16629. if (geometry.isBufferGeometry) {
  16630. // we assume non-indexed geometry
  16631. if (geometry.index === null) {
  16632. const positionAttribute = geometry.attributes.position;
  16633. const lineDistances = [];
  16634. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16635. _start$1.fromBufferAttribute(positionAttribute, i);
  16636. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16637. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16638. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16639. }
  16640. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16641. } else {
  16642. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16643. }
  16644. } else if (geometry.isGeometry) {
  16645. const vertices = geometry.vertices;
  16646. const lineDistances = geometry.lineDistances;
  16647. for (let i = 0, l = vertices.length; i < l; i += 2) {
  16648. _start$1.copy(vertices[i]);
  16649. _end$1.copy(vertices[i + 1]);
  16650. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16651. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16652. }
  16653. }
  16654. return this;
  16655. }
  16656. });
  16657. function LineLoop(geometry, material) {
  16658. Line.call(this, geometry, material);
  16659. this.type = 'LineLoop';
  16660. }
  16661. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16662. constructor: LineLoop,
  16663. isLineLoop: true
  16664. });
  16665. /**
  16666. * parameters = {
  16667. * color: <hex>,
  16668. * opacity: <float>,
  16669. * map: new THREE.Texture( <Image> ),
  16670. * alphaMap: new THREE.Texture( <Image> ),
  16671. *
  16672. * size: <float>,
  16673. * sizeAttenuation: <bool>
  16674. *
  16675. * morphTargets: <bool>
  16676. * }
  16677. */
  16678. function PointsMaterial(parameters) {
  16679. Material.call(this);
  16680. this.type = 'PointsMaterial';
  16681. this.color = new Color(0xffffff);
  16682. this.map = null;
  16683. this.alphaMap = null;
  16684. this.size = 1;
  16685. this.sizeAttenuation = true;
  16686. this.morphTargets = false;
  16687. this.setValues(parameters);
  16688. }
  16689. PointsMaterial.prototype = Object.create(Material.prototype);
  16690. PointsMaterial.prototype.constructor = PointsMaterial;
  16691. PointsMaterial.prototype.isPointsMaterial = true;
  16692. PointsMaterial.prototype.copy = function (source) {
  16693. Material.prototype.copy.call(this, source);
  16694. this.color.copy(source.color);
  16695. this.map = source.map;
  16696. this.alphaMap = source.alphaMap;
  16697. this.size = source.size;
  16698. this.sizeAttenuation = source.sizeAttenuation;
  16699. this.morphTargets = source.morphTargets;
  16700. return this;
  16701. };
  16702. const _inverseMatrix$2 = new Matrix4();
  16703. const _ray$2 = new Ray();
  16704. const _sphere$3 = new Sphere();
  16705. const _position$1 = new Vector3();
  16706. function Points(geometry, material) {
  16707. Object3D.call(this);
  16708. this.type = 'Points';
  16709. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16710. this.material = material !== undefined ? material : new PointsMaterial();
  16711. this.updateMorphTargets();
  16712. }
  16713. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16714. constructor: Points,
  16715. isPoints: true,
  16716. copy: function (source) {
  16717. Object3D.prototype.copy.call(this, source);
  16718. this.material = source.material;
  16719. this.geometry = source.geometry;
  16720. return this;
  16721. },
  16722. raycast: function (raycaster, intersects) {
  16723. const geometry = this.geometry;
  16724. const matrixWorld = this.matrixWorld;
  16725. const threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16726. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16727. _sphere$3.copy(geometry.boundingSphere);
  16728. _sphere$3.applyMatrix4(matrixWorld);
  16729. _sphere$3.radius += threshold;
  16730. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16731. _inverseMatrix$2.copy(matrixWorld).invert();
  16732. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16733. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16734. const localThresholdSq = localThreshold * localThreshold;
  16735. if (geometry.isBufferGeometry) {
  16736. const index = geometry.index;
  16737. const attributes = geometry.attributes;
  16738. const positionAttribute = attributes.position;
  16739. if (index !== null) {
  16740. const indices = index.array;
  16741. for (let i = 0, il = indices.length; i < il; i++) {
  16742. const a = indices[i];
  16743. _position$1.fromBufferAttribute(positionAttribute, a);
  16744. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16745. }
  16746. } else {
  16747. for (let i = 0, l = positionAttribute.count; i < l; i++) {
  16748. _position$1.fromBufferAttribute(positionAttribute, i);
  16749. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16750. }
  16751. }
  16752. } else {
  16753. const vertices = geometry.vertices;
  16754. for (let i = 0, l = vertices.length; i < l; i++) {
  16755. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16756. }
  16757. }
  16758. },
  16759. updateMorphTargets: function () {
  16760. const geometry = this.geometry;
  16761. if (geometry.isBufferGeometry) {
  16762. const morphAttributes = geometry.morphAttributes;
  16763. const keys = Object.keys(morphAttributes);
  16764. if (keys.length > 0) {
  16765. const morphAttribute = morphAttributes[keys[0]];
  16766. if (morphAttribute !== undefined) {
  16767. this.morphTargetInfluences = [];
  16768. this.morphTargetDictionary = {};
  16769. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16770. const name = morphAttribute[m].name || String(m);
  16771. this.morphTargetInfluences.push(0);
  16772. this.morphTargetDictionary[name] = m;
  16773. }
  16774. }
  16775. }
  16776. } else {
  16777. const morphTargets = geometry.morphTargets;
  16778. if (morphTargets !== undefined && morphTargets.length > 0) {
  16779. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16780. }
  16781. }
  16782. }
  16783. });
  16784. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16785. const rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  16786. if (rayPointDistanceSq < localThresholdSq) {
  16787. const intersectPoint = new Vector3();
  16788. _ray$2.closestPointToPoint(point, intersectPoint);
  16789. intersectPoint.applyMatrix4(matrixWorld);
  16790. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16791. if (distance < raycaster.near || distance > raycaster.far) return;
  16792. intersects.push({
  16793. distance: distance,
  16794. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16795. point: intersectPoint,
  16796. index: index,
  16797. face: null,
  16798. object: object
  16799. });
  16800. }
  16801. }
  16802. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16803. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16804. this.format = format !== undefined ? format : RGBFormat;
  16805. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16806. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16807. this.generateMipmaps = false;
  16808. const scope = this;
  16809. function updateVideo() {
  16810. scope.needsUpdate = true;
  16811. video.requestVideoFrameCallback(updateVideo);
  16812. }
  16813. if ('requestVideoFrameCallback' in video) {
  16814. video.requestVideoFrameCallback(updateVideo);
  16815. }
  16816. }
  16817. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  16818. constructor: VideoTexture,
  16819. clone: function () {
  16820. return new this.constructor(this.image).copy(this);
  16821. },
  16822. isVideoTexture: true,
  16823. update: function () {
  16824. const video = this.image;
  16825. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16826. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16827. this.needsUpdate = true;
  16828. }
  16829. }
  16830. });
  16831. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16832. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16833. this.image = {
  16834. width: width,
  16835. height: height
  16836. };
  16837. this.mipmaps = mipmaps; // no flipping for cube textures
  16838. // (also flipping doesn't work for compressed textures )
  16839. this.flipY = false; // can't generate mipmaps for compressed textures
  16840. // mips must be embedded in DDS files
  16841. this.generateMipmaps = false;
  16842. }
  16843. CompressedTexture.prototype = Object.create(Texture.prototype);
  16844. CompressedTexture.prototype.constructor = CompressedTexture;
  16845. CompressedTexture.prototype.isCompressedTexture = true;
  16846. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16847. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16848. this.needsUpdate = true;
  16849. }
  16850. CanvasTexture.prototype = Object.create(Texture.prototype);
  16851. CanvasTexture.prototype.constructor = CanvasTexture;
  16852. CanvasTexture.prototype.isCanvasTexture = true;
  16853. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16854. format = format !== undefined ? format : DepthFormat;
  16855. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16856. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16857. }
  16858. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16859. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16860. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16861. this.image = {
  16862. width: width,
  16863. height: height
  16864. };
  16865. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16866. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16867. this.flipY = false;
  16868. this.generateMipmaps = false;
  16869. }
  16870. DepthTexture.prototype = Object.create(Texture.prototype);
  16871. DepthTexture.prototype.constructor = DepthTexture;
  16872. DepthTexture.prototype.isDepthTexture = true;
  16873. let _geometryId = 0; // Geometry uses even numbers as Id
  16874. const _m1$3 = new Matrix4();
  16875. const _obj$1 = new Object3D();
  16876. const _offset$1 = new Vector3();
  16877. function Geometry() {
  16878. Object.defineProperty(this, 'id', {
  16879. value: _geometryId += 2
  16880. });
  16881. this.uuid = MathUtils.generateUUID();
  16882. this.name = '';
  16883. this.type = 'Geometry';
  16884. this.vertices = [];
  16885. this.colors = [];
  16886. this.faces = [];
  16887. this.faceVertexUvs = [[]];
  16888. this.morphTargets = [];
  16889. this.morphNormals = [];
  16890. this.skinWeights = [];
  16891. this.skinIndices = [];
  16892. this.lineDistances = [];
  16893. this.boundingBox = null;
  16894. this.boundingSphere = null; // update flags
  16895. this.elementsNeedUpdate = false;
  16896. this.verticesNeedUpdate = false;
  16897. this.uvsNeedUpdate = false;
  16898. this.normalsNeedUpdate = false;
  16899. this.colorsNeedUpdate = false;
  16900. this.lineDistancesNeedUpdate = false;
  16901. this.groupsNeedUpdate = false;
  16902. }
  16903. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  16904. constructor: Geometry,
  16905. isGeometry: true,
  16906. applyMatrix4: function (matrix) {
  16907. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  16908. for (let i = 0, il = this.vertices.length; i < il; i++) {
  16909. const vertex = this.vertices[i];
  16910. vertex.applyMatrix4(matrix);
  16911. }
  16912. for (let i = 0, il = this.faces.length; i < il; i++) {
  16913. const face = this.faces[i];
  16914. face.normal.applyMatrix3(normalMatrix).normalize();
  16915. for (let j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  16916. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  16917. }
  16918. }
  16919. if (this.boundingBox !== null) {
  16920. this.computeBoundingBox();
  16921. }
  16922. if (this.boundingSphere !== null) {
  16923. this.computeBoundingSphere();
  16924. }
  16925. this.verticesNeedUpdate = true;
  16926. this.normalsNeedUpdate = true;
  16927. return this;
  16928. },
  16929. rotateX: function (angle) {
  16930. // rotate geometry around world x-axis
  16931. _m1$3.makeRotationX(angle);
  16932. this.applyMatrix4(_m1$3);
  16933. return this;
  16934. },
  16935. rotateY: function (angle) {
  16936. // rotate geometry around world y-axis
  16937. _m1$3.makeRotationY(angle);
  16938. this.applyMatrix4(_m1$3);
  16939. return this;
  16940. },
  16941. rotateZ: function (angle) {
  16942. // rotate geometry around world z-axis
  16943. _m1$3.makeRotationZ(angle);
  16944. this.applyMatrix4(_m1$3);
  16945. return this;
  16946. },
  16947. translate: function (x, y, z) {
  16948. // translate geometry
  16949. _m1$3.makeTranslation(x, y, z);
  16950. this.applyMatrix4(_m1$3);
  16951. return this;
  16952. },
  16953. scale: function (x, y, z) {
  16954. // scale geometry
  16955. _m1$3.makeScale(x, y, z);
  16956. this.applyMatrix4(_m1$3);
  16957. return this;
  16958. },
  16959. lookAt: function (vector) {
  16960. _obj$1.lookAt(vector);
  16961. _obj$1.updateMatrix();
  16962. this.applyMatrix4(_obj$1.matrix);
  16963. return this;
  16964. },
  16965. fromBufferGeometry: function (geometry) {
  16966. const scope = this;
  16967. const index = geometry.index !== null ? geometry.index : undefined;
  16968. const attributes = geometry.attributes;
  16969. if (attributes.position === undefined) {
  16970. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  16971. return this;
  16972. }
  16973. const position = attributes.position;
  16974. const normal = attributes.normal;
  16975. const color = attributes.color;
  16976. const uv = attributes.uv;
  16977. const uv2 = attributes.uv2;
  16978. if (uv2 !== undefined) this.faceVertexUvs[1] = [];
  16979. for (let i = 0; i < position.count; i++) {
  16980. scope.vertices.push(new Vector3().fromBufferAttribute(position, i));
  16981. if (color !== undefined) {
  16982. scope.colors.push(new Color().fromBufferAttribute(color, i));
  16983. }
  16984. }
  16985. function addFace(a, b, c, materialIndex) {
  16986. const vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  16987. const vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)];
  16988. const face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  16989. scope.faces.push(face);
  16990. if (uv !== undefined) {
  16991. scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]);
  16992. }
  16993. if (uv2 !== undefined) {
  16994. scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]);
  16995. }
  16996. }
  16997. const groups = geometry.groups;
  16998. if (groups.length > 0) {
  16999. for (let i = 0; i < groups.length; i++) {
  17000. const group = groups[i];
  17001. const start = group.start;
  17002. const count = group.count;
  17003. for (let j = start, jl = start + count; j < jl; j += 3) {
  17004. if (index !== undefined) {
  17005. addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex);
  17006. } else {
  17007. addFace(j, j + 1, j + 2, group.materialIndex);
  17008. }
  17009. }
  17010. }
  17011. } else {
  17012. if (index !== undefined) {
  17013. for (let i = 0; i < index.count; i += 3) {
  17014. addFace(index.getX(i), index.getX(i + 1), index.getX(i + 2));
  17015. }
  17016. } else {
  17017. for (let i = 0; i < position.count; i += 3) {
  17018. addFace(i, i + 1, i + 2);
  17019. }
  17020. }
  17021. }
  17022. this.computeFaceNormals();
  17023. if (geometry.boundingBox !== null) {
  17024. this.boundingBox = geometry.boundingBox.clone();
  17025. }
  17026. if (geometry.boundingSphere !== null) {
  17027. this.boundingSphere = geometry.boundingSphere.clone();
  17028. }
  17029. return this;
  17030. },
  17031. center: function () {
  17032. this.computeBoundingBox();
  17033. this.boundingBox.getCenter(_offset$1).negate();
  17034. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  17035. return this;
  17036. },
  17037. normalize: function () {
  17038. this.computeBoundingSphere();
  17039. const center = this.boundingSphere.center;
  17040. const radius = this.boundingSphere.radius;
  17041. const s = radius === 0 ? 1 : 1.0 / radius;
  17042. const matrix = new Matrix4();
  17043. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  17044. this.applyMatrix4(matrix);
  17045. return this;
  17046. },
  17047. computeFaceNormals: function () {
  17048. const cb = new Vector3(),
  17049. ab = new Vector3();
  17050. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17051. const face = this.faces[f];
  17052. const vA = this.vertices[face.a];
  17053. const vB = this.vertices[face.b];
  17054. const vC = this.vertices[face.c];
  17055. cb.subVectors(vC, vB);
  17056. ab.subVectors(vA, vB);
  17057. cb.cross(ab);
  17058. cb.normalize();
  17059. face.normal.copy(cb);
  17060. }
  17061. },
  17062. computeVertexNormals: function (areaWeighted = true) {
  17063. const vertices = new Array(this.vertices.length);
  17064. for (let v = 0, vl = this.vertices.length; v < vl; v++) {
  17065. vertices[v] = new Vector3();
  17066. }
  17067. if (areaWeighted) {
  17068. // vertex normals weighted by triangle areas
  17069. // http://www.iquilezles.org/www/articles/normals/normals.htm
  17070. const cb = new Vector3(),
  17071. ab = new Vector3();
  17072. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17073. const face = this.faces[f];
  17074. const vA = this.vertices[face.a];
  17075. const vB = this.vertices[face.b];
  17076. const vC = this.vertices[face.c];
  17077. cb.subVectors(vC, vB);
  17078. ab.subVectors(vA, vB);
  17079. cb.cross(ab);
  17080. vertices[face.a].add(cb);
  17081. vertices[face.b].add(cb);
  17082. vertices[face.c].add(cb);
  17083. }
  17084. } else {
  17085. this.computeFaceNormals();
  17086. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17087. const face = this.faces[f];
  17088. vertices[face.a].add(face.normal);
  17089. vertices[face.b].add(face.normal);
  17090. vertices[face.c].add(face.normal);
  17091. }
  17092. }
  17093. for (let v = 0, vl = this.vertices.length; v < vl; v++) {
  17094. vertices[v].normalize();
  17095. }
  17096. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17097. const face = this.faces[f];
  17098. const vertexNormals = face.vertexNormals;
  17099. if (vertexNormals.length === 3) {
  17100. vertexNormals[0].copy(vertices[face.a]);
  17101. vertexNormals[1].copy(vertices[face.b]);
  17102. vertexNormals[2].copy(vertices[face.c]);
  17103. } else {
  17104. vertexNormals[0] = vertices[face.a].clone();
  17105. vertexNormals[1] = vertices[face.b].clone();
  17106. vertexNormals[2] = vertices[face.c].clone();
  17107. }
  17108. }
  17109. if (this.faces.length > 0) {
  17110. this.normalsNeedUpdate = true;
  17111. }
  17112. },
  17113. computeFlatVertexNormals: function () {
  17114. this.computeFaceNormals();
  17115. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17116. const face = this.faces[f];
  17117. const vertexNormals = face.vertexNormals;
  17118. if (vertexNormals.length === 3) {
  17119. vertexNormals[0].copy(face.normal);
  17120. vertexNormals[1].copy(face.normal);
  17121. vertexNormals[2].copy(face.normal);
  17122. } else {
  17123. vertexNormals[0] = face.normal.clone();
  17124. vertexNormals[1] = face.normal.clone();
  17125. vertexNormals[2] = face.normal.clone();
  17126. }
  17127. }
  17128. if (this.faces.length > 0) {
  17129. this.normalsNeedUpdate = true;
  17130. }
  17131. },
  17132. computeMorphNormals: function () {
  17133. // save original normals
  17134. // - create temp variables on first access
  17135. // otherwise just copy (for faster repeated calls)
  17136. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17137. const face = this.faces[f];
  17138. if (!face.__originalFaceNormal) {
  17139. face.__originalFaceNormal = face.normal.clone();
  17140. } else {
  17141. face.__originalFaceNormal.copy(face.normal);
  17142. }
  17143. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  17144. for (let i = 0, il = face.vertexNormals.length; i < il; i++) {
  17145. if (!face.__originalVertexNormals[i]) {
  17146. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  17147. } else {
  17148. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  17149. }
  17150. }
  17151. } // use temp geometry to compute face and vertex normals for each morph
  17152. const tmpGeo = new Geometry();
  17153. tmpGeo.faces = this.faces;
  17154. for (let i = 0, il = this.morphTargets.length; i < il; i++) {
  17155. // create on first access
  17156. if (!this.morphNormals[i]) {
  17157. this.morphNormals[i] = {};
  17158. this.morphNormals[i].faceNormals = [];
  17159. this.morphNormals[i].vertexNormals = [];
  17160. const dstNormalsFace = this.morphNormals[i].faceNormals;
  17161. const dstNormalsVertex = this.morphNormals[i].vertexNormals;
  17162. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17163. const faceNormal = new Vector3();
  17164. const vertexNormals = {
  17165. a: new Vector3(),
  17166. b: new Vector3(),
  17167. c: new Vector3()
  17168. };
  17169. dstNormalsFace.push(faceNormal);
  17170. dstNormalsVertex.push(vertexNormals);
  17171. }
  17172. }
  17173. const morphNormals = this.morphNormals[i]; // set vertices to morph target
  17174. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  17175. tmpGeo.computeFaceNormals();
  17176. tmpGeo.computeVertexNormals(); // store morph normals
  17177. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17178. const face = this.faces[f];
  17179. const faceNormal = morphNormals.faceNormals[f];
  17180. const vertexNormals = morphNormals.vertexNormals[f];
  17181. faceNormal.copy(face.normal);
  17182. vertexNormals.a.copy(face.vertexNormals[0]);
  17183. vertexNormals.b.copy(face.vertexNormals[1]);
  17184. vertexNormals.c.copy(face.vertexNormals[2]);
  17185. }
  17186. } // restore original normals
  17187. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17188. const face = this.faces[f];
  17189. face.normal = face.__originalFaceNormal;
  17190. face.vertexNormals = face.__originalVertexNormals;
  17191. }
  17192. },
  17193. computeBoundingBox: function () {
  17194. if (this.boundingBox === null) {
  17195. this.boundingBox = new Box3();
  17196. }
  17197. this.boundingBox.setFromPoints(this.vertices);
  17198. },
  17199. computeBoundingSphere: function () {
  17200. if (this.boundingSphere === null) {
  17201. this.boundingSphere = new Sphere();
  17202. }
  17203. this.boundingSphere.setFromPoints(this.vertices);
  17204. },
  17205. merge: function (geometry, matrix, materialIndexOffset = 0) {
  17206. if (!(geometry && geometry.isGeometry)) {
  17207. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  17208. return;
  17209. }
  17210. let normalMatrix;
  17211. const vertexOffset = this.vertices.length,
  17212. vertices1 = this.vertices,
  17213. vertices2 = geometry.vertices,
  17214. faces1 = this.faces,
  17215. faces2 = geometry.faces,
  17216. colors1 = this.colors,
  17217. colors2 = geometry.colors;
  17218. if (matrix !== undefined) {
  17219. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  17220. } // vertices
  17221. for (let i = 0, il = vertices2.length; i < il; i++) {
  17222. const vertex = vertices2[i];
  17223. const vertexCopy = vertex.clone();
  17224. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  17225. vertices1.push(vertexCopy);
  17226. } // colors
  17227. for (let i = 0, il = colors2.length; i < il; i++) {
  17228. colors1.push(colors2[i].clone());
  17229. } // faces
  17230. for (let i = 0, il = faces2.length; i < il; i++) {
  17231. const face = faces2[i];
  17232. let normal, color;
  17233. const faceVertexNormals = face.vertexNormals,
  17234. faceVertexColors = face.vertexColors;
  17235. const faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  17236. faceCopy.normal.copy(face.normal);
  17237. if (normalMatrix !== undefined) {
  17238. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  17239. }
  17240. for (let j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  17241. normal = faceVertexNormals[j].clone();
  17242. if (normalMatrix !== undefined) {
  17243. normal.applyMatrix3(normalMatrix).normalize();
  17244. }
  17245. faceCopy.vertexNormals.push(normal);
  17246. }
  17247. faceCopy.color.copy(face.color);
  17248. for (let j = 0, jl = faceVertexColors.length; j < jl; j++) {
  17249. color = faceVertexColors[j];
  17250. faceCopy.vertexColors.push(color.clone());
  17251. }
  17252. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  17253. faces1.push(faceCopy);
  17254. } // uvs
  17255. for (let i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  17256. const faceVertexUvs2 = geometry.faceVertexUvs[i];
  17257. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  17258. for (let j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  17259. const uvs2 = faceVertexUvs2[j],
  17260. uvsCopy = [];
  17261. for (let k = 0, kl = uvs2.length; k < kl; k++) {
  17262. uvsCopy.push(uvs2[k].clone());
  17263. }
  17264. this.faceVertexUvs[i].push(uvsCopy);
  17265. }
  17266. }
  17267. },
  17268. mergeMesh: function (mesh) {
  17269. if (!(mesh && mesh.isMesh)) {
  17270. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  17271. return;
  17272. }
  17273. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  17274. this.merge(mesh.geometry, mesh.matrix);
  17275. },
  17276. /*
  17277. * Checks for duplicate vertices with hashmap.
  17278. * Duplicated vertices are removed
  17279. * and faces' vertices are updated.
  17280. */
  17281. mergeVertices: function (precisionPoints = 4) {
  17282. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  17283. const unique = [],
  17284. changes = [];
  17285. const precision = Math.pow(10, precisionPoints);
  17286. for (let i = 0, il = this.vertices.length; i < il; i++) {
  17287. const v = this.vertices[i];
  17288. const key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  17289. if (verticesMap[key] === undefined) {
  17290. verticesMap[key] = i;
  17291. unique.push(this.vertices[i]);
  17292. changes[i] = unique.length - 1;
  17293. } else {
  17294. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  17295. changes[i] = changes[verticesMap[key]];
  17296. }
  17297. } // if faces are completely degenerate after merging vertices, we
  17298. // have to remove them from the geometry.
  17299. const faceIndicesToRemove = [];
  17300. for (let i = 0, il = this.faces.length; i < il; i++) {
  17301. const face = this.faces[i];
  17302. face.a = changes[face.a];
  17303. face.b = changes[face.b];
  17304. face.c = changes[face.c];
  17305. const indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  17306. // we have to remove the face as nothing can be saved
  17307. for (let n = 0; n < 3; n++) {
  17308. if (indices[n] === indices[(n + 1) % 3]) {
  17309. faceIndicesToRemove.push(i);
  17310. break;
  17311. }
  17312. }
  17313. }
  17314. for (let i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  17315. const idx = faceIndicesToRemove[i];
  17316. this.faces.splice(idx, 1);
  17317. for (let j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  17318. this.faceVertexUvs[j].splice(idx, 1);
  17319. }
  17320. } // Use unique set of vertices
  17321. const diff = this.vertices.length - unique.length;
  17322. this.vertices = unique;
  17323. return diff;
  17324. },
  17325. setFromPoints: function (points) {
  17326. this.vertices = [];
  17327. for (let i = 0, l = points.length; i < l; i++) {
  17328. const point = points[i];
  17329. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  17330. }
  17331. return this;
  17332. },
  17333. sortFacesByMaterialIndex: function () {
  17334. const faces = this.faces;
  17335. const length = faces.length; // tag faces
  17336. for (let i = 0; i < length; i++) {
  17337. faces[i]._id = i;
  17338. } // sort faces
  17339. function materialIndexSort(a, b) {
  17340. return a.materialIndex - b.materialIndex;
  17341. }
  17342. faces.sort(materialIndexSort); // sort uvs
  17343. const uvs1 = this.faceVertexUvs[0];
  17344. const uvs2 = this.faceVertexUvs[1];
  17345. let newUvs1, newUvs2;
  17346. if (uvs1 && uvs1.length === length) newUvs1 = [];
  17347. if (uvs2 && uvs2.length === length) newUvs2 = [];
  17348. for (let i = 0; i < length; i++) {
  17349. const id = faces[i]._id;
  17350. if (newUvs1) newUvs1.push(uvs1[id]);
  17351. if (newUvs2) newUvs2.push(uvs2[id]);
  17352. }
  17353. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  17354. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  17355. },
  17356. toJSON: function () {
  17357. const data = {
  17358. metadata: {
  17359. version: 4.5,
  17360. type: 'Geometry',
  17361. generator: 'Geometry.toJSON'
  17362. }
  17363. }; // standard Geometry serialization
  17364. data.uuid = this.uuid;
  17365. data.type = this.type;
  17366. if (this.name !== '') data.name = this.name;
  17367. if (this.parameters !== undefined) {
  17368. const parameters = this.parameters;
  17369. for (const key in parameters) {
  17370. if (parameters[key] !== undefined) data[key] = parameters[key];
  17371. }
  17372. return data;
  17373. }
  17374. const vertices = [];
  17375. for (let i = 0; i < this.vertices.length; i++) {
  17376. const vertex = this.vertices[i];
  17377. vertices.push(vertex.x, vertex.y, vertex.z);
  17378. }
  17379. const faces = [];
  17380. const normals = [];
  17381. const normalsHash = {};
  17382. const colors = [];
  17383. const colorsHash = {};
  17384. const uvs = [];
  17385. const uvsHash = {};
  17386. for (let i = 0; i < this.faces.length; i++) {
  17387. const face = this.faces[i];
  17388. const hasMaterial = true;
  17389. const hasFaceUv = false; // deprecated
  17390. const hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  17391. const hasFaceNormal = face.normal.length() > 0;
  17392. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  17393. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  17394. const hasFaceVertexColor = face.vertexColors.length > 0;
  17395. let faceType = 0;
  17396. faceType = setBit(faceType, 0, 0); // isQuad
  17397. faceType = setBit(faceType, 1, hasMaterial);
  17398. faceType = setBit(faceType, 2, hasFaceUv);
  17399. faceType = setBit(faceType, 3, hasFaceVertexUv);
  17400. faceType = setBit(faceType, 4, hasFaceNormal);
  17401. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  17402. faceType = setBit(faceType, 6, hasFaceColor);
  17403. faceType = setBit(faceType, 7, hasFaceVertexColor);
  17404. faces.push(faceType);
  17405. faces.push(face.a, face.b, face.c);
  17406. faces.push(face.materialIndex);
  17407. if (hasFaceVertexUv) {
  17408. const faceVertexUvs = this.faceVertexUvs[0][i];
  17409. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  17410. }
  17411. if (hasFaceNormal) {
  17412. faces.push(getNormalIndex(face.normal));
  17413. }
  17414. if (hasFaceVertexNormal) {
  17415. const vertexNormals = face.vertexNormals;
  17416. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  17417. }
  17418. if (hasFaceColor) {
  17419. faces.push(getColorIndex(face.color));
  17420. }
  17421. if (hasFaceVertexColor) {
  17422. const vertexColors = face.vertexColors;
  17423. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  17424. }
  17425. }
  17426. function setBit(value, position, enabled) {
  17427. return enabled ? value | 1 << position : value & ~(1 << position);
  17428. }
  17429. function getNormalIndex(normal) {
  17430. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  17431. if (normalsHash[hash] !== undefined) {
  17432. return normalsHash[hash];
  17433. }
  17434. normalsHash[hash] = normals.length / 3;
  17435. normals.push(normal.x, normal.y, normal.z);
  17436. return normalsHash[hash];
  17437. }
  17438. function getColorIndex(color) {
  17439. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  17440. if (colorsHash[hash] !== undefined) {
  17441. return colorsHash[hash];
  17442. }
  17443. colorsHash[hash] = colors.length;
  17444. colors.push(color.getHex());
  17445. return colorsHash[hash];
  17446. }
  17447. function getUvIndex(uv) {
  17448. const hash = uv.x.toString() + uv.y.toString();
  17449. if (uvsHash[hash] !== undefined) {
  17450. return uvsHash[hash];
  17451. }
  17452. uvsHash[hash] = uvs.length / 2;
  17453. uvs.push(uv.x, uv.y);
  17454. return uvsHash[hash];
  17455. }
  17456. data.data = {};
  17457. data.data.vertices = vertices;
  17458. data.data.normals = normals;
  17459. if (colors.length > 0) data.data.colors = colors;
  17460. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  17461. data.data.faces = faces;
  17462. return data;
  17463. },
  17464. clone: function () {
  17465. /*
  17466. // Handle primitives
  17467. const parameters = this.parameters;
  17468. if ( parameters !== undefined ) {
  17469. const values = [];
  17470. for ( const key in parameters ) {
  17471. values.push( parameters[ key ] );
  17472. }
  17473. const geometry = Object.create( this.constructor.prototype );
  17474. this.constructor.apply( geometry, values );
  17475. return geometry;
  17476. }
  17477. return new this.constructor().copy( this );
  17478. */
  17479. return new Geometry().copy(this);
  17480. },
  17481. copy: function (source) {
  17482. // reset
  17483. this.vertices = [];
  17484. this.colors = [];
  17485. this.faces = [];
  17486. this.faceVertexUvs = [[]];
  17487. this.morphTargets = [];
  17488. this.morphNormals = [];
  17489. this.skinWeights = [];
  17490. this.skinIndices = [];
  17491. this.lineDistances = [];
  17492. this.boundingBox = null;
  17493. this.boundingSphere = null; // name
  17494. this.name = source.name; // vertices
  17495. const vertices = source.vertices;
  17496. for (let i = 0, il = vertices.length; i < il; i++) {
  17497. this.vertices.push(vertices[i].clone());
  17498. } // colors
  17499. const colors = source.colors;
  17500. for (let i = 0, il = colors.length; i < il; i++) {
  17501. this.colors.push(colors[i].clone());
  17502. } // faces
  17503. const faces = source.faces;
  17504. for (let i = 0, il = faces.length; i < il; i++) {
  17505. this.faces.push(faces[i].clone());
  17506. } // face vertex uvs
  17507. for (let i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  17508. const faceVertexUvs = source.faceVertexUvs[i];
  17509. if (this.faceVertexUvs[i] === undefined) {
  17510. this.faceVertexUvs[i] = [];
  17511. }
  17512. for (let j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  17513. const uvs = faceVertexUvs[j],
  17514. uvsCopy = [];
  17515. for (let k = 0, kl = uvs.length; k < kl; k++) {
  17516. const uv = uvs[k];
  17517. uvsCopy.push(uv.clone());
  17518. }
  17519. this.faceVertexUvs[i].push(uvsCopy);
  17520. }
  17521. } // morph targets
  17522. const morphTargets = source.morphTargets;
  17523. for (let i = 0, il = morphTargets.length; i < il; i++) {
  17524. const morphTarget = {};
  17525. morphTarget.name = morphTargets[i].name; // vertices
  17526. if (morphTargets[i].vertices !== undefined) {
  17527. morphTarget.vertices = [];
  17528. for (let j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  17529. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  17530. }
  17531. } // normals
  17532. if (morphTargets[i].normals !== undefined) {
  17533. morphTarget.normals = [];
  17534. for (let j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  17535. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  17536. }
  17537. }
  17538. this.morphTargets.push(morphTarget);
  17539. } // morph normals
  17540. const morphNormals = source.morphNormals;
  17541. for (let i = 0, il = morphNormals.length; i < il; i++) {
  17542. const morphNormal = {}; // vertex normals
  17543. if (morphNormals[i].vertexNormals !== undefined) {
  17544. morphNormal.vertexNormals = [];
  17545. for (let j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  17546. const srcVertexNormal = morphNormals[i].vertexNormals[j];
  17547. const destVertexNormal = {};
  17548. destVertexNormal.a = srcVertexNormal.a.clone();
  17549. destVertexNormal.b = srcVertexNormal.b.clone();
  17550. destVertexNormal.c = srcVertexNormal.c.clone();
  17551. morphNormal.vertexNormals.push(destVertexNormal);
  17552. }
  17553. } // face normals
  17554. if (morphNormals[i].faceNormals !== undefined) {
  17555. morphNormal.faceNormals = [];
  17556. for (let j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  17557. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  17558. }
  17559. }
  17560. this.morphNormals.push(morphNormal);
  17561. } // skin weights
  17562. const skinWeights = source.skinWeights;
  17563. for (let i = 0, il = skinWeights.length; i < il; i++) {
  17564. this.skinWeights.push(skinWeights[i].clone());
  17565. } // skin indices
  17566. const skinIndices = source.skinIndices;
  17567. for (let i = 0, il = skinIndices.length; i < il; i++) {
  17568. this.skinIndices.push(skinIndices[i].clone());
  17569. } // line distances
  17570. const lineDistances = source.lineDistances;
  17571. for (let i = 0, il = lineDistances.length; i < il; i++) {
  17572. this.lineDistances.push(lineDistances[i]);
  17573. } // bounding box
  17574. const boundingBox = source.boundingBox;
  17575. if (boundingBox !== null) {
  17576. this.boundingBox = boundingBox.clone();
  17577. } // bounding sphere
  17578. const boundingSphere = source.boundingSphere;
  17579. if (boundingSphere !== null) {
  17580. this.boundingSphere = boundingSphere.clone();
  17581. } // update flags
  17582. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17583. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17584. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17585. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17586. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17587. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17588. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17589. return this;
  17590. },
  17591. dispose: function () {
  17592. this.dispatchEvent({
  17593. type: 'dispose'
  17594. });
  17595. }
  17596. });
  17597. class BoxGeometry extends Geometry {
  17598. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  17599. super();
  17600. this.type = 'BoxGeometry';
  17601. this.parameters = {
  17602. width: width,
  17603. height: height,
  17604. depth: depth,
  17605. widthSegments: widthSegments,
  17606. heightSegments: heightSegments,
  17607. depthSegments: depthSegments
  17608. };
  17609. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  17610. this.mergeVertices();
  17611. }
  17612. }
  17613. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  17614. class CircleBufferGeometry extends BufferGeometry {
  17615. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17616. super();
  17617. this.type = 'CircleBufferGeometry';
  17618. this.parameters = {
  17619. radius: radius,
  17620. segments: segments,
  17621. thetaStart: thetaStart,
  17622. thetaLength: thetaLength
  17623. };
  17624. segments = Math.max(3, segments); // buffers
  17625. const indices = [];
  17626. const vertices = [];
  17627. const normals = [];
  17628. const uvs = []; // helper variables
  17629. const vertex = new Vector3();
  17630. const uv = new Vector2(); // center point
  17631. vertices.push(0, 0, 0);
  17632. normals.push(0, 0, 1);
  17633. uvs.push(0.5, 0.5);
  17634. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17635. const segment = thetaStart + s / segments * thetaLength; // vertex
  17636. vertex.x = radius * Math.cos(segment);
  17637. vertex.y = radius * Math.sin(segment);
  17638. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17639. normals.push(0, 0, 1); // uvs
  17640. uv.x = (vertices[i] / radius + 1) / 2;
  17641. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17642. uvs.push(uv.x, uv.y);
  17643. } // indices
  17644. for (let i = 1; i <= segments; i++) {
  17645. indices.push(i, i + 1, 0);
  17646. } // build geometry
  17647. this.setIndex(indices);
  17648. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17649. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17650. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17651. }
  17652. }
  17653. exports.CircleBufferGeometry = CircleBufferGeometry;
  17654. class CircleGeometry extends Geometry {
  17655. constructor(radius, segments, thetaStart, thetaLength) {
  17656. super();
  17657. this.type = 'CircleGeometry';
  17658. this.parameters = {
  17659. radius: radius,
  17660. segments: segments,
  17661. thetaStart: thetaStart,
  17662. thetaLength: thetaLength
  17663. };
  17664. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  17665. this.mergeVertices();
  17666. }
  17667. }
  17668. exports.CircleGeometry = CircleGeometry;
  17669. class CylinderBufferGeometry extends BufferGeometry {
  17670. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17671. super();
  17672. this.type = 'CylinderBufferGeometry';
  17673. this.parameters = {
  17674. radiusTop: radiusTop,
  17675. radiusBottom: radiusBottom,
  17676. height: height,
  17677. radialSegments: radialSegments,
  17678. heightSegments: heightSegments,
  17679. openEnded: openEnded,
  17680. thetaStart: thetaStart,
  17681. thetaLength: thetaLength
  17682. };
  17683. const scope = this;
  17684. radialSegments = Math.floor(radialSegments);
  17685. heightSegments = Math.floor(heightSegments); // buffers
  17686. const indices = [];
  17687. const vertices = [];
  17688. const normals = [];
  17689. const uvs = []; // helper variables
  17690. let index = 0;
  17691. const indexArray = [];
  17692. const halfHeight = height / 2;
  17693. let groupStart = 0; // generate geometry
  17694. generateTorso();
  17695. if (openEnded === false) {
  17696. if (radiusTop > 0) generateCap(true);
  17697. if (radiusBottom > 0) generateCap(false);
  17698. } // build geometry
  17699. this.setIndex(indices);
  17700. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17701. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17702. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17703. function generateTorso() {
  17704. const normal = new Vector3();
  17705. const vertex = new Vector3();
  17706. let groupCount = 0; // this will be used to calculate the normal
  17707. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17708. for (let y = 0; y <= heightSegments; y++) {
  17709. const indexRow = [];
  17710. const v = y / heightSegments; // calculate the radius of the current row
  17711. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17712. for (let x = 0; x <= radialSegments; x++) {
  17713. const u = x / radialSegments;
  17714. const theta = u * thetaLength + thetaStart;
  17715. const sinTheta = Math.sin(theta);
  17716. const cosTheta = Math.cos(theta); // vertex
  17717. vertex.x = radius * sinTheta;
  17718. vertex.y = -v * height + halfHeight;
  17719. vertex.z = radius * cosTheta;
  17720. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17721. normal.set(sinTheta, slope, cosTheta).normalize();
  17722. normals.push(normal.x, normal.y, normal.z); // uv
  17723. uvs.push(u, 1 - v); // save index of vertex in respective row
  17724. indexRow.push(index++);
  17725. } // now save vertices of the row in our index array
  17726. indexArray.push(indexRow);
  17727. } // generate indices
  17728. for (let x = 0; x < radialSegments; x++) {
  17729. for (let y = 0; y < heightSegments; y++) {
  17730. // we use the index array to access the correct indices
  17731. const a = indexArray[y][x];
  17732. const b = indexArray[y + 1][x];
  17733. const c = indexArray[y + 1][x + 1];
  17734. const d = indexArray[y][x + 1]; // faces
  17735. indices.push(a, b, d);
  17736. indices.push(b, c, d); // update group counter
  17737. groupCount += 6;
  17738. }
  17739. } // add a group to the geometry. this will ensure multi material support
  17740. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17741. groupStart += groupCount;
  17742. }
  17743. function generateCap(top) {
  17744. // save the index of the first center vertex
  17745. const centerIndexStart = index;
  17746. const uv = new Vector2();
  17747. const vertex = new Vector3();
  17748. let groupCount = 0;
  17749. const radius = top === true ? radiusTop : radiusBottom;
  17750. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17751. // because the geometry needs one set of uvs per face,
  17752. // we must generate a center vertex per face/segment
  17753. for (let x = 1; x <= radialSegments; x++) {
  17754. // vertex
  17755. vertices.push(0, halfHeight * sign, 0); // normal
  17756. normals.push(0, sign, 0); // uv
  17757. uvs.push(0.5, 0.5); // increase index
  17758. index++;
  17759. } // save the index of the last center vertex
  17760. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17761. for (let x = 0; x <= radialSegments; x++) {
  17762. const u = x / radialSegments;
  17763. const theta = u * thetaLength + thetaStart;
  17764. const cosTheta = Math.cos(theta);
  17765. const sinTheta = Math.sin(theta); // vertex
  17766. vertex.x = radius * sinTheta;
  17767. vertex.y = halfHeight * sign;
  17768. vertex.z = radius * cosTheta;
  17769. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17770. normals.push(0, sign, 0); // uv
  17771. uv.x = cosTheta * 0.5 + 0.5;
  17772. uv.y = sinTheta * 0.5 * sign + 0.5;
  17773. uvs.push(uv.x, uv.y); // increase index
  17774. index++;
  17775. } // generate indices
  17776. for (let x = 0; x < radialSegments; x++) {
  17777. const c = centerIndexStart + x;
  17778. const i = centerIndexEnd + x;
  17779. if (top === true) {
  17780. // face top
  17781. indices.push(i, i + 1, c);
  17782. } else {
  17783. // face bottom
  17784. indices.push(i + 1, i, c);
  17785. }
  17786. groupCount += 3;
  17787. } // add a group to the geometry. this will ensure multi material support
  17788. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17789. groupStart += groupCount;
  17790. }
  17791. }
  17792. }
  17793. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  17794. class CylinderGeometry extends Geometry {
  17795. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  17796. super();
  17797. this.type = 'CylinderGeometry';
  17798. this.parameters = {
  17799. radiusTop: radiusTop,
  17800. radiusBottom: radiusBottom,
  17801. height: height,
  17802. radialSegments: radialSegments,
  17803. heightSegments: heightSegments,
  17804. openEnded: openEnded,
  17805. thetaStart: thetaStart,
  17806. thetaLength: thetaLength
  17807. };
  17808. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  17809. this.mergeVertices();
  17810. }
  17811. }
  17812. exports.CylinderGeometry = CylinderGeometry;
  17813. class ConeGeometry extends CylinderGeometry {
  17814. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  17815. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17816. this.type = 'ConeGeometry';
  17817. this.parameters = {
  17818. radius: radius,
  17819. height: height,
  17820. radialSegments: radialSegments,
  17821. heightSegments: heightSegments,
  17822. openEnded: openEnded,
  17823. thetaStart: thetaStart,
  17824. thetaLength: thetaLength
  17825. };
  17826. }
  17827. }
  17828. exports.ConeGeometry = ConeGeometry;
  17829. class ConeBufferGeometry extends CylinderBufferGeometry {
  17830. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17831. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17832. this.type = 'ConeBufferGeometry';
  17833. this.parameters = {
  17834. radius: radius,
  17835. height: height,
  17836. radialSegments: radialSegments,
  17837. heightSegments: heightSegments,
  17838. openEnded: openEnded,
  17839. thetaStart: thetaStart,
  17840. thetaLength: thetaLength
  17841. };
  17842. }
  17843. }
  17844. exports.ConeBufferGeometry = ConeBufferGeometry;
  17845. class PolyhedronBufferGeometry extends BufferGeometry {
  17846. constructor(vertices, indices, radius = 1, detail = 0) {
  17847. super();
  17848. this.type = 'PolyhedronBufferGeometry';
  17849. this.parameters = {
  17850. vertices: vertices,
  17851. indices: indices,
  17852. radius: radius,
  17853. detail: detail
  17854. }; // default buffer data
  17855. const vertexBuffer = [];
  17856. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17857. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17858. applyRadius(radius); // finally, create the uv data
  17859. generateUVs(); // build non-indexed geometry
  17860. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17861. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17862. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17863. if (detail === 0) {
  17864. this.computeVertexNormals(); // flat normals
  17865. } else {
  17866. this.normalizeNormals(); // smooth normals
  17867. } // helper functions
  17868. function subdivide(detail) {
  17869. const a = new Vector3();
  17870. const b = new Vector3();
  17871. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17872. for (let i = 0; i < indices.length; i += 3) {
  17873. // get the vertices of the face
  17874. getVertexByIndex(indices[i + 0], a);
  17875. getVertexByIndex(indices[i + 1], b);
  17876. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17877. subdivideFace(a, b, c, detail);
  17878. }
  17879. }
  17880. function subdivideFace(a, b, c, detail) {
  17881. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17882. const v = []; // construct all of the vertices for this subdivision
  17883. for (let i = 0; i <= cols; i++) {
  17884. v[i] = [];
  17885. const aj = a.clone().lerp(c, i / cols);
  17886. const bj = b.clone().lerp(c, i / cols);
  17887. const rows = cols - i;
  17888. for (let j = 0; j <= rows; j++) {
  17889. if (j === 0 && i === cols) {
  17890. v[i][j] = aj;
  17891. } else {
  17892. v[i][j] = aj.clone().lerp(bj, j / rows);
  17893. }
  17894. }
  17895. } // construct all of the faces
  17896. for (let i = 0; i < cols; i++) {
  17897. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17898. const k = Math.floor(j / 2);
  17899. if (j % 2 === 0) {
  17900. pushVertex(v[i][k + 1]);
  17901. pushVertex(v[i + 1][k]);
  17902. pushVertex(v[i][k]);
  17903. } else {
  17904. pushVertex(v[i][k + 1]);
  17905. pushVertex(v[i + 1][k + 1]);
  17906. pushVertex(v[i + 1][k]);
  17907. }
  17908. }
  17909. }
  17910. }
  17911. function applyRadius(radius) {
  17912. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17913. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17914. vertex.x = vertexBuffer[i + 0];
  17915. vertex.y = vertexBuffer[i + 1];
  17916. vertex.z = vertexBuffer[i + 2];
  17917. vertex.normalize().multiplyScalar(radius);
  17918. vertexBuffer[i + 0] = vertex.x;
  17919. vertexBuffer[i + 1] = vertex.y;
  17920. vertexBuffer[i + 2] = vertex.z;
  17921. }
  17922. }
  17923. function generateUVs() {
  17924. const vertex = new Vector3();
  17925. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17926. vertex.x = vertexBuffer[i + 0];
  17927. vertex.y = vertexBuffer[i + 1];
  17928. vertex.z = vertexBuffer[i + 2];
  17929. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17930. const v = inclination(vertex) / Math.PI + 0.5;
  17931. uvBuffer.push(u, 1 - v);
  17932. }
  17933. correctUVs();
  17934. correctSeam();
  17935. }
  17936. function correctSeam() {
  17937. // handle case when face straddles the seam, see #3269
  17938. for (let i = 0; i < uvBuffer.length; i += 6) {
  17939. // uv data of a single face
  17940. const x0 = uvBuffer[i + 0];
  17941. const x1 = uvBuffer[i + 2];
  17942. const x2 = uvBuffer[i + 4];
  17943. const max = Math.max(x0, x1, x2);
  17944. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17945. if (max > 0.9 && min < 0.1) {
  17946. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17947. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17948. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17949. }
  17950. }
  17951. }
  17952. function pushVertex(vertex) {
  17953. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17954. }
  17955. function getVertexByIndex(index, vertex) {
  17956. const stride = index * 3;
  17957. vertex.x = vertices[stride + 0];
  17958. vertex.y = vertices[stride + 1];
  17959. vertex.z = vertices[stride + 2];
  17960. }
  17961. function correctUVs() {
  17962. const a = new Vector3();
  17963. const b = new Vector3();
  17964. const c = new Vector3();
  17965. const centroid = new Vector3();
  17966. const uvA = new Vector2();
  17967. const uvB = new Vector2();
  17968. const uvC = new Vector2();
  17969. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17970. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17971. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17972. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17973. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17974. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17975. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17976. centroid.copy(a).add(b).add(c).divideScalar(3);
  17977. const azi = azimuth(centroid);
  17978. correctUV(uvA, j + 0, a, azi);
  17979. correctUV(uvB, j + 2, b, azi);
  17980. correctUV(uvC, j + 4, c, azi);
  17981. }
  17982. }
  17983. function correctUV(uv, stride, vector, azimuth) {
  17984. if (azimuth < 0 && uv.x === 1) {
  17985. uvBuffer[stride] = uv.x - 1;
  17986. }
  17987. if (vector.x === 0 && vector.z === 0) {
  17988. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17989. }
  17990. } // Angle around the Y axis, counter-clockwise when looking from above.
  17991. function azimuth(vector) {
  17992. return Math.atan2(vector.z, -vector.x);
  17993. } // Angle above the XZ plane.
  17994. function inclination(vector) {
  17995. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17996. }
  17997. }
  17998. }
  17999. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  18000. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  18001. constructor(radius = 1, detail = 0) {
  18002. const t = (1 + Math.sqrt(5)) / 2;
  18003. const r = 1 / t;
  18004. const vertices = [// (±1, ±1, ±1)
  18005. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  18006. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18007. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18008. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18009. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  18010. super(vertices, indices, radius, detail);
  18011. this.type = 'DodecahedronBufferGeometry';
  18012. this.parameters = {
  18013. radius: radius,
  18014. detail: detail
  18015. };
  18016. }
  18017. }
  18018. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  18019. class DodecahedronGeometry extends Geometry {
  18020. constructor(radius, detail) {
  18021. super();
  18022. this.type = 'DodecahedronGeometry';
  18023. this.parameters = {
  18024. radius: radius,
  18025. detail: detail
  18026. };
  18027. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18028. this.mergeVertices();
  18029. }
  18030. }
  18031. exports.DodecahedronGeometry = DodecahedronGeometry;
  18032. const _v0$2 = new Vector3();
  18033. const _v1$5 = new Vector3();
  18034. const _normal$1 = new Vector3();
  18035. const _triangle = new Triangle();
  18036. class EdgesGeometry extends BufferGeometry {
  18037. constructor(geometry, thresholdAngle) {
  18038. super();
  18039. this.type = 'EdgesGeometry';
  18040. this.parameters = {
  18041. thresholdAngle: thresholdAngle
  18042. };
  18043. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  18044. if (geometry.isGeometry) {
  18045. geometry = new BufferGeometry().fromGeometry(geometry);
  18046. }
  18047. const precisionPoints = 4;
  18048. const precision = Math.pow(10, precisionPoints);
  18049. const thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  18050. const indexAttr = geometry.getIndex();
  18051. const positionAttr = geometry.getAttribute('position');
  18052. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18053. const indexArr = [0, 0, 0];
  18054. const vertKeys = ['a', 'b', 'c'];
  18055. const hashes = new Array(3);
  18056. const edgeData = {};
  18057. const vertices = [];
  18058. for (let i = 0; i < indexCount; i += 3) {
  18059. if (indexAttr) {
  18060. indexArr[0] = indexAttr.getX(i);
  18061. indexArr[1] = indexAttr.getX(i + 1);
  18062. indexArr[2] = indexAttr.getX(i + 2);
  18063. } else {
  18064. indexArr[0] = i;
  18065. indexArr[1] = i + 1;
  18066. indexArr[2] = i + 2;
  18067. }
  18068. const {
  18069. a,
  18070. b,
  18071. c
  18072. } = _triangle;
  18073. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18074. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18075. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18076. _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
  18077. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18078. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18079. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18080. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18081. continue;
  18082. } // iterate over every edge
  18083. for (let j = 0; j < 3; j++) {
  18084. // get the first and next vertex making up the edge
  18085. const jNext = (j + 1) % 3;
  18086. const vecHash0 = hashes[j];
  18087. const vecHash1 = hashes[jNext];
  18088. const v0 = _triangle[vertKeys[j]];
  18089. const v1 = _triangle[vertKeys[jNext]];
  18090. const hash = `${vecHash0}_${vecHash1}`;
  18091. const reverseHash = `${vecHash1}_${vecHash0}`;
  18092. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18093. // if we found a sibling edge add it into the vertex array if
  18094. // it meets the angle threshold and delete the edge from the map.
  18095. if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18096. vertices.push(v0.x, v0.y, v0.z);
  18097. vertices.push(v1.x, v1.y, v1.z);
  18098. }
  18099. edgeData[reverseHash] = null;
  18100. } else if (!(hash in edgeData)) {
  18101. // if we've already got an edge here then skip adding a new one
  18102. edgeData[hash] = {
  18103. index0: indexArr[j],
  18104. index1: indexArr[jNext],
  18105. normal: _normal$1.clone()
  18106. };
  18107. }
  18108. }
  18109. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18110. for (const key in edgeData) {
  18111. if (edgeData[key]) {
  18112. const {
  18113. index0,
  18114. index1
  18115. } = edgeData[key];
  18116. _v0$2.fromBufferAttribute(positionAttr, index0);
  18117. _v1$5.fromBufferAttribute(positionAttr, index1);
  18118. vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
  18119. vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
  18120. }
  18121. }
  18122. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18123. }
  18124. }
  18125. /**
  18126. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18127. */
  18128. exports.EdgesGeometry = EdgesGeometry;
  18129. const Earcut = {
  18130. triangulate: function (data, holeIndices, dim) {
  18131. dim = dim || 2;
  18132. const hasHoles = holeIndices && holeIndices.length;
  18133. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  18134. let outerNode = linkedList(data, 0, outerLen, dim, true);
  18135. const triangles = [];
  18136. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18137. let minX, minY, maxX, maxY, x, y, invSize;
  18138. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18139. if (data.length > 80 * dim) {
  18140. minX = maxX = data[0];
  18141. minY = maxY = data[1];
  18142. for (let i = dim; i < outerLen; i += dim) {
  18143. x = data[i];
  18144. y = data[i + 1];
  18145. if (x < minX) minX = x;
  18146. if (y < minY) minY = y;
  18147. if (x > maxX) maxX = x;
  18148. if (y > maxY) maxY = y;
  18149. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18150. invSize = Math.max(maxX - minX, maxY - minY);
  18151. invSize = invSize !== 0 ? 1 / invSize : 0;
  18152. }
  18153. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18154. return triangles;
  18155. }
  18156. }; // create a circular doubly linked list from polygon points in the specified winding order
  18157. function linkedList(data, start, end, dim, clockwise) {
  18158. let i, last;
  18159. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18160. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18161. } else {
  18162. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18163. }
  18164. if (last && equals(last, last.next)) {
  18165. removeNode(last);
  18166. last = last.next;
  18167. }
  18168. return last;
  18169. } // eliminate colinear or duplicate points
  18170. function filterPoints(start, end) {
  18171. if (!start) return start;
  18172. if (!end) end = start;
  18173. let p = start,
  18174. again;
  18175. do {
  18176. again = false;
  18177. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18178. removeNode(p);
  18179. p = end = p.prev;
  18180. if (p === p.next) break;
  18181. again = true;
  18182. } else {
  18183. p = p.next;
  18184. }
  18185. } while (again || p !== end);
  18186. return end;
  18187. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18188. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18189. if (!ear) return; // interlink polygon nodes in z-order
  18190. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18191. let stop = ear,
  18192. prev,
  18193. next; // iterate through ears, slicing them one by one
  18194. while (ear.prev !== ear.next) {
  18195. prev = ear.prev;
  18196. next = ear.next;
  18197. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18198. // cut off the triangle
  18199. triangles.push(prev.i / dim);
  18200. triangles.push(ear.i / dim);
  18201. triangles.push(next.i / dim);
  18202. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18203. ear = next.next;
  18204. stop = next.next;
  18205. continue;
  18206. }
  18207. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18208. if (ear === stop) {
  18209. // try filtering points and slicing again
  18210. if (!pass) {
  18211. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18212. } else if (pass === 1) {
  18213. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  18214. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18215. } else if (pass === 2) {
  18216. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18217. }
  18218. break;
  18219. }
  18220. }
  18221. } // check whether a polygon node forms a valid ear with adjacent nodes
  18222. function isEar(ear) {
  18223. const a = ear.prev,
  18224. b = ear,
  18225. c = ear.next;
  18226. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18227. // now make sure we don't have other points inside the potential ear
  18228. let p = ear.next.next;
  18229. while (p !== ear.prev) {
  18230. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18231. p = p.next;
  18232. }
  18233. return true;
  18234. }
  18235. function isEarHashed(ear, minX, minY, invSize) {
  18236. const a = ear.prev,
  18237. b = ear,
  18238. c = ear.next;
  18239. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18240. // triangle bbox; min & max are calculated like this for speed
  18241. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18242. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18243. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18244. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  18245. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18246. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18247. let p = ear.prevZ,
  18248. n = ear.nextZ; // look for points inside the triangle in both directions
  18249. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18250. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18251. p = p.prevZ;
  18252. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18253. n = n.nextZ;
  18254. } // look for remaining points in decreasing z-order
  18255. while (p && p.z >= minZ) {
  18256. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18257. p = p.prevZ;
  18258. } // look for remaining points in increasing z-order
  18259. while (n && n.z <= maxZ) {
  18260. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18261. n = n.nextZ;
  18262. }
  18263. return true;
  18264. } // go through all polygon nodes and cure small local self-intersections
  18265. function cureLocalIntersections(start, triangles, dim) {
  18266. let p = start;
  18267. do {
  18268. const a = p.prev,
  18269. b = p.next.next;
  18270. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18271. triangles.push(a.i / dim);
  18272. triangles.push(p.i / dim);
  18273. triangles.push(b.i / dim); // remove two nodes involved
  18274. removeNode(p);
  18275. removeNode(p.next);
  18276. p = start = b;
  18277. }
  18278. p = p.next;
  18279. } while (p !== start);
  18280. return filterPoints(p);
  18281. } // try splitting polygon into two and triangulate them independently
  18282. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18283. // look for a valid diagonal that divides the polygon into two
  18284. let a = start;
  18285. do {
  18286. let b = a.next.next;
  18287. while (b !== a.prev) {
  18288. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18289. // split the polygon in two by the diagonal
  18290. let c = splitPolygon(a, b); // filter colinear points around the cuts
  18291. a = filterPoints(a, a.next);
  18292. c = filterPoints(c, c.next); // run earcut on each half
  18293. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18294. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18295. return;
  18296. }
  18297. b = b.next;
  18298. }
  18299. a = a.next;
  18300. } while (a !== start);
  18301. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18302. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18303. const queue = [];
  18304. let i, len, start, end, list;
  18305. for (i = 0, len = holeIndices.length; i < len; i++) {
  18306. start = holeIndices[i] * dim;
  18307. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18308. list = linkedList(data, start, end, dim, false);
  18309. if (list === list.next) list.steiner = true;
  18310. queue.push(getLeftmost(list));
  18311. }
  18312. queue.sort(compareX); // process holes from left to right
  18313. for (i = 0; i < queue.length; i++) {
  18314. eliminateHole(queue[i], outerNode);
  18315. outerNode = filterPoints(outerNode, outerNode.next);
  18316. }
  18317. return outerNode;
  18318. }
  18319. function compareX(a, b) {
  18320. return a.x - b.x;
  18321. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18322. function eliminateHole(hole, outerNode) {
  18323. outerNode = findHoleBridge(hole, outerNode);
  18324. if (outerNode) {
  18325. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  18326. filterPoints(outerNode, outerNode.next);
  18327. filterPoints(b, b.next);
  18328. }
  18329. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18330. function findHoleBridge(hole, outerNode) {
  18331. let p = outerNode;
  18332. const hx = hole.x;
  18333. const hy = hole.y;
  18334. let qx = -Infinity,
  18335. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18336. // segment's endpoint with lesser x will be potential connection point
  18337. do {
  18338. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18339. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18340. if (x <= hx && x > qx) {
  18341. qx = x;
  18342. if (x === hx) {
  18343. if (hy === p.y) return p;
  18344. if (hy === p.next.y) return p.next;
  18345. }
  18346. m = p.x < p.next.x ? p : p.next;
  18347. }
  18348. }
  18349. p = p.next;
  18350. } while (p !== outerNode);
  18351. if (!m) return null;
  18352. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  18353. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18354. // if there are no points found, we have a valid connection;
  18355. // otherwise choose the point of the minimum angle with the ray as connection point
  18356. const stop = m,
  18357. mx = m.x,
  18358. my = m.y;
  18359. let tanMin = Infinity,
  18360. tan;
  18361. p = m;
  18362. do {
  18363. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  18364. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18365. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  18366. m = p;
  18367. tanMin = tan;
  18368. }
  18369. }
  18370. p = p.next;
  18371. } while (p !== stop);
  18372. return m;
  18373. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  18374. function sectorContainsSector(m, p) {
  18375. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  18376. } // interlink polygon nodes in z-order
  18377. function indexCurve(start, minX, minY, invSize) {
  18378. let p = start;
  18379. do {
  18380. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18381. p.prevZ = p.prev;
  18382. p.nextZ = p.next;
  18383. p = p.next;
  18384. } while (p !== start);
  18385. p.prevZ.nextZ = null;
  18386. p.prevZ = null;
  18387. sortLinked(p);
  18388. } // Simon Tatham's linked list merge sort algorithm
  18389. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18390. function sortLinked(list) {
  18391. let i,
  18392. p,
  18393. q,
  18394. e,
  18395. tail,
  18396. numMerges,
  18397. pSize,
  18398. qSize,
  18399. inSize = 1;
  18400. do {
  18401. p = list;
  18402. list = null;
  18403. tail = null;
  18404. numMerges = 0;
  18405. while (p) {
  18406. numMerges++;
  18407. q = p;
  18408. pSize = 0;
  18409. for (i = 0; i < inSize; i++) {
  18410. pSize++;
  18411. q = q.nextZ;
  18412. if (!q) break;
  18413. }
  18414. qSize = inSize;
  18415. while (pSize > 0 || qSize > 0 && q) {
  18416. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18417. e = p;
  18418. p = p.nextZ;
  18419. pSize--;
  18420. } else {
  18421. e = q;
  18422. q = q.nextZ;
  18423. qSize--;
  18424. }
  18425. if (tail) tail.nextZ = e;else list = e;
  18426. e.prevZ = tail;
  18427. tail = e;
  18428. }
  18429. p = q;
  18430. }
  18431. tail.nextZ = null;
  18432. inSize *= 2;
  18433. } while (numMerges > 1);
  18434. return list;
  18435. } // z-order of a point given coords and inverse of the longer side of data bbox
  18436. function zOrder(x, y, minX, minY, invSize) {
  18437. // coords are transformed into non-negative 15-bit integer range
  18438. x = 32767 * (x - minX) * invSize;
  18439. y = 32767 * (y - minY) * invSize;
  18440. x = (x | x << 8) & 0x00FF00FF;
  18441. x = (x | x << 4) & 0x0F0F0F0F;
  18442. x = (x | x << 2) & 0x33333333;
  18443. x = (x | x << 1) & 0x55555555;
  18444. y = (y | y << 8) & 0x00FF00FF;
  18445. y = (y | y << 4) & 0x0F0F0F0F;
  18446. y = (y | y << 2) & 0x33333333;
  18447. y = (y | y << 1) & 0x55555555;
  18448. return x | y << 1;
  18449. } // find the leftmost node of a polygon ring
  18450. function getLeftmost(start) {
  18451. let p = start,
  18452. leftmost = start;
  18453. do {
  18454. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18455. p = p.next;
  18456. } while (p !== start);
  18457. return leftmost;
  18458. } // check if a point lies within a convex triangle
  18459. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18460. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  18461. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18462. function isValidDiagonal(a, b) {
  18463. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  18464. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  18465. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  18466. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  18467. } // signed area of a triangle
  18468. function area(p, q, r) {
  18469. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18470. } // check if two points are equal
  18471. function equals(p1, p2) {
  18472. return p1.x === p2.x && p1.y === p2.y;
  18473. } // check if two segments intersect
  18474. function intersects(p1, q1, p2, q2) {
  18475. const o1 = sign(area(p1, q1, p2));
  18476. const o2 = sign(area(p1, q1, q2));
  18477. const o3 = sign(area(p2, q2, p1));
  18478. const o4 = sign(area(p2, q2, q1));
  18479. if (o1 !== o2 && o3 !== o4) return true; // general case
  18480. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18481. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18482. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18483. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18484. return false;
  18485. } // for collinear points p, q, r, check if point q lies on segment pr
  18486. function onSegment(p, q, r) {
  18487. 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);
  18488. }
  18489. function sign(num) {
  18490. return num > 0 ? 1 : num < 0 ? -1 : 0;
  18491. } // check if a polygon diagonal intersects any polygon segments
  18492. function intersectsPolygon(a, b) {
  18493. let p = a;
  18494. do {
  18495. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  18496. p = p.next;
  18497. } while (p !== a);
  18498. return false;
  18499. } // check if a polygon diagonal is locally inside the polygon
  18500. function locallyInside(a, b) {
  18501. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  18502. } // check if the middle point of a polygon diagonal is inside the polygon
  18503. function middleInside(a, b) {
  18504. let p = a,
  18505. inside = false;
  18506. const px = (a.x + b.x) / 2,
  18507. py = (a.y + b.y) / 2;
  18508. do {
  18509. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  18510. p = p.next;
  18511. } while (p !== a);
  18512. return inside;
  18513. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18514. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18515. function splitPolygon(a, b) {
  18516. const a2 = new Node(a.i, a.x, a.y),
  18517. b2 = new Node(b.i, b.x, b.y),
  18518. an = a.next,
  18519. bp = b.prev;
  18520. a.next = b;
  18521. b.prev = a;
  18522. a2.next = an;
  18523. an.prev = a2;
  18524. b2.next = a2;
  18525. a2.prev = b2;
  18526. bp.next = b2;
  18527. b2.prev = bp;
  18528. return b2;
  18529. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18530. function insertNode(i, x, y, last) {
  18531. const p = new Node(i, x, y);
  18532. if (!last) {
  18533. p.prev = p;
  18534. p.next = p;
  18535. } else {
  18536. p.next = last.next;
  18537. p.prev = last;
  18538. last.next.prev = p;
  18539. last.next = p;
  18540. }
  18541. return p;
  18542. }
  18543. function removeNode(p) {
  18544. p.next.prev = p.prev;
  18545. p.prev.next = p.next;
  18546. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18547. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18548. }
  18549. function Node(i, x, y) {
  18550. // vertex index in coordinates array
  18551. this.i = i; // vertex coordinates
  18552. this.x = x;
  18553. this.y = y; // previous and next vertex nodes in a polygon ring
  18554. this.prev = null;
  18555. this.next = null; // z-order curve value
  18556. this.z = null; // previous and next nodes in z-order
  18557. this.prevZ = null;
  18558. this.nextZ = null; // indicates whether this is a steiner point
  18559. this.steiner = false;
  18560. }
  18561. function signedArea(data, start, end, dim) {
  18562. let sum = 0;
  18563. for (let i = start, j = end - dim; i < end; i += dim) {
  18564. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18565. j = i;
  18566. }
  18567. return sum;
  18568. }
  18569. const ShapeUtils = {
  18570. // calculate area of the contour polygon
  18571. area: function (contour) {
  18572. const n = contour.length;
  18573. let a = 0.0;
  18574. for (let p = n - 1, q = 0; q < n; p = q++) {
  18575. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18576. }
  18577. return a * 0.5;
  18578. },
  18579. isClockWise: function (pts) {
  18580. return ShapeUtils.area(pts) < 0;
  18581. },
  18582. triangulateShape: function (contour, holes) {
  18583. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18584. const holeIndices = []; // array of hole indices
  18585. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18586. removeDupEndPts(contour);
  18587. addContour(vertices, contour); //
  18588. let holeIndex = contour.length;
  18589. holes.forEach(removeDupEndPts);
  18590. for (let i = 0; i < holes.length; i++) {
  18591. holeIndices.push(holeIndex);
  18592. holeIndex += holes[i].length;
  18593. addContour(vertices, holes[i]);
  18594. } //
  18595. const triangles = Earcut.triangulate(vertices, holeIndices); //
  18596. for (let i = 0; i < triangles.length; i += 3) {
  18597. faces.push(triangles.slice(i, i + 3));
  18598. }
  18599. return faces;
  18600. }
  18601. };
  18602. exports.ShapeUtils = ShapeUtils;
  18603. function removeDupEndPts(points) {
  18604. const l = points.length;
  18605. if (l > 2 && points[l - 1].equals(points[0])) {
  18606. points.pop();
  18607. }
  18608. }
  18609. function addContour(vertices, contour) {
  18610. for (let i = 0; i < contour.length; i++) {
  18611. vertices.push(contour[i].x);
  18612. vertices.push(contour[i].y);
  18613. }
  18614. }
  18615. /**
  18616. * Creates extruded geometry from a path shape.
  18617. *
  18618. * parameters = {
  18619. *
  18620. * curveSegments: <int>, // number of points on the curves
  18621. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18622. * depth: <float>, // Depth to extrude the shape
  18623. *
  18624. * bevelEnabled: <bool>, // turn on bevel
  18625. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18626. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18627. * bevelOffset: <float>, // how far from shape outline does bevel start
  18628. * bevelSegments: <int>, // number of bevel layers
  18629. *
  18630. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18631. *
  18632. * UVGenerator: <Object> // object that provides UV generator functions
  18633. *
  18634. * }
  18635. */
  18636. class ExtrudeBufferGeometry extends BufferGeometry {
  18637. constructor(shapes, options) {
  18638. super();
  18639. this.type = 'ExtrudeBufferGeometry';
  18640. this.parameters = {
  18641. shapes: shapes,
  18642. options: options
  18643. };
  18644. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18645. const scope = this;
  18646. const verticesArray = [];
  18647. const uvArray = [];
  18648. for (let i = 0, l = shapes.length; i < l; i++) {
  18649. const shape = shapes[i];
  18650. addShape(shape);
  18651. } // build geometry
  18652. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18653. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18654. this.computeVertexNormals(); // functions
  18655. function addShape(shape) {
  18656. const placeholder = []; // options
  18657. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18658. const steps = options.steps !== undefined ? options.steps : 1;
  18659. let depth = options.depth !== undefined ? options.depth : 100;
  18660. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18661. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18662. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18663. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18664. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18665. const extrudePath = options.extrudePath;
  18666. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18667. if (options.amount !== undefined) {
  18668. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18669. depth = options.amount;
  18670. } //
  18671. let extrudePts,
  18672. extrudeByPath = false;
  18673. let splineTube, binormal, normal, position2;
  18674. if (extrudePath) {
  18675. extrudePts = extrudePath.getSpacedPoints(steps);
  18676. extrudeByPath = true;
  18677. bevelEnabled = false; // bevels not supported for path extrusion
  18678. // SETUP TNB variables
  18679. // TODO1 - have a .isClosed in spline?
  18680. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18681. binormal = new Vector3();
  18682. normal = new Vector3();
  18683. position2 = new Vector3();
  18684. } // Safeguards if bevels are not enabled
  18685. if (!bevelEnabled) {
  18686. bevelSegments = 0;
  18687. bevelThickness = 0;
  18688. bevelSize = 0;
  18689. bevelOffset = 0;
  18690. } // Variables initialization
  18691. const shapePoints = shape.extractPoints(curveSegments);
  18692. let vertices = shapePoints.shape;
  18693. const holes = shapePoints.holes;
  18694. const reverse = !ShapeUtils.isClockWise(vertices);
  18695. if (reverse) {
  18696. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18697. for (let h = 0, hl = holes.length; h < hl; h++) {
  18698. const ahole = holes[h];
  18699. if (ShapeUtils.isClockWise(ahole)) {
  18700. holes[h] = ahole.reverse();
  18701. }
  18702. }
  18703. }
  18704. const faces = ShapeUtils.triangulateShape(vertices, holes);
  18705. /* Vertices */
  18706. const contour = vertices; // vertices has all points but contour has only points of circumference
  18707. for (let h = 0, hl = holes.length; h < hl; h++) {
  18708. const ahole = holes[h];
  18709. vertices = vertices.concat(ahole);
  18710. }
  18711. function scalePt2(pt, vec, size) {
  18712. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18713. return vec.clone().multiplyScalar(size).add(pt);
  18714. }
  18715. const vlen = vertices.length,
  18716. flen = faces.length; // Find directions for point movement
  18717. function getBevelVec(inPt, inPrev, inNext) {
  18718. // computes for inPt the corresponding point inPt' on a new contour
  18719. // shifted by 1 unit (length of normalized vector) to the left
  18720. // if we walk along contour clockwise, this new contour is outside the old one
  18721. //
  18722. // inPt' is the intersection of the two lines parallel to the two
  18723. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18724. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18725. // good reading for geometry algorithms (here: line-line intersection)
  18726. // http://geomalgorithms.com/a05-_intersect-1.html
  18727. const v_prev_x = inPt.x - inPrev.x,
  18728. v_prev_y = inPt.y - inPrev.y;
  18729. const v_next_x = inNext.x - inPt.x,
  18730. v_next_y = inNext.y - inPt.y;
  18731. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18732. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18733. if (Math.abs(collinear0) > Number.EPSILON) {
  18734. // not collinear
  18735. // length of vectors for normalizing
  18736. const v_prev_len = Math.sqrt(v_prev_lensq);
  18737. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  18738. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18739. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18740. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18741. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18742. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  18743. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18744. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18745. // but prevent crazy spikes
  18746. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18747. if (v_trans_lensq <= 2) {
  18748. return new Vector2(v_trans_x, v_trans_y);
  18749. } else {
  18750. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18751. }
  18752. } else {
  18753. // handle special case of collinear edges
  18754. let direction_eq = false; // assumes: opposite
  18755. if (v_prev_x > Number.EPSILON) {
  18756. if (v_next_x > Number.EPSILON) {
  18757. direction_eq = true;
  18758. }
  18759. } else {
  18760. if (v_prev_x < -Number.EPSILON) {
  18761. if (v_next_x < -Number.EPSILON) {
  18762. direction_eq = true;
  18763. }
  18764. } else {
  18765. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18766. direction_eq = true;
  18767. }
  18768. }
  18769. }
  18770. if (direction_eq) {
  18771. // console.log("Warning: lines are a straight sequence");
  18772. v_trans_x = -v_prev_y;
  18773. v_trans_y = v_prev_x;
  18774. shrink_by = Math.sqrt(v_prev_lensq);
  18775. } else {
  18776. // console.log("Warning: lines are a straight spike");
  18777. v_trans_x = v_prev_x;
  18778. v_trans_y = v_prev_y;
  18779. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18780. }
  18781. }
  18782. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18783. }
  18784. const contourMovements = [];
  18785. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18786. if (j === il) j = 0;
  18787. if (k === il) k = 0; // (j)---(i)---(k)
  18788. // console.log('i,j,k', i, j , k)
  18789. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18790. }
  18791. const holesMovements = [];
  18792. let oneHoleMovements,
  18793. verticesMovements = contourMovements.concat();
  18794. for (let h = 0, hl = holes.length; h < hl; h++) {
  18795. const ahole = holes[h];
  18796. oneHoleMovements = [];
  18797. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18798. if (j === il) j = 0;
  18799. if (k === il) k = 0; // (j)---(i)---(k)
  18800. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18801. }
  18802. holesMovements.push(oneHoleMovements);
  18803. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18804. } // Loop bevelSegments, 1 for the front, 1 for the back
  18805. for (let b = 0; b < bevelSegments; b++) {
  18806. //for ( b = bevelSegments; b > 0; b -- ) {
  18807. const t = b / bevelSegments;
  18808. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18809. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18810. for (let i = 0, il = contour.length; i < il; i++) {
  18811. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18812. v(vert.x, vert.y, -z);
  18813. } // expand holes
  18814. for (let h = 0, hl = holes.length; h < hl; h++) {
  18815. const ahole = holes[h];
  18816. oneHoleMovements = holesMovements[h];
  18817. for (let i = 0, il = ahole.length; i < il; i++) {
  18818. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18819. v(vert.x, vert.y, -z);
  18820. }
  18821. }
  18822. }
  18823. const bs = bevelSize + bevelOffset; // Back facing vertices
  18824. for (let i = 0; i < vlen; i++) {
  18825. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18826. if (!extrudeByPath) {
  18827. v(vert.x, vert.y, 0);
  18828. } else {
  18829. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18830. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18831. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18832. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18833. v(position2.x, position2.y, position2.z);
  18834. }
  18835. } // Add stepped vertices...
  18836. // Including front facing vertices
  18837. for (let s = 1; s <= steps; s++) {
  18838. for (let i = 0; i < vlen; i++) {
  18839. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18840. if (!extrudeByPath) {
  18841. v(vert.x, vert.y, depth / steps * s);
  18842. } else {
  18843. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18844. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18845. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18846. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18847. v(position2.x, position2.y, position2.z);
  18848. }
  18849. }
  18850. } // Add bevel segments planes
  18851. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18852. for (let b = bevelSegments - 1; b >= 0; b--) {
  18853. const t = b / bevelSegments;
  18854. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18855. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18856. for (let i = 0, il = contour.length; i < il; i++) {
  18857. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18858. v(vert.x, vert.y, depth + z);
  18859. } // expand holes
  18860. for (let h = 0, hl = holes.length; h < hl; h++) {
  18861. const ahole = holes[h];
  18862. oneHoleMovements = holesMovements[h];
  18863. for (let i = 0, il = ahole.length; i < il; i++) {
  18864. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18865. if (!extrudeByPath) {
  18866. v(vert.x, vert.y, depth + z);
  18867. } else {
  18868. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18869. }
  18870. }
  18871. }
  18872. }
  18873. /* Faces */
  18874. // Top and bottom faces
  18875. buildLidFaces(); // Sides faces
  18876. buildSideFaces(); ///// Internal functions
  18877. function buildLidFaces() {
  18878. const start = verticesArray.length / 3;
  18879. if (bevelEnabled) {
  18880. let layer = 0; // steps + 1
  18881. let offset = vlen * layer; // Bottom faces
  18882. for (let i = 0; i < flen; i++) {
  18883. const face = faces[i];
  18884. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18885. }
  18886. layer = steps + bevelSegments * 2;
  18887. offset = vlen * layer; // Top faces
  18888. for (let i = 0; i < flen; i++) {
  18889. const face = faces[i];
  18890. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18891. }
  18892. } else {
  18893. // Bottom faces
  18894. for (let i = 0; i < flen; i++) {
  18895. const face = faces[i];
  18896. f3(face[2], face[1], face[0]);
  18897. } // Top faces
  18898. for (let i = 0; i < flen; i++) {
  18899. const face = faces[i];
  18900. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18901. }
  18902. }
  18903. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18904. } // Create faces for the z-sides of the shape
  18905. function buildSideFaces() {
  18906. const start = verticesArray.length / 3;
  18907. let layeroffset = 0;
  18908. sidewalls(contour, layeroffset);
  18909. layeroffset += contour.length;
  18910. for (let h = 0, hl = holes.length; h < hl; h++) {
  18911. const ahole = holes[h];
  18912. sidewalls(ahole, layeroffset); //, true
  18913. layeroffset += ahole.length;
  18914. }
  18915. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18916. }
  18917. function sidewalls(contour, layeroffset) {
  18918. let i = contour.length;
  18919. while (--i >= 0) {
  18920. const j = i;
  18921. let k = i - 1;
  18922. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18923. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  18924. const slen1 = vlen * s;
  18925. const slen2 = vlen * (s + 1);
  18926. const a = layeroffset + j + slen1,
  18927. b = layeroffset + k + slen1,
  18928. c = layeroffset + k + slen2,
  18929. d = layeroffset + j + slen2;
  18930. f4(a, b, c, d);
  18931. }
  18932. }
  18933. }
  18934. function v(x, y, z) {
  18935. placeholder.push(x);
  18936. placeholder.push(y);
  18937. placeholder.push(z);
  18938. }
  18939. function f3(a, b, c) {
  18940. addVertex(a);
  18941. addVertex(b);
  18942. addVertex(c);
  18943. const nextIndex = verticesArray.length / 3;
  18944. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18945. addUV(uvs[0]);
  18946. addUV(uvs[1]);
  18947. addUV(uvs[2]);
  18948. }
  18949. function f4(a, b, c, d) {
  18950. addVertex(a);
  18951. addVertex(b);
  18952. addVertex(d);
  18953. addVertex(b);
  18954. addVertex(c);
  18955. addVertex(d);
  18956. const nextIndex = verticesArray.length / 3;
  18957. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18958. addUV(uvs[0]);
  18959. addUV(uvs[1]);
  18960. addUV(uvs[3]);
  18961. addUV(uvs[1]);
  18962. addUV(uvs[2]);
  18963. addUV(uvs[3]);
  18964. }
  18965. function addVertex(index) {
  18966. verticesArray.push(placeholder[index * 3 + 0]);
  18967. verticesArray.push(placeholder[index * 3 + 1]);
  18968. verticesArray.push(placeholder[index * 3 + 2]);
  18969. }
  18970. function addUV(vector2) {
  18971. uvArray.push(vector2.x);
  18972. uvArray.push(vector2.y);
  18973. }
  18974. }
  18975. }
  18976. toJSON() {
  18977. const data = BufferGeometry.prototype.toJSON.call(this);
  18978. const shapes = this.parameters.shapes;
  18979. const options = this.parameters.options;
  18980. return toJSON(shapes, options, data);
  18981. }
  18982. }
  18983. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  18984. const WorldUVGenerator = {
  18985. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18986. const a_x = vertices[indexA * 3];
  18987. const a_y = vertices[indexA * 3 + 1];
  18988. const b_x = vertices[indexB * 3];
  18989. const b_y = vertices[indexB * 3 + 1];
  18990. const c_x = vertices[indexC * 3];
  18991. const c_y = vertices[indexC * 3 + 1];
  18992. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18993. },
  18994. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18995. const a_x = vertices[indexA * 3];
  18996. const a_y = vertices[indexA * 3 + 1];
  18997. const a_z = vertices[indexA * 3 + 2];
  18998. const b_x = vertices[indexB * 3];
  18999. const b_y = vertices[indexB * 3 + 1];
  19000. const b_z = vertices[indexB * 3 + 2];
  19001. const c_x = vertices[indexC * 3];
  19002. const c_y = vertices[indexC * 3 + 1];
  19003. const c_z = vertices[indexC * 3 + 2];
  19004. const d_x = vertices[indexD * 3];
  19005. const d_y = vertices[indexD * 3 + 1];
  19006. const d_z = vertices[indexD * 3 + 2];
  19007. if (Math.abs(a_y - b_y) < 0.01) {
  19008. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  19009. } else {
  19010. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  19011. }
  19012. }
  19013. };
  19014. function toJSON(shapes, options, data) {
  19015. data.shapes = [];
  19016. if (Array.isArray(shapes)) {
  19017. for (let i = 0, l = shapes.length; i < l; i++) {
  19018. const shape = shapes[i];
  19019. data.shapes.push(shape.uuid);
  19020. }
  19021. } else {
  19022. data.shapes.push(shapes.uuid);
  19023. }
  19024. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19025. return data;
  19026. }
  19027. /**
  19028. * Creates extruded geometry from a path shape.
  19029. *
  19030. * parameters = {
  19031. *
  19032. * curveSegments: <int>, // number of points on the curves
  19033. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19034. * depth: <float>, // Depth to extrude the shape
  19035. *
  19036. * bevelEnabled: <bool>, // turn on bevel
  19037. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19038. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19039. * bevelOffset: <float>, // how far from shape outline does bevel start
  19040. * bevelSegments: <int>, // number of bevel layers
  19041. *
  19042. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19043. *
  19044. * UVGenerator: <Object> // object that provides UV generator functions
  19045. *
  19046. * }
  19047. */
  19048. class ExtrudeGeometry extends Geometry {
  19049. constructor(shapes, options) {
  19050. super();
  19051. this.type = 'ExtrudeGeometry';
  19052. this.parameters = {
  19053. shapes: shapes,
  19054. options: options
  19055. };
  19056. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19057. this.mergeVertices();
  19058. }
  19059. toJSON() {
  19060. const data = super.toJSON();
  19061. const shapes = this.parameters.shapes;
  19062. const options = this.parameters.options;
  19063. return toJSON$1(shapes, options, data);
  19064. }
  19065. }
  19066. exports.ExtrudeGeometry = ExtrudeGeometry;
  19067. function toJSON$1(shapes, options, data) {
  19068. data.shapes = [];
  19069. if (Array.isArray(shapes)) {
  19070. for (let i = 0, l = shapes.length; i < l; i++) {
  19071. const shape = shapes[i];
  19072. data.shapes.push(shape.uuid);
  19073. }
  19074. } else {
  19075. data.shapes.push(shapes.uuid);
  19076. }
  19077. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19078. return data;
  19079. }
  19080. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  19081. constructor(radius = 1, detail = 0) {
  19082. const t = (1 + Math.sqrt(5)) / 2;
  19083. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  19084. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  19085. super(vertices, indices, radius, detail);
  19086. this.type = 'IcosahedronBufferGeometry';
  19087. this.parameters = {
  19088. radius: radius,
  19089. detail: detail
  19090. };
  19091. }
  19092. }
  19093. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  19094. class IcosahedronGeometry extends Geometry {
  19095. constructor(radius, detail) {
  19096. super();
  19097. this.type = 'IcosahedronGeometry';
  19098. this.parameters = {
  19099. radius: radius,
  19100. detail: detail
  19101. };
  19102. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  19103. this.mergeVertices();
  19104. }
  19105. }
  19106. exports.IcosahedronGeometry = IcosahedronGeometry;
  19107. class LatheBufferGeometry extends BufferGeometry {
  19108. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19109. super();
  19110. this.type = 'LatheBufferGeometry';
  19111. this.parameters = {
  19112. points: points,
  19113. segments: segments,
  19114. phiStart: phiStart,
  19115. phiLength: phiLength
  19116. };
  19117. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19118. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  19119. const indices = [];
  19120. const vertices = [];
  19121. const uvs = []; // helper variables
  19122. const inverseSegments = 1.0 / segments;
  19123. const vertex = new Vector3();
  19124. const uv = new Vector2(); // generate vertices and uvs
  19125. for (let i = 0; i <= segments; i++) {
  19126. const phi = phiStart + i * inverseSegments * phiLength;
  19127. const sin = Math.sin(phi);
  19128. const cos = Math.cos(phi);
  19129. for (let j = 0; j <= points.length - 1; j++) {
  19130. // vertex
  19131. vertex.x = points[j].x * sin;
  19132. vertex.y = points[j].y;
  19133. vertex.z = points[j].x * cos;
  19134. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19135. uv.x = i / segments;
  19136. uv.y = j / (points.length - 1);
  19137. uvs.push(uv.x, uv.y);
  19138. }
  19139. } // indices
  19140. for (let i = 0; i < segments; i++) {
  19141. for (let j = 0; j < points.length - 1; j++) {
  19142. const base = j + i * points.length;
  19143. const a = base;
  19144. const b = base + points.length;
  19145. const c = base + points.length + 1;
  19146. const d = base + 1; // faces
  19147. indices.push(a, b, d);
  19148. indices.push(b, c, d);
  19149. }
  19150. } // build geometry
  19151. this.setIndex(indices);
  19152. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19153. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19154. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19155. // because the corresponding vertices are identical (but still have different UVs).
  19156. if (phiLength === Math.PI * 2) {
  19157. const normals = this.attributes.normal.array;
  19158. const n1 = new Vector3();
  19159. const n2 = new Vector3();
  19160. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  19161. const base = segments * points.length * 3;
  19162. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  19163. // select the normal of the vertex in the first line
  19164. n1.x = normals[j + 0];
  19165. n1.y = normals[j + 1];
  19166. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19167. n2.x = normals[base + j + 0];
  19168. n2.y = normals[base + j + 1];
  19169. n2.z = normals[base + j + 2]; // average normals
  19170. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19171. normals[j + 0] = normals[base + j + 0] = n.x;
  19172. normals[j + 1] = normals[base + j + 1] = n.y;
  19173. normals[j + 2] = normals[base + j + 2] = n.z;
  19174. }
  19175. }
  19176. }
  19177. }
  19178. exports.LatheBufferGeometry = LatheBufferGeometry;
  19179. class LatheGeometry extends Geometry {
  19180. constructor(points, segments, phiStart, phiLength) {
  19181. super();
  19182. this.type = 'LatheGeometry';
  19183. this.parameters = {
  19184. points: points,
  19185. segments: segments,
  19186. phiStart: phiStart,
  19187. phiLength: phiLength
  19188. };
  19189. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19190. this.mergeVertices();
  19191. }
  19192. }
  19193. exports.LatheGeometry = LatheGeometry;
  19194. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  19195. constructor(radius = 1, detail = 0) {
  19196. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  19197. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  19198. super(vertices, indices, radius, detail);
  19199. this.type = 'OctahedronBufferGeometry';
  19200. this.parameters = {
  19201. radius: radius,
  19202. detail: detail
  19203. };
  19204. }
  19205. }
  19206. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  19207. class OctahedronGeometry extends Geometry {
  19208. constructor(radius, detail) {
  19209. super();
  19210. this.type = 'OctahedronGeometry';
  19211. this.parameters = {
  19212. radius: radius,
  19213. detail: detail
  19214. };
  19215. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  19216. this.mergeVertices();
  19217. }
  19218. }
  19219. /**
  19220. * Parametric Surfaces Geometry
  19221. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19222. */
  19223. exports.OctahedronGeometry = OctahedronGeometry;
  19224. function ParametricBufferGeometry(func, slices, stacks) {
  19225. BufferGeometry.call(this);
  19226. this.type = 'ParametricBufferGeometry';
  19227. this.parameters = {
  19228. func: func,
  19229. slices: slices,
  19230. stacks: stacks
  19231. }; // buffers
  19232. const indices = [];
  19233. const vertices = [];
  19234. const normals = [];
  19235. const uvs = [];
  19236. const EPS = 0.00001;
  19237. const normal = new Vector3();
  19238. const p0 = new Vector3(),
  19239. p1 = new Vector3();
  19240. const pu = new Vector3(),
  19241. pv = new Vector3();
  19242. if (func.length < 3) {
  19243. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  19244. } // generate vertices, normals and uvs
  19245. const sliceCount = slices + 1;
  19246. for (let i = 0; i <= stacks; i++) {
  19247. const v = i / stacks;
  19248. for (let j = 0; j <= slices; j++) {
  19249. const u = j / slices; // vertex
  19250. func(u, v, p0);
  19251. vertices.push(p0.x, p0.y, p0.z); // normal
  19252. // approximate tangent vectors via finite differences
  19253. if (u - EPS >= 0) {
  19254. func(u - EPS, v, p1);
  19255. pu.subVectors(p0, p1);
  19256. } else {
  19257. func(u + EPS, v, p1);
  19258. pu.subVectors(p1, p0);
  19259. }
  19260. if (v - EPS >= 0) {
  19261. func(u, v - EPS, p1);
  19262. pv.subVectors(p0, p1);
  19263. } else {
  19264. func(u, v + EPS, p1);
  19265. pv.subVectors(p1, p0);
  19266. } // cross product of tangent vectors returns surface normal
  19267. normal.crossVectors(pu, pv).normalize();
  19268. normals.push(normal.x, normal.y, normal.z); // uv
  19269. uvs.push(u, v);
  19270. }
  19271. } // generate indices
  19272. for (let i = 0; i < stacks; i++) {
  19273. for (let j = 0; j < slices; j++) {
  19274. const a = i * sliceCount + j;
  19275. const b = i * sliceCount + j + 1;
  19276. const c = (i + 1) * sliceCount + j + 1;
  19277. const d = (i + 1) * sliceCount + j; // faces one and two
  19278. indices.push(a, b, d);
  19279. indices.push(b, c, d);
  19280. }
  19281. } // build geometry
  19282. this.setIndex(indices);
  19283. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19284. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19285. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19286. }
  19287. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19288. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19289. /**
  19290. * Parametric Surfaces Geometry
  19291. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19292. */
  19293. function ParametricGeometry(func, slices, stacks) {
  19294. Geometry.call(this);
  19295. this.type = 'ParametricGeometry';
  19296. this.parameters = {
  19297. func: func,
  19298. slices: slices,
  19299. stacks: stacks
  19300. };
  19301. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  19302. this.mergeVertices();
  19303. }
  19304. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  19305. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19306. class PlaneGeometry extends Geometry {
  19307. constructor(width, height, widthSegments, heightSegments) {
  19308. super();
  19309. this.type = 'PlaneGeometry';
  19310. this.parameters = {
  19311. width: width,
  19312. height: height,
  19313. widthSegments: widthSegments,
  19314. heightSegments: heightSegments
  19315. };
  19316. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  19317. this.mergeVertices();
  19318. }
  19319. }
  19320. exports.PlaneGeometry = PlaneGeometry;
  19321. class PolyhedronGeometry extends Geometry {
  19322. constructor(vertices, indices, radius, detail) {
  19323. super();
  19324. this.type = 'PolyhedronGeometry';
  19325. this.parameters = {
  19326. vertices: vertices,
  19327. indices: indices,
  19328. radius: radius,
  19329. detail: detail
  19330. };
  19331. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  19332. this.mergeVertices();
  19333. }
  19334. }
  19335. exports.PolyhedronGeometry = PolyhedronGeometry;
  19336. class RingBufferGeometry extends BufferGeometry {
  19337. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  19338. super();
  19339. this.type = 'RingBufferGeometry';
  19340. this.parameters = {
  19341. innerRadius: innerRadius,
  19342. outerRadius: outerRadius,
  19343. thetaSegments: thetaSegments,
  19344. phiSegments: phiSegments,
  19345. thetaStart: thetaStart,
  19346. thetaLength: thetaLength
  19347. };
  19348. thetaSegments = Math.max(3, thetaSegments);
  19349. phiSegments = Math.max(1, phiSegments); // buffers
  19350. const indices = [];
  19351. const vertices = [];
  19352. const normals = [];
  19353. const uvs = []; // some helper variables
  19354. let radius = innerRadius;
  19355. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  19356. const vertex = new Vector3();
  19357. const uv = new Vector2(); // generate vertices, normals and uvs
  19358. for (let j = 0; j <= phiSegments; j++) {
  19359. for (let i = 0; i <= thetaSegments; i++) {
  19360. // values are generate from the inside of the ring to the outside
  19361. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19362. vertex.x = radius * Math.cos(segment);
  19363. vertex.y = radius * Math.sin(segment);
  19364. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19365. normals.push(0, 0, 1); // uv
  19366. uv.x = (vertex.x / outerRadius + 1) / 2;
  19367. uv.y = (vertex.y / outerRadius + 1) / 2;
  19368. uvs.push(uv.x, uv.y);
  19369. } // increase the radius for next row of vertices
  19370. radius += radiusStep;
  19371. } // indices
  19372. for (let j = 0; j < phiSegments; j++) {
  19373. const thetaSegmentLevel = j * (thetaSegments + 1);
  19374. for (let i = 0; i < thetaSegments; i++) {
  19375. const segment = i + thetaSegmentLevel;
  19376. const a = segment;
  19377. const b = segment + thetaSegments + 1;
  19378. const c = segment + thetaSegments + 2;
  19379. const d = segment + 1; // faces
  19380. indices.push(a, b, d);
  19381. indices.push(b, c, d);
  19382. }
  19383. } // build geometry
  19384. this.setIndex(indices);
  19385. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19386. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19387. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19388. }
  19389. }
  19390. exports.RingBufferGeometry = RingBufferGeometry;
  19391. class RingGeometry extends Geometry {
  19392. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19393. super();
  19394. this.type = 'RingGeometry';
  19395. this.parameters = {
  19396. innerRadius: innerRadius,
  19397. outerRadius: outerRadius,
  19398. thetaSegments: thetaSegments,
  19399. phiSegments: phiSegments,
  19400. thetaStart: thetaStart,
  19401. thetaLength: thetaLength
  19402. };
  19403. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19404. this.mergeVertices();
  19405. }
  19406. }
  19407. exports.RingGeometry = RingGeometry;
  19408. class ShapeBufferGeometry extends BufferGeometry {
  19409. constructor(shapes, curveSegments = 12) {
  19410. super();
  19411. this.type = 'ShapeBufferGeometry';
  19412. this.parameters = {
  19413. shapes: shapes,
  19414. curveSegments: curveSegments
  19415. }; // buffers
  19416. const indices = [];
  19417. const vertices = [];
  19418. const normals = [];
  19419. const uvs = []; // helper variables
  19420. let groupStart = 0;
  19421. let groupCount = 0; // allow single and array values for "shapes" parameter
  19422. if (Array.isArray(shapes) === false) {
  19423. addShape(shapes);
  19424. } else {
  19425. for (let i = 0; i < shapes.length; i++) {
  19426. addShape(shapes[i]);
  19427. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19428. groupStart += groupCount;
  19429. groupCount = 0;
  19430. }
  19431. } // build geometry
  19432. this.setIndex(indices);
  19433. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19434. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19435. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19436. function addShape(shape) {
  19437. const indexOffset = vertices.length / 3;
  19438. const points = shape.extractPoints(curveSegments);
  19439. let shapeVertices = points.shape;
  19440. const shapeHoles = points.holes; // check direction of vertices
  19441. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19442. shapeVertices = shapeVertices.reverse();
  19443. }
  19444. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19445. const shapeHole = shapeHoles[i];
  19446. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19447. shapeHoles[i] = shapeHole.reverse();
  19448. }
  19449. }
  19450. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19451. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19452. const shapeHole = shapeHoles[i];
  19453. shapeVertices = shapeVertices.concat(shapeHole);
  19454. } // vertices, normals, uvs
  19455. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19456. const vertex = shapeVertices[i];
  19457. vertices.push(vertex.x, vertex.y, 0);
  19458. normals.push(0, 0, 1);
  19459. uvs.push(vertex.x, vertex.y); // world uvs
  19460. } // incides
  19461. for (let i = 0, l = faces.length; i < l; i++) {
  19462. const face = faces[i];
  19463. const a = face[0] + indexOffset;
  19464. const b = face[1] + indexOffset;
  19465. const c = face[2] + indexOffset;
  19466. indices.push(a, b, c);
  19467. groupCount += 3;
  19468. }
  19469. }
  19470. }
  19471. toJSON() {
  19472. const data = BufferGeometry.prototype.toJSON.call(this);
  19473. const shapes = this.parameters.shapes;
  19474. return toJSON$2(shapes, data);
  19475. }
  19476. }
  19477. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  19478. function toJSON$2(shapes, data) {
  19479. data.shapes = [];
  19480. if (Array.isArray(shapes)) {
  19481. for (let i = 0, l = shapes.length; i < l; i++) {
  19482. const shape = shapes[i];
  19483. data.shapes.push(shape.uuid);
  19484. }
  19485. } else {
  19486. data.shapes.push(shapes.uuid);
  19487. }
  19488. return data;
  19489. }
  19490. class ShapeGeometry extends Geometry {
  19491. constructor(shapes, curveSegments) {
  19492. super();
  19493. this.type = 'ShapeGeometry';
  19494. if (typeof curveSegments === 'object') {
  19495. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  19496. curveSegments = curveSegments.curveSegments;
  19497. }
  19498. this.parameters = {
  19499. shapes: shapes,
  19500. curveSegments: curveSegments
  19501. };
  19502. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  19503. this.mergeVertices();
  19504. }
  19505. toJSON() {
  19506. const data = Geometry.prototype.toJSON.call(this);
  19507. const shapes = this.parameters.shapes;
  19508. return toJSON$3(shapes, data);
  19509. }
  19510. }
  19511. exports.ShapeGeometry = ShapeGeometry;
  19512. function toJSON$3(shapes, data) {
  19513. data.shapes = [];
  19514. if (Array.isArray(shapes)) {
  19515. for (let i = 0, l = shapes.length; i < l; i++) {
  19516. const shape = shapes[i];
  19517. data.shapes.push(shape.uuid);
  19518. }
  19519. } else {
  19520. data.shapes.push(shapes.uuid);
  19521. }
  19522. return data;
  19523. }
  19524. class SphereBufferGeometry extends BufferGeometry {
  19525. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  19526. super();
  19527. this.type = 'SphereBufferGeometry';
  19528. this.parameters = {
  19529. radius: radius,
  19530. widthSegments: widthSegments,
  19531. heightSegments: heightSegments,
  19532. phiStart: phiStart,
  19533. phiLength: phiLength,
  19534. thetaStart: thetaStart,
  19535. thetaLength: thetaLength
  19536. };
  19537. widthSegments = Math.max(3, Math.floor(widthSegments));
  19538. heightSegments = Math.max(2, Math.floor(heightSegments));
  19539. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19540. let index = 0;
  19541. const grid = [];
  19542. const vertex = new Vector3();
  19543. const normal = new Vector3(); // buffers
  19544. const indices = [];
  19545. const vertices = [];
  19546. const normals = [];
  19547. const uvs = []; // generate vertices, normals and uvs
  19548. for (let iy = 0; iy <= heightSegments; iy++) {
  19549. const verticesRow = [];
  19550. const v = iy / heightSegments; // special case for the poles
  19551. let uOffset = 0;
  19552. if (iy == 0 && thetaStart == 0) {
  19553. uOffset = 0.5 / widthSegments;
  19554. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19555. uOffset = -0.5 / widthSegments;
  19556. }
  19557. for (let ix = 0; ix <= widthSegments; ix++) {
  19558. const u = ix / widthSegments; // vertex
  19559. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19560. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19561. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19562. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19563. normal.copy(vertex).normalize();
  19564. normals.push(normal.x, normal.y, normal.z); // uv
  19565. uvs.push(u + uOffset, 1 - v);
  19566. verticesRow.push(index++);
  19567. }
  19568. grid.push(verticesRow);
  19569. } // indices
  19570. for (let iy = 0; iy < heightSegments; iy++) {
  19571. for (let ix = 0; ix < widthSegments; ix++) {
  19572. const a = grid[iy][ix + 1];
  19573. const b = grid[iy][ix];
  19574. const c = grid[iy + 1][ix];
  19575. const d = grid[iy + 1][ix + 1];
  19576. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19577. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19578. }
  19579. } // build geometry
  19580. this.setIndex(indices);
  19581. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19582. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19583. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19584. }
  19585. }
  19586. exports.SphereBufferGeometry = SphereBufferGeometry;
  19587. class SphereGeometry extends Geometry {
  19588. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19589. super();
  19590. this.type = 'SphereGeometry';
  19591. this.parameters = {
  19592. radius: radius,
  19593. widthSegments: widthSegments,
  19594. heightSegments: heightSegments,
  19595. phiStart: phiStart,
  19596. phiLength: phiLength,
  19597. thetaStart: thetaStart,
  19598. thetaLength: thetaLength
  19599. };
  19600. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19601. this.mergeVertices();
  19602. }
  19603. }
  19604. exports.SphereGeometry = SphereGeometry;
  19605. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  19606. constructor(radius = 1, detail = 0) {
  19607. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  19608. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  19609. super(vertices, indices, radius, detail);
  19610. this.type = 'TetrahedronBufferGeometry';
  19611. this.parameters = {
  19612. radius: radius,
  19613. detail: detail
  19614. };
  19615. }
  19616. }
  19617. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  19618. class TetrahedronGeometry extends Geometry {
  19619. constructor(radius, detail) {
  19620. super();
  19621. this.type = 'TetrahedronGeometry';
  19622. this.parameters = {
  19623. radius: radius,
  19624. detail: detail
  19625. };
  19626. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  19627. this.mergeVertices();
  19628. }
  19629. }
  19630. /**
  19631. * Text = 3D Text
  19632. *
  19633. * parameters = {
  19634. * font: <THREE.Font>, // font
  19635. *
  19636. * size: <float>, // size of the text
  19637. * height: <float>, // thickness to extrude text
  19638. * curveSegments: <int>, // number of points on the curves
  19639. *
  19640. * bevelEnabled: <bool>, // turn on bevel
  19641. * bevelThickness: <float>, // how deep into text bevel goes
  19642. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19643. * bevelOffset: <float> // how far from text outline does bevel start
  19644. * }
  19645. */
  19646. exports.TetrahedronGeometry = TetrahedronGeometry;
  19647. class TextBufferGeometry extends ExtrudeBufferGeometry {
  19648. constructor(text, parameters = {}) {
  19649. const font = parameters.font;
  19650. if (!(font && font.isFont)) {
  19651. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19652. return new BufferGeometry();
  19653. }
  19654. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19655. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19656. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19657. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19658. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19659. super(shapes, parameters);
  19660. this.type = 'TextBufferGeometry';
  19661. }
  19662. }
  19663. /**
  19664. * Text = 3D Text
  19665. *
  19666. * parameters = {
  19667. * font: <THREE.Font>, // font
  19668. *
  19669. * size: <float>, // size of the text
  19670. * height: <float>, // thickness to extrude text
  19671. * curveSegments: <int>, // number of points on the curves
  19672. *
  19673. * bevelEnabled: <bool>, // turn on bevel
  19674. * bevelThickness: <float>, // how deep into text bevel goes
  19675. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19676. * bevelOffset: <float> // how far from text outline does bevel start
  19677. * }
  19678. */
  19679. exports.TextBufferGeometry = TextBufferGeometry;
  19680. class TextGeometry extends Geometry {
  19681. constructor(text, parameters) {
  19682. super();
  19683. this.type = 'TextGeometry';
  19684. this.parameters = {
  19685. text: text,
  19686. parameters: parameters
  19687. };
  19688. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19689. this.mergeVertices();
  19690. }
  19691. }
  19692. exports.TextGeometry = TextGeometry;
  19693. class TorusBufferGeometry extends BufferGeometry {
  19694. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  19695. super();
  19696. this.type = 'TorusBufferGeometry';
  19697. this.parameters = {
  19698. radius: radius,
  19699. tube: tube,
  19700. radialSegments: radialSegments,
  19701. tubularSegments: tubularSegments,
  19702. arc: arc
  19703. };
  19704. radialSegments = Math.floor(radialSegments);
  19705. tubularSegments = Math.floor(tubularSegments); // buffers
  19706. const indices = [];
  19707. const vertices = [];
  19708. const normals = [];
  19709. const uvs = []; // helper variables
  19710. const center = new Vector3();
  19711. const vertex = new Vector3();
  19712. const normal = new Vector3(); // generate vertices, normals and uvs
  19713. for (let j = 0; j <= radialSegments; j++) {
  19714. for (let i = 0; i <= tubularSegments; i++) {
  19715. const u = i / tubularSegments * arc;
  19716. const v = j / radialSegments * Math.PI * 2; // vertex
  19717. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  19718. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  19719. vertex.z = tube * Math.sin(v);
  19720. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19721. center.x = radius * Math.cos(u);
  19722. center.y = radius * Math.sin(u);
  19723. normal.subVectors(vertex, center).normalize();
  19724. normals.push(normal.x, normal.y, normal.z); // uv
  19725. uvs.push(i / tubularSegments);
  19726. uvs.push(j / radialSegments);
  19727. }
  19728. } // generate indices
  19729. for (let j = 1; j <= radialSegments; j++) {
  19730. for (let i = 1; i <= tubularSegments; i++) {
  19731. // indices
  19732. const a = (tubularSegments + 1) * j + i - 1;
  19733. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  19734. const c = (tubularSegments + 1) * (j - 1) + i;
  19735. const d = (tubularSegments + 1) * j + i; // faces
  19736. indices.push(a, b, d);
  19737. indices.push(b, c, d);
  19738. }
  19739. } // build geometry
  19740. this.setIndex(indices);
  19741. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19742. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19743. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19744. }
  19745. }
  19746. exports.TorusBufferGeometry = TorusBufferGeometry;
  19747. class TorusGeometry extends Geometry {
  19748. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  19749. super();
  19750. this.type = 'TorusGeometry';
  19751. this.parameters = {
  19752. radius: radius,
  19753. tube: tube,
  19754. radialSegments: radialSegments,
  19755. tubularSegments: tubularSegments,
  19756. arc: arc
  19757. };
  19758. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  19759. this.mergeVertices();
  19760. }
  19761. }
  19762. exports.TorusGeometry = TorusGeometry;
  19763. class TorusKnotBufferGeometry extends BufferGeometry {
  19764. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  19765. super();
  19766. this.type = 'TorusKnotBufferGeometry';
  19767. this.parameters = {
  19768. radius: radius,
  19769. tube: tube,
  19770. tubularSegments: tubularSegments,
  19771. radialSegments: radialSegments,
  19772. p: p,
  19773. q: q
  19774. };
  19775. tubularSegments = Math.floor(tubularSegments);
  19776. radialSegments = Math.floor(radialSegments); // buffers
  19777. const indices = [];
  19778. const vertices = [];
  19779. const normals = [];
  19780. const uvs = []; // helper variables
  19781. const vertex = new Vector3();
  19782. const normal = new Vector3();
  19783. const P1 = new Vector3();
  19784. const P2 = new Vector3();
  19785. const B = new Vector3();
  19786. const T = new Vector3();
  19787. const N = new Vector3(); // generate vertices, normals and uvs
  19788. for (let i = 0; i <= tubularSegments; ++i) {
  19789. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19790. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19791. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19792. calculatePositionOnCurve(u, p, q, radius, P1);
  19793. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  19794. T.subVectors(P2, P1);
  19795. N.addVectors(P2, P1);
  19796. B.crossVectors(T, N);
  19797. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  19798. B.normalize();
  19799. N.normalize();
  19800. for (let j = 0; j <= radialSegments; ++j) {
  19801. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19802. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19803. const v = j / radialSegments * Math.PI * 2;
  19804. const cx = -tube * Math.cos(v);
  19805. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  19806. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19807. vertex.x = P1.x + (cx * N.x + cy * B.x);
  19808. vertex.y = P1.y + (cx * N.y + cy * B.y);
  19809. vertex.z = P1.z + (cx * N.z + cy * B.z);
  19810. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19811. normal.subVectors(vertex, P1).normalize();
  19812. normals.push(normal.x, normal.y, normal.z); // uv
  19813. uvs.push(i / tubularSegments);
  19814. uvs.push(j / radialSegments);
  19815. }
  19816. } // generate indices
  19817. for (let j = 1; j <= tubularSegments; j++) {
  19818. for (let i = 1; i <= radialSegments; i++) {
  19819. // indices
  19820. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19821. const b = (radialSegments + 1) * j + (i - 1);
  19822. const c = (radialSegments + 1) * j + i;
  19823. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19824. indices.push(a, b, d);
  19825. indices.push(b, c, d);
  19826. }
  19827. } // build geometry
  19828. this.setIndex(indices);
  19829. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19830. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19831. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  19832. function calculatePositionOnCurve(u, p, q, radius, position) {
  19833. const cu = Math.cos(u);
  19834. const su = Math.sin(u);
  19835. const quOverP = q / p * u;
  19836. const cs = Math.cos(quOverP);
  19837. position.x = radius * (2 + cs) * 0.5 * cu;
  19838. position.y = radius * (2 + cs) * su * 0.5;
  19839. position.z = radius * Math.sin(quOverP) * 0.5;
  19840. }
  19841. }
  19842. }
  19843. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  19844. class TorusKnotGeometry extends Geometry {
  19845. constructor(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  19846. super();
  19847. this.type = 'TorusKnotGeometry';
  19848. this.parameters = {
  19849. radius: radius,
  19850. tube: tube,
  19851. tubularSegments: tubularSegments,
  19852. radialSegments: radialSegments,
  19853. p: p,
  19854. q: q
  19855. };
  19856. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  19857. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  19858. this.mergeVertices();
  19859. }
  19860. }
  19861. exports.TorusKnotGeometry = TorusKnotGeometry;
  19862. class TubeBufferGeometry extends BufferGeometry {
  19863. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  19864. super();
  19865. this.type = 'TubeBufferGeometry';
  19866. this.parameters = {
  19867. path: path,
  19868. tubularSegments: tubularSegments,
  19869. radius: radius,
  19870. radialSegments: radialSegments,
  19871. closed: closed
  19872. };
  19873. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  19874. this.tangents = frames.tangents;
  19875. this.normals = frames.normals;
  19876. this.binormals = frames.binormals; // helper variables
  19877. const vertex = new Vector3();
  19878. const normal = new Vector3();
  19879. const uv = new Vector2();
  19880. let P = new Vector3(); // buffer
  19881. const vertices = [];
  19882. const normals = [];
  19883. const uvs = [];
  19884. const indices = []; // create buffer data
  19885. generateBufferData(); // build geometry
  19886. this.setIndex(indices);
  19887. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19888. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19889. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  19890. function generateBufferData() {
  19891. for (let i = 0; i < tubularSegments; i++) {
  19892. generateSegment(i);
  19893. } // if the geometry is not closed, generate the last row of vertices and normals
  19894. // at the regular position on the given path
  19895. //
  19896. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19897. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  19898. // this makes it easy compute correct values for closed geometries
  19899. generateUVs(); // finally create faces
  19900. generateIndices();
  19901. }
  19902. function generateSegment(i) {
  19903. // we use getPointAt to sample evenly distributed points from the given path
  19904. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  19905. const N = frames.normals[i];
  19906. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  19907. for (let j = 0; j <= radialSegments; j++) {
  19908. const v = j / radialSegments * Math.PI * 2;
  19909. const sin = Math.sin(v);
  19910. const cos = -Math.cos(v); // normal
  19911. normal.x = cos * N.x + sin * B.x;
  19912. normal.y = cos * N.y + sin * B.y;
  19913. normal.z = cos * N.z + sin * B.z;
  19914. normal.normalize();
  19915. normals.push(normal.x, normal.y, normal.z); // vertex
  19916. vertex.x = P.x + radius * normal.x;
  19917. vertex.y = P.y + radius * normal.y;
  19918. vertex.z = P.z + radius * normal.z;
  19919. vertices.push(vertex.x, vertex.y, vertex.z);
  19920. }
  19921. }
  19922. function generateIndices() {
  19923. for (let j = 1; j <= tubularSegments; j++) {
  19924. for (let i = 1; i <= radialSegments; i++) {
  19925. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19926. const b = (radialSegments + 1) * j + (i - 1);
  19927. const c = (radialSegments + 1) * j + i;
  19928. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19929. indices.push(a, b, d);
  19930. indices.push(b, c, d);
  19931. }
  19932. }
  19933. }
  19934. function generateUVs() {
  19935. for (let i = 0; i <= tubularSegments; i++) {
  19936. for (let j = 0; j <= radialSegments; j++) {
  19937. uv.x = i / tubularSegments;
  19938. uv.y = j / radialSegments;
  19939. uvs.push(uv.x, uv.y);
  19940. }
  19941. }
  19942. }
  19943. }
  19944. toJSON() {
  19945. const data = BufferGeometry.prototype.toJSON.call(this);
  19946. data.path = this.parameters.path.toJSON();
  19947. return data;
  19948. }
  19949. }
  19950. exports.TubeBufferGeometry = TubeBufferGeometry;
  19951. class TubeGeometry extends Geometry {
  19952. constructor(path, tubularSegments, radius, radialSegments, closed, taper) {
  19953. super();
  19954. this.type = 'TubeGeometry';
  19955. this.parameters = {
  19956. path: path,
  19957. tubularSegments: tubularSegments,
  19958. radius: radius,
  19959. radialSegments: radialSegments,
  19960. closed: closed
  19961. };
  19962. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  19963. const bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  19964. this.tangents = bufferGeometry.tangents;
  19965. this.normals = bufferGeometry.normals;
  19966. this.binormals = bufferGeometry.binormals; // create geometry
  19967. this.fromBufferGeometry(bufferGeometry);
  19968. this.mergeVertices();
  19969. }
  19970. }
  19971. exports.TubeGeometry = TubeGeometry;
  19972. class WireframeGeometry extends BufferGeometry {
  19973. constructor(geometry) {
  19974. super();
  19975. this.type = 'WireframeGeometry'; // buffer
  19976. const vertices = []; // helper variables
  19977. const edge = [0, 0],
  19978. edges = {};
  19979. const keys = ['a', 'b', 'c']; // different logic for Geometry and BufferGeometry
  19980. if (geometry && geometry.isGeometry) {
  19981. // create a data structure that contains all edges without duplicates
  19982. const faces = geometry.faces;
  19983. for (let i = 0, l = faces.length; i < l; i++) {
  19984. const face = faces[i];
  19985. for (let j = 0; j < 3; j++) {
  19986. const edge1 = face[keys[j]];
  19987. const edge2 = face[keys[(j + 1) % 3]];
  19988. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  19989. edge[1] = Math.max(edge1, edge2);
  19990. const key = edge[0] + ',' + edge[1];
  19991. if (edges[key] === undefined) {
  19992. edges[key] = {
  19993. index1: edge[0],
  19994. index2: edge[1]
  19995. };
  19996. }
  19997. }
  19998. } // generate vertices
  19999. for (const key in edges) {
  20000. const e = edges[key];
  20001. let vertex = geometry.vertices[e.index1];
  20002. vertices.push(vertex.x, vertex.y, vertex.z);
  20003. vertex = geometry.vertices[e.index2];
  20004. vertices.push(vertex.x, vertex.y, vertex.z);
  20005. }
  20006. } else if (geometry && geometry.isBufferGeometry) {
  20007. const vertex = new Vector3();
  20008. if (geometry.index !== null) {
  20009. // indexed BufferGeometry
  20010. const position = geometry.attributes.position;
  20011. const indices = geometry.index;
  20012. let groups = geometry.groups;
  20013. if (groups.length === 0) {
  20014. groups = [{
  20015. start: 0,
  20016. count: indices.count,
  20017. materialIndex: 0
  20018. }];
  20019. } // create a data structure that contains all eges without duplicates
  20020. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20021. const group = groups[o];
  20022. const start = group.start;
  20023. const count = group.count;
  20024. for (let i = start, l = start + count; i < l; i += 3) {
  20025. for (let j = 0; j < 3; j++) {
  20026. const edge1 = indices.getX(i + j);
  20027. const edge2 = indices.getX(i + (j + 1) % 3);
  20028. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  20029. edge[1] = Math.max(edge1, edge2);
  20030. const key = edge[0] + ',' + edge[1];
  20031. if (edges[key] === undefined) {
  20032. edges[key] = {
  20033. index1: edge[0],
  20034. index2: edge[1]
  20035. };
  20036. }
  20037. }
  20038. }
  20039. } // generate vertices
  20040. for (const key in edges) {
  20041. const e = edges[key];
  20042. vertex.fromBufferAttribute(position, e.index1);
  20043. vertices.push(vertex.x, vertex.y, vertex.z);
  20044. vertex.fromBufferAttribute(position, e.index2);
  20045. vertices.push(vertex.x, vertex.y, vertex.z);
  20046. }
  20047. } else {
  20048. // non-indexed BufferGeometry
  20049. const position = geometry.attributes.position;
  20050. for (let i = 0, l = position.count / 3; i < l; i++) {
  20051. for (let j = 0; j < 3; j++) {
  20052. // three edges per triangle, an edge is represented as (index1, index2)
  20053. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20054. const index1 = 3 * i + j;
  20055. vertex.fromBufferAttribute(position, index1);
  20056. vertices.push(vertex.x, vertex.y, vertex.z);
  20057. const index2 = 3 * i + (j + 1) % 3;
  20058. vertex.fromBufferAttribute(position, index2);
  20059. vertices.push(vertex.x, vertex.y, vertex.z);
  20060. }
  20061. }
  20062. }
  20063. } // build geometry
  20064. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20065. }
  20066. }
  20067. exports.WireframeGeometry = WireframeGeometry;
  20068. var Geometries =
  20069. /*#__PURE__*/
  20070. Object.freeze({
  20071. __proto__: null,
  20072. BoxGeometry: BoxGeometry,
  20073. BoxBufferGeometry: BoxBufferGeometry,
  20074. CircleGeometry: CircleGeometry,
  20075. CircleBufferGeometry: CircleBufferGeometry,
  20076. ConeGeometry: ConeGeometry,
  20077. ConeBufferGeometry: ConeBufferGeometry,
  20078. CylinderGeometry: CylinderGeometry,
  20079. CylinderBufferGeometry: CylinderBufferGeometry,
  20080. DodecahedronGeometry: DodecahedronGeometry,
  20081. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20082. EdgesGeometry: EdgesGeometry,
  20083. ExtrudeGeometry: ExtrudeGeometry,
  20084. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20085. IcosahedronGeometry: IcosahedronGeometry,
  20086. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20087. LatheGeometry: LatheGeometry,
  20088. LatheBufferGeometry: LatheBufferGeometry,
  20089. OctahedronGeometry: OctahedronGeometry,
  20090. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20091. ParametricGeometry: ParametricGeometry,
  20092. ParametricBufferGeometry: ParametricBufferGeometry,
  20093. PlaneGeometry: PlaneGeometry,
  20094. PlaneBufferGeometry: PlaneBufferGeometry,
  20095. PolyhedronGeometry: PolyhedronGeometry,
  20096. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20097. RingGeometry: RingGeometry,
  20098. RingBufferGeometry: RingBufferGeometry,
  20099. ShapeGeometry: ShapeGeometry,
  20100. ShapeBufferGeometry: ShapeBufferGeometry,
  20101. SphereGeometry: SphereGeometry,
  20102. SphereBufferGeometry: SphereBufferGeometry,
  20103. TetrahedronGeometry: TetrahedronGeometry,
  20104. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20105. TextGeometry: TextGeometry,
  20106. TextBufferGeometry: TextBufferGeometry,
  20107. TorusGeometry: TorusGeometry,
  20108. TorusBufferGeometry: TorusBufferGeometry,
  20109. TorusKnotGeometry: TorusKnotGeometry,
  20110. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20111. TubeGeometry: TubeGeometry,
  20112. TubeBufferGeometry: TubeBufferGeometry,
  20113. WireframeGeometry: WireframeGeometry
  20114. });
  20115. /**
  20116. * parameters = {
  20117. * color: <THREE.Color>
  20118. * }
  20119. */
  20120. function ShadowMaterial(parameters) {
  20121. Material.call(this);
  20122. this.type = 'ShadowMaterial';
  20123. this.color = new Color(0x000000);
  20124. this.transparent = true;
  20125. this.setValues(parameters);
  20126. }
  20127. ShadowMaterial.prototype = Object.create(Material.prototype);
  20128. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20129. ShadowMaterial.prototype.isShadowMaterial = true;
  20130. ShadowMaterial.prototype.copy = function (source) {
  20131. Material.prototype.copy.call(this, source);
  20132. this.color.copy(source.color);
  20133. return this;
  20134. };
  20135. function RawShaderMaterial(parameters) {
  20136. ShaderMaterial.call(this, parameters);
  20137. this.type = 'RawShaderMaterial';
  20138. }
  20139. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20140. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20141. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20142. /**
  20143. * parameters = {
  20144. * color: <hex>,
  20145. * roughness: <float>,
  20146. * metalness: <float>,
  20147. * opacity: <float>,
  20148. *
  20149. * map: new THREE.Texture( <Image> ),
  20150. *
  20151. * lightMap: new THREE.Texture( <Image> ),
  20152. * lightMapIntensity: <float>
  20153. *
  20154. * aoMap: new THREE.Texture( <Image> ),
  20155. * aoMapIntensity: <float>
  20156. *
  20157. * emissive: <hex>,
  20158. * emissiveIntensity: <float>
  20159. * emissiveMap: new THREE.Texture( <Image> ),
  20160. *
  20161. * bumpMap: new THREE.Texture( <Image> ),
  20162. * bumpScale: <float>,
  20163. *
  20164. * normalMap: new THREE.Texture( <Image> ),
  20165. * normalMapType: THREE.TangentSpaceNormalMap,
  20166. * normalScale: <Vector2>,
  20167. *
  20168. * displacementMap: new THREE.Texture( <Image> ),
  20169. * displacementScale: <float>,
  20170. * displacementBias: <float>,
  20171. *
  20172. * roughnessMap: new THREE.Texture( <Image> ),
  20173. *
  20174. * metalnessMap: new THREE.Texture( <Image> ),
  20175. *
  20176. * alphaMap: new THREE.Texture( <Image> ),
  20177. *
  20178. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20179. * envMapIntensity: <float>
  20180. *
  20181. * refractionRatio: <float>,
  20182. *
  20183. * wireframe: <boolean>,
  20184. * wireframeLinewidth: <float>,
  20185. *
  20186. * skinning: <bool>,
  20187. * morphTargets: <bool>,
  20188. * morphNormals: <bool>
  20189. * }
  20190. */
  20191. function MeshStandardMaterial(parameters) {
  20192. Material.call(this);
  20193. this.defines = {
  20194. 'STANDARD': ''
  20195. };
  20196. this.type = 'MeshStandardMaterial';
  20197. this.color = new Color(0xffffff); // diffuse
  20198. this.roughness = 1.0;
  20199. this.metalness = 0.0;
  20200. this.map = null;
  20201. this.lightMap = null;
  20202. this.lightMapIntensity = 1.0;
  20203. this.aoMap = null;
  20204. this.aoMapIntensity = 1.0;
  20205. this.emissive = new Color(0x000000);
  20206. this.emissiveIntensity = 1.0;
  20207. this.emissiveMap = null;
  20208. this.bumpMap = null;
  20209. this.bumpScale = 1;
  20210. this.normalMap = null;
  20211. this.normalMapType = TangentSpaceNormalMap;
  20212. this.normalScale = new Vector2(1, 1);
  20213. this.displacementMap = null;
  20214. this.displacementScale = 1;
  20215. this.displacementBias = 0;
  20216. this.roughnessMap = null;
  20217. this.metalnessMap = null;
  20218. this.alphaMap = null;
  20219. this.envMap = null;
  20220. this.envMapIntensity = 1.0;
  20221. this.refractionRatio = 0.98;
  20222. this.wireframe = false;
  20223. this.wireframeLinewidth = 1;
  20224. this.wireframeLinecap = 'round';
  20225. this.wireframeLinejoin = 'round';
  20226. this.skinning = false;
  20227. this.morphTargets = false;
  20228. this.morphNormals = false;
  20229. this.vertexTangents = false;
  20230. this.setValues(parameters);
  20231. }
  20232. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20233. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20234. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20235. MeshStandardMaterial.prototype.copy = function (source) {
  20236. Material.prototype.copy.call(this, source);
  20237. this.defines = {
  20238. 'STANDARD': ''
  20239. };
  20240. this.color.copy(source.color);
  20241. this.roughness = source.roughness;
  20242. this.metalness = source.metalness;
  20243. this.map = source.map;
  20244. this.lightMap = source.lightMap;
  20245. this.lightMapIntensity = source.lightMapIntensity;
  20246. this.aoMap = source.aoMap;
  20247. this.aoMapIntensity = source.aoMapIntensity;
  20248. this.emissive.copy(source.emissive);
  20249. this.emissiveMap = source.emissiveMap;
  20250. this.emissiveIntensity = source.emissiveIntensity;
  20251. this.bumpMap = source.bumpMap;
  20252. this.bumpScale = source.bumpScale;
  20253. this.normalMap = source.normalMap;
  20254. this.normalMapType = source.normalMapType;
  20255. this.normalScale.copy(source.normalScale);
  20256. this.displacementMap = source.displacementMap;
  20257. this.displacementScale = source.displacementScale;
  20258. this.displacementBias = source.displacementBias;
  20259. this.roughnessMap = source.roughnessMap;
  20260. this.metalnessMap = source.metalnessMap;
  20261. this.alphaMap = source.alphaMap;
  20262. this.envMap = source.envMap;
  20263. this.envMapIntensity = source.envMapIntensity;
  20264. this.refractionRatio = source.refractionRatio;
  20265. this.wireframe = source.wireframe;
  20266. this.wireframeLinewidth = source.wireframeLinewidth;
  20267. this.wireframeLinecap = source.wireframeLinecap;
  20268. this.wireframeLinejoin = source.wireframeLinejoin;
  20269. this.skinning = source.skinning;
  20270. this.morphTargets = source.morphTargets;
  20271. this.morphNormals = source.morphNormals;
  20272. this.vertexTangents = source.vertexTangents;
  20273. return this;
  20274. };
  20275. /**
  20276. * parameters = {
  20277. * clearcoat: <float>,
  20278. * clearcoatMap: new THREE.Texture( <Image> ),
  20279. * clearcoatRoughness: <float>,
  20280. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20281. * clearcoatNormalScale: <Vector2>,
  20282. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20283. *
  20284. * reflectivity: <float>,
  20285. * ior: <float>,
  20286. *
  20287. * sheen: <Color>,
  20288. *
  20289. * transmission: <float>,
  20290. * transmissionMap: new THREE.Texture( <Image> )
  20291. * }
  20292. */
  20293. function MeshPhysicalMaterial(parameters) {
  20294. MeshStandardMaterial.call(this);
  20295. this.defines = {
  20296. 'STANDARD': '',
  20297. 'PHYSICAL': ''
  20298. };
  20299. this.type = 'MeshPhysicalMaterial';
  20300. this.clearcoat = 0.0;
  20301. this.clearcoatMap = null;
  20302. this.clearcoatRoughness = 0.0;
  20303. this.clearcoatRoughnessMap = null;
  20304. this.clearcoatNormalScale = new Vector2(1, 1);
  20305. this.clearcoatNormalMap = null;
  20306. this.reflectivity = 0.5; // maps to F0 = 0.04
  20307. Object.defineProperty(this, 'ior', {
  20308. get: function () {
  20309. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  20310. },
  20311. set: function (ior) {
  20312. this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  20313. }
  20314. });
  20315. this.sheen = null; // null will disable sheen bsdf
  20316. this.transmission = 0.0;
  20317. this.transmissionMap = null;
  20318. this.setValues(parameters);
  20319. }
  20320. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20321. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20322. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20323. MeshPhysicalMaterial.prototype.copy = function (source) {
  20324. MeshStandardMaterial.prototype.copy.call(this, source);
  20325. this.defines = {
  20326. 'STANDARD': '',
  20327. 'PHYSICAL': ''
  20328. };
  20329. this.clearcoat = source.clearcoat;
  20330. this.clearcoatMap = source.clearcoatMap;
  20331. this.clearcoatRoughness = source.clearcoatRoughness;
  20332. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20333. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20334. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20335. this.reflectivity = source.reflectivity;
  20336. if (source.sheen) {
  20337. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  20338. } else {
  20339. this.sheen = null;
  20340. }
  20341. this.transmission = source.transmission;
  20342. this.transmissionMap = source.transmissionMap;
  20343. return this;
  20344. };
  20345. /**
  20346. * parameters = {
  20347. * color: <hex>,
  20348. * specular: <hex>,
  20349. * shininess: <float>,
  20350. * opacity: <float>,
  20351. *
  20352. * map: new THREE.Texture( <Image> ),
  20353. *
  20354. * lightMap: new THREE.Texture( <Image> ),
  20355. * lightMapIntensity: <float>
  20356. *
  20357. * aoMap: new THREE.Texture( <Image> ),
  20358. * aoMapIntensity: <float>
  20359. *
  20360. * emissive: <hex>,
  20361. * emissiveIntensity: <float>
  20362. * emissiveMap: new THREE.Texture( <Image> ),
  20363. *
  20364. * bumpMap: new THREE.Texture( <Image> ),
  20365. * bumpScale: <float>,
  20366. *
  20367. * normalMap: new THREE.Texture( <Image> ),
  20368. * normalMapType: THREE.TangentSpaceNormalMap,
  20369. * normalScale: <Vector2>,
  20370. *
  20371. * displacementMap: new THREE.Texture( <Image> ),
  20372. * displacementScale: <float>,
  20373. * displacementBias: <float>,
  20374. *
  20375. * specularMap: new THREE.Texture( <Image> ),
  20376. *
  20377. * alphaMap: new THREE.Texture( <Image> ),
  20378. *
  20379. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20380. * combine: THREE.MultiplyOperation,
  20381. * reflectivity: <float>,
  20382. * refractionRatio: <float>,
  20383. *
  20384. * wireframe: <boolean>,
  20385. * wireframeLinewidth: <float>,
  20386. *
  20387. * skinning: <bool>,
  20388. * morphTargets: <bool>,
  20389. * morphNormals: <bool>
  20390. * }
  20391. */
  20392. function MeshPhongMaterial(parameters) {
  20393. Material.call(this);
  20394. this.type = 'MeshPhongMaterial';
  20395. this.color = new Color(0xffffff); // diffuse
  20396. this.specular = new Color(0x111111);
  20397. this.shininess = 30;
  20398. this.map = null;
  20399. this.lightMap = null;
  20400. this.lightMapIntensity = 1.0;
  20401. this.aoMap = null;
  20402. this.aoMapIntensity = 1.0;
  20403. this.emissive = new Color(0x000000);
  20404. this.emissiveIntensity = 1.0;
  20405. this.emissiveMap = null;
  20406. this.bumpMap = null;
  20407. this.bumpScale = 1;
  20408. this.normalMap = null;
  20409. this.normalMapType = TangentSpaceNormalMap;
  20410. this.normalScale = new Vector2(1, 1);
  20411. this.displacementMap = null;
  20412. this.displacementScale = 1;
  20413. this.displacementBias = 0;
  20414. this.specularMap = null;
  20415. this.alphaMap = null;
  20416. this.envMap = null;
  20417. this.combine = MultiplyOperation;
  20418. this.reflectivity = 1;
  20419. this.refractionRatio = 0.98;
  20420. this.wireframe = false;
  20421. this.wireframeLinewidth = 1;
  20422. this.wireframeLinecap = 'round';
  20423. this.wireframeLinejoin = 'round';
  20424. this.skinning = false;
  20425. this.morphTargets = false;
  20426. this.morphNormals = false;
  20427. this.setValues(parameters);
  20428. }
  20429. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20430. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20431. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20432. MeshPhongMaterial.prototype.copy = function (source) {
  20433. Material.prototype.copy.call(this, source);
  20434. this.color.copy(source.color);
  20435. this.specular.copy(source.specular);
  20436. this.shininess = source.shininess;
  20437. this.map = source.map;
  20438. this.lightMap = source.lightMap;
  20439. this.lightMapIntensity = source.lightMapIntensity;
  20440. this.aoMap = source.aoMap;
  20441. this.aoMapIntensity = source.aoMapIntensity;
  20442. this.emissive.copy(source.emissive);
  20443. this.emissiveMap = source.emissiveMap;
  20444. this.emissiveIntensity = source.emissiveIntensity;
  20445. this.bumpMap = source.bumpMap;
  20446. this.bumpScale = source.bumpScale;
  20447. this.normalMap = source.normalMap;
  20448. this.normalMapType = source.normalMapType;
  20449. this.normalScale.copy(source.normalScale);
  20450. this.displacementMap = source.displacementMap;
  20451. this.displacementScale = source.displacementScale;
  20452. this.displacementBias = source.displacementBias;
  20453. this.specularMap = source.specularMap;
  20454. this.alphaMap = source.alphaMap;
  20455. this.envMap = source.envMap;
  20456. this.combine = source.combine;
  20457. this.reflectivity = source.reflectivity;
  20458. this.refractionRatio = source.refractionRatio;
  20459. this.wireframe = source.wireframe;
  20460. this.wireframeLinewidth = source.wireframeLinewidth;
  20461. this.wireframeLinecap = source.wireframeLinecap;
  20462. this.wireframeLinejoin = source.wireframeLinejoin;
  20463. this.skinning = source.skinning;
  20464. this.morphTargets = source.morphTargets;
  20465. this.morphNormals = source.morphNormals;
  20466. return this;
  20467. };
  20468. /**
  20469. * parameters = {
  20470. * color: <hex>,
  20471. *
  20472. * map: new THREE.Texture( <Image> ),
  20473. * gradientMap: new THREE.Texture( <Image> ),
  20474. *
  20475. * lightMap: new THREE.Texture( <Image> ),
  20476. * lightMapIntensity: <float>
  20477. *
  20478. * aoMap: new THREE.Texture( <Image> ),
  20479. * aoMapIntensity: <float>
  20480. *
  20481. * emissive: <hex>,
  20482. * emissiveIntensity: <float>
  20483. * emissiveMap: new THREE.Texture( <Image> ),
  20484. *
  20485. * bumpMap: new THREE.Texture( <Image> ),
  20486. * bumpScale: <float>,
  20487. *
  20488. * normalMap: new THREE.Texture( <Image> ),
  20489. * normalMapType: THREE.TangentSpaceNormalMap,
  20490. * normalScale: <Vector2>,
  20491. *
  20492. * displacementMap: new THREE.Texture( <Image> ),
  20493. * displacementScale: <float>,
  20494. * displacementBias: <float>,
  20495. *
  20496. * alphaMap: new THREE.Texture( <Image> ),
  20497. *
  20498. * wireframe: <boolean>,
  20499. * wireframeLinewidth: <float>,
  20500. *
  20501. * skinning: <bool>,
  20502. * morphTargets: <bool>,
  20503. * morphNormals: <bool>
  20504. * }
  20505. */
  20506. function MeshToonMaterial(parameters) {
  20507. Material.call(this);
  20508. this.defines = {
  20509. 'TOON': ''
  20510. };
  20511. this.type = 'MeshToonMaterial';
  20512. this.color = new Color(0xffffff);
  20513. this.map = null;
  20514. this.gradientMap = null;
  20515. this.lightMap = null;
  20516. this.lightMapIntensity = 1.0;
  20517. this.aoMap = null;
  20518. this.aoMapIntensity = 1.0;
  20519. this.emissive = new Color(0x000000);
  20520. this.emissiveIntensity = 1.0;
  20521. this.emissiveMap = null;
  20522. this.bumpMap = null;
  20523. this.bumpScale = 1;
  20524. this.normalMap = null;
  20525. this.normalMapType = TangentSpaceNormalMap;
  20526. this.normalScale = new Vector2(1, 1);
  20527. this.displacementMap = null;
  20528. this.displacementScale = 1;
  20529. this.displacementBias = 0;
  20530. this.alphaMap = null;
  20531. this.wireframe = false;
  20532. this.wireframeLinewidth = 1;
  20533. this.wireframeLinecap = 'round';
  20534. this.wireframeLinejoin = 'round';
  20535. this.skinning = false;
  20536. this.morphTargets = false;
  20537. this.morphNormals = false;
  20538. this.setValues(parameters);
  20539. }
  20540. MeshToonMaterial.prototype = Object.create(Material.prototype);
  20541. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20542. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20543. MeshToonMaterial.prototype.copy = function (source) {
  20544. Material.prototype.copy.call(this, source);
  20545. this.color.copy(source.color);
  20546. this.map = source.map;
  20547. this.gradientMap = source.gradientMap;
  20548. this.lightMap = source.lightMap;
  20549. this.lightMapIntensity = source.lightMapIntensity;
  20550. this.aoMap = source.aoMap;
  20551. this.aoMapIntensity = source.aoMapIntensity;
  20552. this.emissive.copy(source.emissive);
  20553. this.emissiveMap = source.emissiveMap;
  20554. this.emissiveIntensity = source.emissiveIntensity;
  20555. this.bumpMap = source.bumpMap;
  20556. this.bumpScale = source.bumpScale;
  20557. this.normalMap = source.normalMap;
  20558. this.normalMapType = source.normalMapType;
  20559. this.normalScale.copy(source.normalScale);
  20560. this.displacementMap = source.displacementMap;
  20561. this.displacementScale = source.displacementScale;
  20562. this.displacementBias = source.displacementBias;
  20563. this.alphaMap = source.alphaMap;
  20564. this.wireframe = source.wireframe;
  20565. this.wireframeLinewidth = source.wireframeLinewidth;
  20566. this.wireframeLinecap = source.wireframeLinecap;
  20567. this.wireframeLinejoin = source.wireframeLinejoin;
  20568. this.skinning = source.skinning;
  20569. this.morphTargets = source.morphTargets;
  20570. this.morphNormals = source.morphNormals;
  20571. return this;
  20572. };
  20573. /**
  20574. * parameters = {
  20575. * opacity: <float>,
  20576. *
  20577. * bumpMap: new THREE.Texture( <Image> ),
  20578. * bumpScale: <float>,
  20579. *
  20580. * normalMap: new THREE.Texture( <Image> ),
  20581. * normalMapType: THREE.TangentSpaceNormalMap,
  20582. * normalScale: <Vector2>,
  20583. *
  20584. * displacementMap: new THREE.Texture( <Image> ),
  20585. * displacementScale: <float>,
  20586. * displacementBias: <float>,
  20587. *
  20588. * wireframe: <boolean>,
  20589. * wireframeLinewidth: <float>
  20590. *
  20591. * skinning: <bool>,
  20592. * morphTargets: <bool>,
  20593. * morphNormals: <bool>
  20594. * }
  20595. */
  20596. function MeshNormalMaterial(parameters) {
  20597. Material.call(this);
  20598. this.type = 'MeshNormalMaterial';
  20599. this.bumpMap = null;
  20600. this.bumpScale = 1;
  20601. this.normalMap = null;
  20602. this.normalMapType = TangentSpaceNormalMap;
  20603. this.normalScale = new Vector2(1, 1);
  20604. this.displacementMap = null;
  20605. this.displacementScale = 1;
  20606. this.displacementBias = 0;
  20607. this.wireframe = false;
  20608. this.wireframeLinewidth = 1;
  20609. this.fog = false;
  20610. this.skinning = false;
  20611. this.morphTargets = false;
  20612. this.morphNormals = false;
  20613. this.setValues(parameters);
  20614. }
  20615. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20616. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20617. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20618. MeshNormalMaterial.prototype.copy = function (source) {
  20619. Material.prototype.copy.call(this, source);
  20620. this.bumpMap = source.bumpMap;
  20621. this.bumpScale = source.bumpScale;
  20622. this.normalMap = source.normalMap;
  20623. this.normalMapType = source.normalMapType;
  20624. this.normalScale.copy(source.normalScale);
  20625. this.displacementMap = source.displacementMap;
  20626. this.displacementScale = source.displacementScale;
  20627. this.displacementBias = source.displacementBias;
  20628. this.wireframe = source.wireframe;
  20629. this.wireframeLinewidth = source.wireframeLinewidth;
  20630. this.skinning = source.skinning;
  20631. this.morphTargets = source.morphTargets;
  20632. this.morphNormals = source.morphNormals;
  20633. return this;
  20634. };
  20635. /**
  20636. * parameters = {
  20637. * color: <hex>,
  20638. * opacity: <float>,
  20639. *
  20640. * map: new THREE.Texture( <Image> ),
  20641. *
  20642. * lightMap: new THREE.Texture( <Image> ),
  20643. * lightMapIntensity: <float>
  20644. *
  20645. * aoMap: new THREE.Texture( <Image> ),
  20646. * aoMapIntensity: <float>
  20647. *
  20648. * emissive: <hex>,
  20649. * emissiveIntensity: <float>
  20650. * emissiveMap: new THREE.Texture( <Image> ),
  20651. *
  20652. * specularMap: new THREE.Texture( <Image> ),
  20653. *
  20654. * alphaMap: new THREE.Texture( <Image> ),
  20655. *
  20656. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20657. * combine: THREE.Multiply,
  20658. * reflectivity: <float>,
  20659. * refractionRatio: <float>,
  20660. *
  20661. * wireframe: <boolean>,
  20662. * wireframeLinewidth: <float>,
  20663. *
  20664. * skinning: <bool>,
  20665. * morphTargets: <bool>,
  20666. * morphNormals: <bool>
  20667. * }
  20668. */
  20669. function MeshLambertMaterial(parameters) {
  20670. Material.call(this);
  20671. this.type = 'MeshLambertMaterial';
  20672. this.color = new Color(0xffffff); // diffuse
  20673. this.map = null;
  20674. this.lightMap = null;
  20675. this.lightMapIntensity = 1.0;
  20676. this.aoMap = null;
  20677. this.aoMapIntensity = 1.0;
  20678. this.emissive = new Color(0x000000);
  20679. this.emissiveIntensity = 1.0;
  20680. this.emissiveMap = null;
  20681. this.specularMap = null;
  20682. this.alphaMap = null;
  20683. this.envMap = null;
  20684. this.combine = MultiplyOperation;
  20685. this.reflectivity = 1;
  20686. this.refractionRatio = 0.98;
  20687. this.wireframe = false;
  20688. this.wireframeLinewidth = 1;
  20689. this.wireframeLinecap = 'round';
  20690. this.wireframeLinejoin = 'round';
  20691. this.skinning = false;
  20692. this.morphTargets = false;
  20693. this.morphNormals = false;
  20694. this.setValues(parameters);
  20695. }
  20696. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  20697. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20698. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20699. MeshLambertMaterial.prototype.copy = function (source) {
  20700. Material.prototype.copy.call(this, source);
  20701. this.color.copy(source.color);
  20702. this.map = source.map;
  20703. this.lightMap = source.lightMap;
  20704. this.lightMapIntensity = source.lightMapIntensity;
  20705. this.aoMap = source.aoMap;
  20706. this.aoMapIntensity = source.aoMapIntensity;
  20707. this.emissive.copy(source.emissive);
  20708. this.emissiveMap = source.emissiveMap;
  20709. this.emissiveIntensity = source.emissiveIntensity;
  20710. this.specularMap = source.specularMap;
  20711. this.alphaMap = source.alphaMap;
  20712. this.envMap = source.envMap;
  20713. this.combine = source.combine;
  20714. this.reflectivity = source.reflectivity;
  20715. this.refractionRatio = source.refractionRatio;
  20716. this.wireframe = source.wireframe;
  20717. this.wireframeLinewidth = source.wireframeLinewidth;
  20718. this.wireframeLinecap = source.wireframeLinecap;
  20719. this.wireframeLinejoin = source.wireframeLinejoin;
  20720. this.skinning = source.skinning;
  20721. this.morphTargets = source.morphTargets;
  20722. this.morphNormals = source.morphNormals;
  20723. return this;
  20724. };
  20725. /**
  20726. * parameters = {
  20727. * color: <hex>,
  20728. * opacity: <float>,
  20729. *
  20730. * matcap: new THREE.Texture( <Image> ),
  20731. *
  20732. * map: new THREE.Texture( <Image> ),
  20733. *
  20734. * bumpMap: new THREE.Texture( <Image> ),
  20735. * bumpScale: <float>,
  20736. *
  20737. * normalMap: new THREE.Texture( <Image> ),
  20738. * normalMapType: THREE.TangentSpaceNormalMap,
  20739. * normalScale: <Vector2>,
  20740. *
  20741. * displacementMap: new THREE.Texture( <Image> ),
  20742. * displacementScale: <float>,
  20743. * displacementBias: <float>,
  20744. *
  20745. * alphaMap: new THREE.Texture( <Image> ),
  20746. *
  20747. * skinning: <bool>,
  20748. * morphTargets: <bool>,
  20749. * morphNormals: <bool>
  20750. * }
  20751. */
  20752. function MeshMatcapMaterial(parameters) {
  20753. Material.call(this);
  20754. this.defines = {
  20755. 'MATCAP': ''
  20756. };
  20757. this.type = 'MeshMatcapMaterial';
  20758. this.color = new Color(0xffffff); // diffuse
  20759. this.matcap = null;
  20760. this.map = null;
  20761. this.bumpMap = null;
  20762. this.bumpScale = 1;
  20763. this.normalMap = null;
  20764. this.normalMapType = TangentSpaceNormalMap;
  20765. this.normalScale = new Vector2(1, 1);
  20766. this.displacementMap = null;
  20767. this.displacementScale = 1;
  20768. this.displacementBias = 0;
  20769. this.alphaMap = null;
  20770. this.skinning = false;
  20771. this.morphTargets = false;
  20772. this.morphNormals = false;
  20773. this.setValues(parameters);
  20774. }
  20775. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20776. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20777. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20778. MeshMatcapMaterial.prototype.copy = function (source) {
  20779. Material.prototype.copy.call(this, source);
  20780. this.defines = {
  20781. 'MATCAP': ''
  20782. };
  20783. this.color.copy(source.color);
  20784. this.matcap = source.matcap;
  20785. this.map = source.map;
  20786. this.bumpMap = source.bumpMap;
  20787. this.bumpScale = source.bumpScale;
  20788. this.normalMap = source.normalMap;
  20789. this.normalMapType = source.normalMapType;
  20790. this.normalScale.copy(source.normalScale);
  20791. this.displacementMap = source.displacementMap;
  20792. this.displacementScale = source.displacementScale;
  20793. this.displacementBias = source.displacementBias;
  20794. this.alphaMap = source.alphaMap;
  20795. this.skinning = source.skinning;
  20796. this.morphTargets = source.morphTargets;
  20797. this.morphNormals = source.morphNormals;
  20798. return this;
  20799. };
  20800. /**
  20801. * parameters = {
  20802. * color: <hex>,
  20803. * opacity: <float>,
  20804. *
  20805. * linewidth: <float>,
  20806. *
  20807. * scale: <float>,
  20808. * dashSize: <float>,
  20809. * gapSize: <float>
  20810. * }
  20811. */
  20812. function LineDashedMaterial(parameters) {
  20813. LineBasicMaterial.call(this);
  20814. this.type = 'LineDashedMaterial';
  20815. this.scale = 1;
  20816. this.dashSize = 3;
  20817. this.gapSize = 1;
  20818. this.setValues(parameters);
  20819. }
  20820. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20821. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20822. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20823. LineDashedMaterial.prototype.copy = function (source) {
  20824. LineBasicMaterial.prototype.copy.call(this, source);
  20825. this.scale = source.scale;
  20826. this.dashSize = source.dashSize;
  20827. this.gapSize = source.gapSize;
  20828. return this;
  20829. };
  20830. var Materials =
  20831. /*#__PURE__*/
  20832. Object.freeze({
  20833. __proto__: null,
  20834. ShadowMaterial: ShadowMaterial,
  20835. SpriteMaterial: SpriteMaterial,
  20836. RawShaderMaterial: RawShaderMaterial,
  20837. ShaderMaterial: ShaderMaterial,
  20838. PointsMaterial: PointsMaterial,
  20839. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20840. MeshStandardMaterial: MeshStandardMaterial,
  20841. MeshPhongMaterial: MeshPhongMaterial,
  20842. MeshToonMaterial: MeshToonMaterial,
  20843. MeshNormalMaterial: MeshNormalMaterial,
  20844. MeshLambertMaterial: MeshLambertMaterial,
  20845. MeshDepthMaterial: MeshDepthMaterial,
  20846. MeshDistanceMaterial: MeshDistanceMaterial,
  20847. MeshBasicMaterial: MeshBasicMaterial,
  20848. MeshMatcapMaterial: MeshMatcapMaterial,
  20849. LineDashedMaterial: LineDashedMaterial,
  20850. LineBasicMaterial: LineBasicMaterial,
  20851. Material: Material
  20852. });
  20853. const AnimationUtils = {
  20854. // same as Array.prototype.slice, but also works on typed arrays
  20855. arraySlice: function (array, from, to) {
  20856. if (AnimationUtils.isTypedArray(array)) {
  20857. // in ios9 array.subarray(from, undefined) will return empty array
  20858. // but array.subarray(from) or array.subarray(from, len) is correct
  20859. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20860. }
  20861. return array.slice(from, to);
  20862. },
  20863. // converts an array to a specific type
  20864. convertArray: function (array, type, forceClone) {
  20865. if (!array || // let 'undefined' and 'null' pass
  20866. !forceClone && array.constructor === type) return array;
  20867. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20868. return new type(array); // create typed array
  20869. }
  20870. return Array.prototype.slice.call(array); // create Array
  20871. },
  20872. isTypedArray: function (object) {
  20873. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20874. },
  20875. // returns an array by which times and values can be sorted
  20876. getKeyframeOrder: function (times) {
  20877. function compareTime(i, j) {
  20878. return times[i] - times[j];
  20879. }
  20880. const n = times.length;
  20881. const result = new Array(n);
  20882. for (let i = 0; i !== n; ++i) result[i] = i;
  20883. result.sort(compareTime);
  20884. return result;
  20885. },
  20886. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20887. sortedArray: function (values, stride, order) {
  20888. const nValues = values.length;
  20889. const result = new values.constructor(nValues);
  20890. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20891. const srcOffset = order[i] * stride;
  20892. for (let j = 0; j !== stride; ++j) {
  20893. result[dstOffset++] = values[srcOffset + j];
  20894. }
  20895. }
  20896. return result;
  20897. },
  20898. // function for parsing AOS keyframe formats
  20899. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20900. let i = 1,
  20901. key = jsonKeys[0];
  20902. while (key !== undefined && key[valuePropertyName] === undefined) {
  20903. key = jsonKeys[i++];
  20904. }
  20905. if (key === undefined) return; // no data
  20906. let value = key[valuePropertyName];
  20907. if (value === undefined) return; // no data
  20908. if (Array.isArray(value)) {
  20909. do {
  20910. value = key[valuePropertyName];
  20911. if (value !== undefined) {
  20912. times.push(key.time);
  20913. values.push.apply(values, value); // push all elements
  20914. }
  20915. key = jsonKeys[i++];
  20916. } while (key !== undefined);
  20917. } else if (value.toArray !== undefined) {
  20918. // ...assume THREE.Math-ish
  20919. do {
  20920. value = key[valuePropertyName];
  20921. if (value !== undefined) {
  20922. times.push(key.time);
  20923. value.toArray(values, values.length);
  20924. }
  20925. key = jsonKeys[i++];
  20926. } while (key !== undefined);
  20927. } else {
  20928. // otherwise push as-is
  20929. do {
  20930. value = key[valuePropertyName];
  20931. if (value !== undefined) {
  20932. times.push(key.time);
  20933. values.push(value);
  20934. }
  20935. key = jsonKeys[i++];
  20936. } while (key !== undefined);
  20937. }
  20938. },
  20939. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  20940. const clip = sourceClip.clone();
  20941. clip.name = name;
  20942. const tracks = [];
  20943. for (let i = 0; i < clip.tracks.length; ++i) {
  20944. const track = clip.tracks[i];
  20945. const valueSize = track.getValueSize();
  20946. const times = [];
  20947. const values = [];
  20948. for (let j = 0; j < track.times.length; ++j) {
  20949. const frame = track.times[j] * fps;
  20950. if (frame < startFrame || frame >= endFrame) continue;
  20951. times.push(track.times[j]);
  20952. for (let k = 0; k < valueSize; ++k) {
  20953. values.push(track.values[j * valueSize + k]);
  20954. }
  20955. }
  20956. if (times.length === 0) continue;
  20957. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20958. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20959. tracks.push(track);
  20960. }
  20961. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20962. let minStartTime = Infinity;
  20963. for (let i = 0; i < clip.tracks.length; ++i) {
  20964. if (minStartTime > clip.tracks[i].times[0]) {
  20965. minStartTime = clip.tracks[i].times[0];
  20966. }
  20967. } // shift all tracks such that clip begins at t=0
  20968. for (let i = 0; i < clip.tracks.length; ++i) {
  20969. clip.tracks[i].shift(-1 * minStartTime);
  20970. }
  20971. clip.resetDuration();
  20972. return clip;
  20973. },
  20974. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  20975. if (fps <= 0) fps = 30;
  20976. const numTracks = referenceClip.tracks.length;
  20977. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  20978. for (let i = 0; i < numTracks; ++i) {
  20979. const referenceTrack = referenceClip.tracks[i];
  20980. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  20981. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  20982. const targetTrack = targetClip.tracks.find(function (track) {
  20983. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  20984. });
  20985. if (targetTrack === undefined) continue;
  20986. let referenceOffset = 0;
  20987. const referenceValueSize = referenceTrack.getValueSize();
  20988. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20989. referenceOffset = referenceValueSize / 3;
  20990. }
  20991. let targetOffset = 0;
  20992. const targetValueSize = targetTrack.getValueSize();
  20993. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20994. targetOffset = targetValueSize / 3;
  20995. }
  20996. const lastIndex = referenceTrack.times.length - 1;
  20997. let referenceValue; // Find the value to subtract out of the track
  20998. if (referenceTime <= referenceTrack.times[0]) {
  20999. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21000. const startIndex = referenceOffset;
  21001. const endIndex = referenceValueSize - referenceOffset;
  21002. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21003. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21004. // Reference frame is after the last keyframe, so just use the last keyframe
  21005. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21006. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21007. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21008. } else {
  21009. // Interpolate to the reference value
  21010. const interpolant = referenceTrack.createInterpolant();
  21011. const startIndex = referenceOffset;
  21012. const endIndex = referenceValueSize - referenceOffset;
  21013. interpolant.evaluate(referenceTime);
  21014. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21015. } // Conjugate the quaternion
  21016. if (referenceTrackType === 'quaternion') {
  21017. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21018. referenceQuat.toArray(referenceValue);
  21019. } // Subtract the reference value from all of the track values
  21020. const numTimes = targetTrack.times.length;
  21021. for (let j = 0; j < numTimes; ++j) {
  21022. const valueStart = j * targetValueSize + targetOffset;
  21023. if (referenceTrackType === 'quaternion') {
  21024. // Multiply the conjugate for quaternion track types
  21025. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21026. } else {
  21027. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21028. for (let k = 0; k < valueEnd; ++k) {
  21029. targetTrack.values[valueStart + k] -= referenceValue[k];
  21030. }
  21031. }
  21032. }
  21033. }
  21034. targetClip.blendMode = AdditiveAnimationBlendMode;
  21035. return targetClip;
  21036. }
  21037. };
  21038. /**
  21039. * Abstract base class of interpolants over parametric samples.
  21040. *
  21041. * The parameter domain is one dimensional, typically the time or a path
  21042. * along a curve defined by the data.
  21043. *
  21044. * The sample values can have any dimensionality and derived classes may
  21045. * apply special interpretations to the data.
  21046. *
  21047. * This class provides the interval seek in a Template Method, deferring
  21048. * the actual interpolation to derived classes.
  21049. *
  21050. * Time complexity is O(1) for linear access crossing at most two points
  21051. * and O(log N) for random access, where N is the number of positions.
  21052. *
  21053. * References:
  21054. *
  21055. * http://www.oodesign.com/template-method-pattern.html
  21056. *
  21057. */
  21058. exports.AnimationUtils = AnimationUtils;
  21059. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21060. this.parameterPositions = parameterPositions;
  21061. this._cachedIndex = 0;
  21062. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21063. this.sampleValues = sampleValues;
  21064. this.valueSize = sampleSize;
  21065. }
  21066. Object.assign(Interpolant.prototype, {
  21067. evaluate: function (t) {
  21068. const pp = this.parameterPositions;
  21069. let i1 = this._cachedIndex,
  21070. t1 = pp[i1],
  21071. t0 = pp[i1 - 1];
  21072. validate_interval: {
  21073. seek: {
  21074. let right;
  21075. linear_scan: {
  21076. //- See http://jsperf.com/comparison-to-undefined/3
  21077. //- slower code:
  21078. //-
  21079. //- if ( t >= t1 || t1 === undefined ) {
  21080. forward_scan: if (!(t < t1)) {
  21081. for (let giveUpAt = i1 + 2;;) {
  21082. if (t1 === undefined) {
  21083. if (t < t0) break forward_scan; // after end
  21084. i1 = pp.length;
  21085. this._cachedIndex = i1;
  21086. return this.afterEnd_(i1 - 1, t, t0);
  21087. }
  21088. if (i1 === giveUpAt) break; // this loop
  21089. t0 = t1;
  21090. t1 = pp[++i1];
  21091. if (t < t1) {
  21092. // we have arrived at the sought interval
  21093. break seek;
  21094. }
  21095. } // prepare binary search on the right side of the index
  21096. right = pp.length;
  21097. break linear_scan;
  21098. } //- slower code:
  21099. //- if ( t < t0 || t0 === undefined ) {
  21100. if (!(t >= t0)) {
  21101. // looping?
  21102. const t1global = pp[1];
  21103. if (t < t1global) {
  21104. i1 = 2; // + 1, using the scan for the details
  21105. t0 = t1global;
  21106. } // linear reverse scan
  21107. for (let giveUpAt = i1 - 2;;) {
  21108. if (t0 === undefined) {
  21109. // before start
  21110. this._cachedIndex = 0;
  21111. return this.beforeStart_(0, t, t1);
  21112. }
  21113. if (i1 === giveUpAt) break; // this loop
  21114. t1 = t0;
  21115. t0 = pp[--i1 - 1];
  21116. if (t >= t0) {
  21117. // we have arrived at the sought interval
  21118. break seek;
  21119. }
  21120. } // prepare binary search on the left side of the index
  21121. right = i1;
  21122. i1 = 0;
  21123. break linear_scan;
  21124. } // the interval is valid
  21125. break validate_interval;
  21126. } // linear scan
  21127. // binary search
  21128. while (i1 < right) {
  21129. const mid = i1 + right >>> 1;
  21130. if (t < pp[mid]) {
  21131. right = mid;
  21132. } else {
  21133. i1 = mid + 1;
  21134. }
  21135. }
  21136. t1 = pp[i1];
  21137. t0 = pp[i1 - 1]; // check boundary cases, again
  21138. if (t0 === undefined) {
  21139. this._cachedIndex = 0;
  21140. return this.beforeStart_(0, t, t1);
  21141. }
  21142. if (t1 === undefined) {
  21143. i1 = pp.length;
  21144. this._cachedIndex = i1;
  21145. return this.afterEnd_(i1 - 1, t0, t);
  21146. }
  21147. } // seek
  21148. this._cachedIndex = i1;
  21149. this.intervalChanged_(i1, t0, t1);
  21150. } // validate_interval
  21151. return this.interpolate_(i1, t0, t, t1);
  21152. },
  21153. settings: null,
  21154. // optional, subclass-specific settings structure
  21155. // Note: The indirection allows central control of many interpolants.
  21156. // --- Protected interface
  21157. DefaultSettings_: {},
  21158. getSettings_: function () {
  21159. return this.settings || this.DefaultSettings_;
  21160. },
  21161. copySampleValue_: function (index) {
  21162. // copies a sample value to the result buffer
  21163. const result = this.resultBuffer,
  21164. values = this.sampleValues,
  21165. stride = this.valueSize,
  21166. offset = index * stride;
  21167. for (let i = 0; i !== stride; ++i) {
  21168. result[i] = values[offset + i];
  21169. }
  21170. return result;
  21171. },
  21172. // Template methods for derived classes:
  21173. interpolate_: function ()
  21174. /* i1, t0, t, t1 */
  21175. {
  21176. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21177. },
  21178. intervalChanged_: function ()
  21179. /* i1, t0, t1 */
  21180. {// empty
  21181. }
  21182. }); // DECLARE ALIAS AFTER assign prototype
  21183. Object.assign(Interpolant.prototype, {
  21184. //( 0, t, t0 ), returns this.resultBuffer
  21185. beforeStart_: Interpolant.prototype.copySampleValue_,
  21186. //( N-1, tN-1, t ), returns this.resultBuffer
  21187. afterEnd_: Interpolant.prototype.copySampleValue_
  21188. });
  21189. /**
  21190. * Fast and simple cubic spline interpolant.
  21191. *
  21192. * It was derived from a Hermitian construction setting the first derivative
  21193. * at each sample position to the linear slope between neighboring positions
  21194. * over their parameter interval.
  21195. */
  21196. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21197. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21198. this._weightPrev = -0;
  21199. this._offsetPrev = -0;
  21200. this._weightNext = -0;
  21201. this._offsetNext = -0;
  21202. }
  21203. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21204. constructor: CubicInterpolant,
  21205. DefaultSettings_: {
  21206. endingStart: ZeroCurvatureEnding,
  21207. endingEnd: ZeroCurvatureEnding
  21208. },
  21209. intervalChanged_: function (i1, t0, t1) {
  21210. const pp = this.parameterPositions;
  21211. let iPrev = i1 - 2,
  21212. iNext = i1 + 1,
  21213. tPrev = pp[iPrev],
  21214. tNext = pp[iNext];
  21215. if (tPrev === undefined) {
  21216. switch (this.getSettings_().endingStart) {
  21217. case ZeroSlopeEnding:
  21218. // f'(t0) = 0
  21219. iPrev = i1;
  21220. tPrev = 2 * t0 - t1;
  21221. break;
  21222. case WrapAroundEnding:
  21223. // use the other end of the curve
  21224. iPrev = pp.length - 2;
  21225. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21226. break;
  21227. default:
  21228. // ZeroCurvatureEnding
  21229. // f''(t0) = 0 a.k.a. Natural Spline
  21230. iPrev = i1;
  21231. tPrev = t1;
  21232. }
  21233. }
  21234. if (tNext === undefined) {
  21235. switch (this.getSettings_().endingEnd) {
  21236. case ZeroSlopeEnding:
  21237. // f'(tN) = 0
  21238. iNext = i1;
  21239. tNext = 2 * t1 - t0;
  21240. break;
  21241. case WrapAroundEnding:
  21242. // use the other end of the curve
  21243. iNext = 1;
  21244. tNext = t1 + pp[1] - pp[0];
  21245. break;
  21246. default:
  21247. // ZeroCurvatureEnding
  21248. // f''(tN) = 0, a.k.a. Natural Spline
  21249. iNext = i1 - 1;
  21250. tNext = t0;
  21251. }
  21252. }
  21253. const halfDt = (t1 - t0) * 0.5,
  21254. stride = this.valueSize;
  21255. this._weightPrev = halfDt / (t0 - tPrev);
  21256. this._weightNext = halfDt / (tNext - t1);
  21257. this._offsetPrev = iPrev * stride;
  21258. this._offsetNext = iNext * stride;
  21259. },
  21260. interpolate_: function (i1, t0, t, t1) {
  21261. const result = this.resultBuffer,
  21262. values = this.sampleValues,
  21263. stride = this.valueSize,
  21264. o1 = i1 * stride,
  21265. o0 = o1 - stride,
  21266. oP = this._offsetPrev,
  21267. oN = this._offsetNext,
  21268. wP = this._weightPrev,
  21269. wN = this._weightNext,
  21270. p = (t - t0) / (t1 - t0),
  21271. pp = p * p,
  21272. ppp = pp * p; // evaluate polynomials
  21273. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21274. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21275. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21276. const sN = wN * ppp - wN * pp; // combine data linearly
  21277. for (let i = 0; i !== stride; ++i) {
  21278. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21279. }
  21280. return result;
  21281. }
  21282. });
  21283. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21284. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21285. }
  21286. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21287. constructor: LinearInterpolant,
  21288. interpolate_: function (i1, t0, t, t1) {
  21289. const result = this.resultBuffer,
  21290. values = this.sampleValues,
  21291. stride = this.valueSize,
  21292. offset1 = i1 * stride,
  21293. offset0 = offset1 - stride,
  21294. weight1 = (t - t0) / (t1 - t0),
  21295. weight0 = 1 - weight1;
  21296. for (let i = 0; i !== stride; ++i) {
  21297. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21298. }
  21299. return result;
  21300. }
  21301. });
  21302. /**
  21303. *
  21304. * Interpolant that evaluates to the sample value at the position preceeding
  21305. * the parameter.
  21306. */
  21307. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21308. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21309. }
  21310. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21311. constructor: DiscreteInterpolant,
  21312. interpolate_: function (i1
  21313. /*, t0, t, t1 */
  21314. ) {
  21315. return this.copySampleValue_(i1 - 1);
  21316. }
  21317. });
  21318. function KeyframeTrack(name, times, values, interpolation) {
  21319. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21320. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21321. this.name = name;
  21322. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21323. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21324. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21325. } // Static methods
  21326. Object.assign(KeyframeTrack, {
  21327. // Serialization (in static context, because of constructor invocation
  21328. // and automatic invocation of .toJSON):
  21329. toJSON: function (track) {
  21330. const trackType = track.constructor;
  21331. let json; // derived classes can define a static toJSON method
  21332. if (trackType.toJSON !== undefined) {
  21333. json = trackType.toJSON(track);
  21334. } else {
  21335. // by default, we assume the data can be serialized as-is
  21336. json = {
  21337. 'name': track.name,
  21338. 'times': AnimationUtils.convertArray(track.times, Array),
  21339. 'values': AnimationUtils.convertArray(track.values, Array)
  21340. };
  21341. const interpolation = track.getInterpolation();
  21342. if (interpolation !== track.DefaultInterpolation) {
  21343. json.interpolation = interpolation;
  21344. }
  21345. }
  21346. json.type = track.ValueTypeName; // mandatory
  21347. return json;
  21348. }
  21349. });
  21350. Object.assign(KeyframeTrack.prototype, {
  21351. constructor: KeyframeTrack,
  21352. TimeBufferType: Float32Array,
  21353. ValueBufferType: Float32Array,
  21354. DefaultInterpolation: InterpolateLinear,
  21355. InterpolantFactoryMethodDiscrete: function (result) {
  21356. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21357. },
  21358. InterpolantFactoryMethodLinear: function (result) {
  21359. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21360. },
  21361. InterpolantFactoryMethodSmooth: function (result) {
  21362. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21363. },
  21364. setInterpolation: function (interpolation) {
  21365. let factoryMethod;
  21366. switch (interpolation) {
  21367. case InterpolateDiscrete:
  21368. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21369. break;
  21370. case InterpolateLinear:
  21371. factoryMethod = this.InterpolantFactoryMethodLinear;
  21372. break;
  21373. case InterpolateSmooth:
  21374. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21375. break;
  21376. }
  21377. if (factoryMethod === undefined) {
  21378. const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21379. if (this.createInterpolant === undefined) {
  21380. // fall back to default, unless the default itself is messed up
  21381. if (interpolation !== this.DefaultInterpolation) {
  21382. this.setInterpolation(this.DefaultInterpolation);
  21383. } else {
  21384. throw new Error(message); // fatal, in this case
  21385. }
  21386. }
  21387. console.warn('THREE.KeyframeTrack:', message);
  21388. return this;
  21389. }
  21390. this.createInterpolant = factoryMethod;
  21391. return this;
  21392. },
  21393. getInterpolation: function () {
  21394. switch (this.createInterpolant) {
  21395. case this.InterpolantFactoryMethodDiscrete:
  21396. return InterpolateDiscrete;
  21397. case this.InterpolantFactoryMethodLinear:
  21398. return InterpolateLinear;
  21399. case this.InterpolantFactoryMethodSmooth:
  21400. return InterpolateSmooth;
  21401. }
  21402. },
  21403. getValueSize: function () {
  21404. return this.values.length / this.times.length;
  21405. },
  21406. // move all keyframes either forwards or backwards in time
  21407. shift: function (timeOffset) {
  21408. if (timeOffset !== 0.0) {
  21409. const times = this.times;
  21410. for (let i = 0, n = times.length; i !== n; ++i) {
  21411. times[i] += timeOffset;
  21412. }
  21413. }
  21414. return this;
  21415. },
  21416. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21417. scale: function (timeScale) {
  21418. if (timeScale !== 1.0) {
  21419. const times = this.times;
  21420. for (let i = 0, n = times.length; i !== n; ++i) {
  21421. times[i] *= timeScale;
  21422. }
  21423. }
  21424. return this;
  21425. },
  21426. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21427. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21428. trim: function (startTime, endTime) {
  21429. const times = this.times,
  21430. nKeys = times.length;
  21431. let from = 0,
  21432. to = nKeys - 1;
  21433. while (from !== nKeys && times[from] < startTime) {
  21434. ++from;
  21435. }
  21436. while (to !== -1 && times[to] > endTime) {
  21437. --to;
  21438. }
  21439. ++to; // inclusive -> exclusive bound
  21440. if (from !== 0 || to !== nKeys) {
  21441. // empty tracks are forbidden, so keep at least one keyframe
  21442. if (from >= to) {
  21443. to = Math.max(to, 1);
  21444. from = to - 1;
  21445. }
  21446. const stride = this.getValueSize();
  21447. this.times = AnimationUtils.arraySlice(times, from, to);
  21448. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21449. }
  21450. return this;
  21451. },
  21452. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21453. validate: function () {
  21454. let valid = true;
  21455. const valueSize = this.getValueSize();
  21456. if (valueSize - Math.floor(valueSize) !== 0) {
  21457. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21458. valid = false;
  21459. }
  21460. const times = this.times,
  21461. values = this.values,
  21462. nKeys = times.length;
  21463. if (nKeys === 0) {
  21464. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21465. valid = false;
  21466. }
  21467. let prevTime = null;
  21468. for (let i = 0; i !== nKeys; i++) {
  21469. const currTime = times[i];
  21470. if (typeof currTime === 'number' && isNaN(currTime)) {
  21471. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21472. valid = false;
  21473. break;
  21474. }
  21475. if (prevTime !== null && prevTime > currTime) {
  21476. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21477. valid = false;
  21478. break;
  21479. }
  21480. prevTime = currTime;
  21481. }
  21482. if (values !== undefined) {
  21483. if (AnimationUtils.isTypedArray(values)) {
  21484. for (let i = 0, n = values.length; i !== n; ++i) {
  21485. const value = values[i];
  21486. if (isNaN(value)) {
  21487. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21488. valid = false;
  21489. break;
  21490. }
  21491. }
  21492. }
  21493. }
  21494. return valid;
  21495. },
  21496. // removes equivalent sequential keys as common in morph target sequences
  21497. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21498. optimize: function () {
  21499. // times or values may be shared with other tracks, so overwriting is unsafe
  21500. const times = AnimationUtils.arraySlice(this.times),
  21501. values = AnimationUtils.arraySlice(this.values),
  21502. stride = this.getValueSize(),
  21503. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21504. lastIndex = times.length - 1;
  21505. let writeIndex = 1;
  21506. for (let i = 1; i < lastIndex; ++i) {
  21507. let keep = false;
  21508. const time = times[i];
  21509. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21510. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21511. if (!smoothInterpolation) {
  21512. // remove unnecessary keyframes same as their neighbors
  21513. const offset = i * stride,
  21514. offsetP = offset - stride,
  21515. offsetN = offset + stride;
  21516. for (let j = 0; j !== stride; ++j) {
  21517. const value = values[offset + j];
  21518. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21519. keep = true;
  21520. break;
  21521. }
  21522. }
  21523. } else {
  21524. keep = true;
  21525. }
  21526. } // in-place compaction
  21527. if (keep) {
  21528. if (i !== writeIndex) {
  21529. times[writeIndex] = times[i];
  21530. const readOffset = i * stride,
  21531. writeOffset = writeIndex * stride;
  21532. for (let j = 0; j !== stride; ++j) {
  21533. values[writeOffset + j] = values[readOffset + j];
  21534. }
  21535. }
  21536. ++writeIndex;
  21537. }
  21538. } // flush last keyframe (compaction looks ahead)
  21539. if (lastIndex > 0) {
  21540. times[writeIndex] = times[lastIndex];
  21541. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21542. values[writeOffset + j] = values[readOffset + j];
  21543. }
  21544. ++writeIndex;
  21545. }
  21546. if (writeIndex !== times.length) {
  21547. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21548. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21549. } else {
  21550. this.times = times;
  21551. this.values = values;
  21552. }
  21553. return this;
  21554. },
  21555. clone: function () {
  21556. const times = AnimationUtils.arraySlice(this.times, 0);
  21557. const values = AnimationUtils.arraySlice(this.values, 0);
  21558. const TypedKeyframeTrack = this.constructor;
  21559. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21560. track.createInterpolant = this.createInterpolant;
  21561. return track;
  21562. }
  21563. });
  21564. /**
  21565. * A Track of Boolean keyframe values.
  21566. */
  21567. function BooleanKeyframeTrack(name, times, values) {
  21568. KeyframeTrack.call(this, name, times, values);
  21569. }
  21570. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21571. constructor: BooleanKeyframeTrack,
  21572. ValueTypeName: 'bool',
  21573. ValueBufferType: Array,
  21574. DefaultInterpolation: InterpolateDiscrete,
  21575. InterpolantFactoryMethodLinear: undefined,
  21576. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21577. // representation of a single value and a custom interpolant that
  21578. // computes "firstValue ^ isOdd( index )".
  21579. });
  21580. /**
  21581. * A Track of keyframe values that represent color.
  21582. */
  21583. function ColorKeyframeTrack(name, times, values, interpolation) {
  21584. KeyframeTrack.call(this, name, times, values, interpolation);
  21585. }
  21586. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21587. constructor: ColorKeyframeTrack,
  21588. ValueTypeName: 'color' // ValueBufferType is inherited
  21589. // DefaultInterpolation is inherited
  21590. // Note: Very basic implementation and nothing special yet.
  21591. // However, this is the place for color space parameterization.
  21592. });
  21593. /**
  21594. * A Track of numeric keyframe values.
  21595. */
  21596. function NumberKeyframeTrack(name, times, values, interpolation) {
  21597. KeyframeTrack.call(this, name, times, values, interpolation);
  21598. }
  21599. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21600. constructor: NumberKeyframeTrack,
  21601. ValueTypeName: 'number' // ValueBufferType is inherited
  21602. // DefaultInterpolation is inherited
  21603. });
  21604. /**
  21605. * Spherical linear unit quaternion interpolant.
  21606. */
  21607. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21608. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21609. }
  21610. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21611. constructor: QuaternionLinearInterpolant,
  21612. interpolate_: function (i1, t0, t, t1) {
  21613. const result = this.resultBuffer,
  21614. values = this.sampleValues,
  21615. stride = this.valueSize,
  21616. alpha = (t - t0) / (t1 - t0);
  21617. let offset = i1 * stride;
  21618. for (let end = offset + stride; offset !== end; offset += 4) {
  21619. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21620. }
  21621. return result;
  21622. }
  21623. });
  21624. /**
  21625. * A Track of quaternion keyframe values.
  21626. */
  21627. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21628. KeyframeTrack.call(this, name, times, values, interpolation);
  21629. }
  21630. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21631. constructor: QuaternionKeyframeTrack,
  21632. ValueTypeName: 'quaternion',
  21633. // ValueBufferType is inherited
  21634. DefaultInterpolation: InterpolateLinear,
  21635. InterpolantFactoryMethodLinear: function (result) {
  21636. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21637. },
  21638. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21639. });
  21640. /**
  21641. * A Track that interpolates Strings
  21642. */
  21643. function StringKeyframeTrack(name, times, values, interpolation) {
  21644. KeyframeTrack.call(this, name, times, values, interpolation);
  21645. }
  21646. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21647. constructor: StringKeyframeTrack,
  21648. ValueTypeName: 'string',
  21649. ValueBufferType: Array,
  21650. DefaultInterpolation: InterpolateDiscrete,
  21651. InterpolantFactoryMethodLinear: undefined,
  21652. InterpolantFactoryMethodSmooth: undefined
  21653. });
  21654. /**
  21655. * A Track of vectored keyframe values.
  21656. */
  21657. function VectorKeyframeTrack(name, times, values, interpolation) {
  21658. KeyframeTrack.call(this, name, times, values, interpolation);
  21659. }
  21660. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21661. constructor: VectorKeyframeTrack,
  21662. ValueTypeName: 'vector' // ValueBufferType is inherited
  21663. // DefaultInterpolation is inherited
  21664. });
  21665. function AnimationClip(name, duration, tracks, blendMode) {
  21666. this.name = name;
  21667. this.tracks = tracks;
  21668. this.duration = duration !== undefined ? duration : -1;
  21669. this.blendMode = blendMode !== undefined ? blendMode : NormalAnimationBlendMode;
  21670. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21671. if (this.duration < 0) {
  21672. this.resetDuration();
  21673. }
  21674. }
  21675. function getTrackTypeForValueTypeName(typeName) {
  21676. switch (typeName.toLowerCase()) {
  21677. case 'scalar':
  21678. case 'double':
  21679. case 'float':
  21680. case 'number':
  21681. case 'integer':
  21682. return NumberKeyframeTrack;
  21683. case 'vector':
  21684. case 'vector2':
  21685. case 'vector3':
  21686. case 'vector4':
  21687. return VectorKeyframeTrack;
  21688. case 'color':
  21689. return ColorKeyframeTrack;
  21690. case 'quaternion':
  21691. return QuaternionKeyframeTrack;
  21692. case 'bool':
  21693. case 'boolean':
  21694. return BooleanKeyframeTrack;
  21695. case 'string':
  21696. return StringKeyframeTrack;
  21697. }
  21698. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21699. }
  21700. function parseKeyframeTrack(json) {
  21701. if (json.type === undefined) {
  21702. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21703. }
  21704. const trackType = getTrackTypeForValueTypeName(json.type);
  21705. if (json.times === undefined) {
  21706. const times = [],
  21707. values = [];
  21708. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21709. json.times = times;
  21710. json.values = values;
  21711. } // derived classes can define a static parse method
  21712. if (trackType.parse !== undefined) {
  21713. return trackType.parse(json);
  21714. } else {
  21715. // by default, we assume a constructor compatible with the base
  21716. return new trackType(json.name, json.times, json.values, json.interpolation);
  21717. }
  21718. }
  21719. Object.assign(AnimationClip, {
  21720. parse: function (json) {
  21721. const tracks = [],
  21722. jsonTracks = json.tracks,
  21723. frameTime = 1.0 / (json.fps || 1.0);
  21724. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21725. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21726. }
  21727. const clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
  21728. clip.uuid = json.uuid;
  21729. return clip;
  21730. },
  21731. toJSON: function (clip) {
  21732. const tracks = [],
  21733. clipTracks = clip.tracks;
  21734. const json = {
  21735. 'name': clip.name,
  21736. 'duration': clip.duration,
  21737. 'tracks': tracks,
  21738. 'uuid': clip.uuid,
  21739. 'blendMode': clip.blendMode
  21740. };
  21741. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  21742. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21743. }
  21744. return json;
  21745. },
  21746. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  21747. const numMorphTargets = morphTargetSequence.length;
  21748. const tracks = [];
  21749. for (let i = 0; i < numMorphTargets; i++) {
  21750. let times = [];
  21751. let values = [];
  21752. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21753. values.push(0, 1, 0);
  21754. const order = AnimationUtils.getKeyframeOrder(times);
  21755. times = AnimationUtils.sortedArray(times, 1, order);
  21756. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21757. // last frame as well for perfect loop.
  21758. if (!noLoop && times[0] === 0) {
  21759. times.push(numMorphTargets);
  21760. values.push(values[0]);
  21761. }
  21762. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21763. }
  21764. return new AnimationClip(name, -1, tracks);
  21765. },
  21766. findByName: function (objectOrClipArray, name) {
  21767. let clipArray = objectOrClipArray;
  21768. if (!Array.isArray(objectOrClipArray)) {
  21769. const o = objectOrClipArray;
  21770. clipArray = o.geometry && o.geometry.animations || o.animations;
  21771. }
  21772. for (let i = 0; i < clipArray.length; i++) {
  21773. if (clipArray[i].name === name) {
  21774. return clipArray[i];
  21775. }
  21776. }
  21777. return null;
  21778. },
  21779. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  21780. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21781. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21782. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21783. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21784. for (let i = 0, il = morphTargets.length; i < il; i++) {
  21785. const morphTarget = morphTargets[i];
  21786. const parts = morphTarget.name.match(pattern);
  21787. if (parts && parts.length > 1) {
  21788. const name = parts[1];
  21789. let animationMorphTargets = animationToMorphTargets[name];
  21790. if (!animationMorphTargets) {
  21791. animationToMorphTargets[name] = animationMorphTargets = [];
  21792. }
  21793. animationMorphTargets.push(morphTarget);
  21794. }
  21795. }
  21796. const clips = [];
  21797. for (const name in animationToMorphTargets) {
  21798. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21799. }
  21800. return clips;
  21801. },
  21802. // parse the animation.hierarchy format
  21803. parseAnimation: function (animation, bones) {
  21804. if (!animation) {
  21805. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21806. return null;
  21807. }
  21808. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21809. // only return track if there are actually keys.
  21810. if (animationKeys.length !== 0) {
  21811. const times = [];
  21812. const values = [];
  21813. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21814. if (times.length !== 0) {
  21815. destTracks.push(new trackType(trackName, times, values));
  21816. }
  21817. }
  21818. };
  21819. const tracks = [];
  21820. const clipName = animation.name || 'default';
  21821. const fps = animation.fps || 30;
  21822. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  21823. let duration = animation.length || -1;
  21824. const hierarchyTracks = animation.hierarchy || [];
  21825. for (let h = 0; h < hierarchyTracks.length; h++) {
  21826. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21827. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21828. if (animationKeys[0].morphTargets) {
  21829. // figure out all morph targets used in this track
  21830. const morphTargetNames = {};
  21831. let k;
  21832. for (k = 0; k < animationKeys.length; k++) {
  21833. if (animationKeys[k].morphTargets) {
  21834. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21835. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21836. }
  21837. }
  21838. } // create a track for each morph target with all zero
  21839. // morphTargetInfluences except for the keys in which
  21840. // the morphTarget is named.
  21841. for (const morphTargetName in morphTargetNames) {
  21842. const times = [];
  21843. const values = [];
  21844. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21845. const animationKey = animationKeys[k];
  21846. times.push(animationKey.time);
  21847. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21848. }
  21849. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21850. }
  21851. duration = morphTargetNames.length * (fps || 1.0);
  21852. } else {
  21853. // ...assume skeletal animation
  21854. const boneName = '.bones[' + bones[h].name + ']';
  21855. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21856. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21857. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21858. }
  21859. }
  21860. if (tracks.length === 0) {
  21861. return null;
  21862. }
  21863. const clip = new AnimationClip(clipName, duration, tracks, blendMode);
  21864. return clip;
  21865. }
  21866. });
  21867. Object.assign(AnimationClip.prototype, {
  21868. resetDuration: function () {
  21869. const tracks = this.tracks;
  21870. let duration = 0;
  21871. for (let i = 0, n = tracks.length; i !== n; ++i) {
  21872. const track = this.tracks[i];
  21873. duration = Math.max(duration, track.times[track.times.length - 1]);
  21874. }
  21875. this.duration = duration;
  21876. return this;
  21877. },
  21878. trim: function () {
  21879. for (let i = 0; i < this.tracks.length; i++) {
  21880. this.tracks[i].trim(0, this.duration);
  21881. }
  21882. return this;
  21883. },
  21884. validate: function () {
  21885. let valid = true;
  21886. for (let i = 0; i < this.tracks.length; i++) {
  21887. valid = valid && this.tracks[i].validate();
  21888. }
  21889. return valid;
  21890. },
  21891. optimize: function () {
  21892. for (let i = 0; i < this.tracks.length; i++) {
  21893. this.tracks[i].optimize();
  21894. }
  21895. return this;
  21896. },
  21897. clone: function () {
  21898. const tracks = [];
  21899. for (let i = 0; i < this.tracks.length; i++) {
  21900. tracks.push(this.tracks[i].clone());
  21901. }
  21902. return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
  21903. },
  21904. toJSON: function () {
  21905. return AnimationClip.toJSON(this);
  21906. }
  21907. });
  21908. const Cache = {
  21909. enabled: false,
  21910. files: {},
  21911. add: function (key, file) {
  21912. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21913. this.files[key] = file;
  21914. },
  21915. get: function (key) {
  21916. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21917. return this.files[key];
  21918. },
  21919. remove: function (key) {
  21920. delete this.files[key];
  21921. },
  21922. clear: function () {
  21923. this.files = {};
  21924. }
  21925. };
  21926. exports.Cache = Cache;
  21927. function LoadingManager(onLoad, onProgress, onError) {
  21928. const scope = this;
  21929. let isLoading = false;
  21930. let itemsLoaded = 0;
  21931. let itemsTotal = 0;
  21932. let urlModifier = undefined;
  21933. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21934. // in the constructor
  21935. this.onStart = undefined;
  21936. this.onLoad = onLoad;
  21937. this.onProgress = onProgress;
  21938. this.onError = onError;
  21939. this.itemStart = function (url) {
  21940. itemsTotal++;
  21941. if (isLoading === false) {
  21942. if (scope.onStart !== undefined) {
  21943. scope.onStart(url, itemsLoaded, itemsTotal);
  21944. }
  21945. }
  21946. isLoading = true;
  21947. };
  21948. this.itemEnd = function (url) {
  21949. itemsLoaded++;
  21950. if (scope.onProgress !== undefined) {
  21951. scope.onProgress(url, itemsLoaded, itemsTotal);
  21952. }
  21953. if (itemsLoaded === itemsTotal) {
  21954. isLoading = false;
  21955. if (scope.onLoad !== undefined) {
  21956. scope.onLoad();
  21957. }
  21958. }
  21959. };
  21960. this.itemError = function (url) {
  21961. if (scope.onError !== undefined) {
  21962. scope.onError(url);
  21963. }
  21964. };
  21965. this.resolveURL = function (url) {
  21966. if (urlModifier) {
  21967. return urlModifier(url);
  21968. }
  21969. return url;
  21970. };
  21971. this.setURLModifier = function (transform) {
  21972. urlModifier = transform;
  21973. return this;
  21974. };
  21975. this.addHandler = function (regex, loader) {
  21976. handlers.push(regex, loader);
  21977. return this;
  21978. };
  21979. this.removeHandler = function (regex) {
  21980. const index = handlers.indexOf(regex);
  21981. if (index !== -1) {
  21982. handlers.splice(index, 2);
  21983. }
  21984. return this;
  21985. };
  21986. this.getHandler = function (file) {
  21987. for (let i = 0, l = handlers.length; i < l; i += 2) {
  21988. const regex = handlers[i];
  21989. const loader = handlers[i + 1];
  21990. if (regex.global) regex.lastIndex = 0; // see #17920
  21991. if (regex.test(file)) {
  21992. return loader;
  21993. }
  21994. }
  21995. return null;
  21996. };
  21997. }
  21998. const DefaultLoadingManager = new LoadingManager();
  21999. exports.DefaultLoadingManager = DefaultLoadingManager;
  22000. function Loader(manager) {
  22001. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22002. this.crossOrigin = 'anonymous';
  22003. this.withCredentials = false;
  22004. this.path = '';
  22005. this.resourcePath = '';
  22006. this.requestHeader = {};
  22007. }
  22008. Object.assign(Loader.prototype, {
  22009. load: function ()
  22010. /* url, onLoad, onProgress, onError */
  22011. {},
  22012. loadAsync: function (url, onProgress) {
  22013. const scope = this;
  22014. return new Promise(function (resolve, reject) {
  22015. scope.load(url, resolve, onProgress, reject);
  22016. });
  22017. },
  22018. parse: function ()
  22019. /* data */
  22020. {},
  22021. setCrossOrigin: function (crossOrigin) {
  22022. this.crossOrigin = crossOrigin;
  22023. return this;
  22024. },
  22025. setWithCredentials: function (value) {
  22026. this.withCredentials = value;
  22027. return this;
  22028. },
  22029. setPath: function (path) {
  22030. this.path = path;
  22031. return this;
  22032. },
  22033. setResourcePath: function (resourcePath) {
  22034. this.resourcePath = resourcePath;
  22035. return this;
  22036. },
  22037. setRequestHeader: function (requestHeader) {
  22038. this.requestHeader = requestHeader;
  22039. return this;
  22040. }
  22041. });
  22042. const loading = {};
  22043. function FileLoader(manager) {
  22044. Loader.call(this, manager);
  22045. }
  22046. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22047. constructor: FileLoader,
  22048. load: function (url, onLoad, onProgress, onError) {
  22049. if (url === undefined) url = '';
  22050. if (this.path !== undefined) url = this.path + url;
  22051. url = this.manager.resolveURL(url);
  22052. const scope = this;
  22053. const cached = Cache.get(url);
  22054. if (cached !== undefined) {
  22055. scope.manager.itemStart(url);
  22056. setTimeout(function () {
  22057. if (onLoad) onLoad(cached);
  22058. scope.manager.itemEnd(url);
  22059. }, 0);
  22060. return cached;
  22061. } // Check if request is duplicate
  22062. if (loading[url] !== undefined) {
  22063. loading[url].push({
  22064. onLoad: onLoad,
  22065. onProgress: onProgress,
  22066. onError: onError
  22067. });
  22068. return;
  22069. } // Check for data: URI
  22070. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22071. const dataUriRegexResult = url.match(dataUriRegex);
  22072. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22073. if (dataUriRegexResult) {
  22074. const mimeType = dataUriRegexResult[1];
  22075. const isBase64 = !!dataUriRegexResult[2];
  22076. let data = dataUriRegexResult[3];
  22077. data = decodeURIComponent(data);
  22078. if (isBase64) data = atob(data);
  22079. try {
  22080. let response;
  22081. const responseType = (this.responseType || '').toLowerCase();
  22082. switch (responseType) {
  22083. case 'arraybuffer':
  22084. case 'blob':
  22085. const view = new Uint8Array(data.length);
  22086. for (let i = 0; i < data.length; i++) {
  22087. view[i] = data.charCodeAt(i);
  22088. }
  22089. if (responseType === 'blob') {
  22090. response = new Blob([view.buffer], {
  22091. type: mimeType
  22092. });
  22093. } else {
  22094. response = view.buffer;
  22095. }
  22096. break;
  22097. case 'document':
  22098. const parser = new DOMParser();
  22099. response = parser.parseFromString(data, mimeType);
  22100. break;
  22101. case 'json':
  22102. response = JSON.parse(data);
  22103. break;
  22104. default:
  22105. // 'text' or other
  22106. response = data;
  22107. break;
  22108. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22109. setTimeout(function () {
  22110. if (onLoad) onLoad(response);
  22111. scope.manager.itemEnd(url);
  22112. }, 0);
  22113. } catch (error) {
  22114. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22115. setTimeout(function () {
  22116. if (onError) onError(error);
  22117. scope.manager.itemError(url);
  22118. scope.manager.itemEnd(url);
  22119. }, 0);
  22120. }
  22121. } else {
  22122. // Initialise array for duplicate requests
  22123. loading[url] = [];
  22124. loading[url].push({
  22125. onLoad: onLoad,
  22126. onProgress: onProgress,
  22127. onError: onError
  22128. });
  22129. request = new XMLHttpRequest();
  22130. request.open('GET', url, true);
  22131. request.addEventListener('load', function (event) {
  22132. const response = this.response;
  22133. const callbacks = loading[url];
  22134. delete loading[url];
  22135. if (this.status === 200 || this.status === 0) {
  22136. // Some browsers return HTTP Status 0 when using non-http protocol
  22137. // e.g. 'file://' or 'data://'. Handle as success.
  22138. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  22139. // error response bodies as proper responses to requests.
  22140. Cache.add(url, response);
  22141. for (let i = 0, il = callbacks.length; i < il; i++) {
  22142. const callback = callbacks[i];
  22143. if (callback.onLoad) callback.onLoad(response);
  22144. }
  22145. scope.manager.itemEnd(url);
  22146. } else {
  22147. for (let i = 0, il = callbacks.length; i < il; i++) {
  22148. const callback = callbacks[i];
  22149. if (callback.onError) callback.onError(event);
  22150. }
  22151. scope.manager.itemError(url);
  22152. scope.manager.itemEnd(url);
  22153. }
  22154. }, false);
  22155. request.addEventListener('progress', function (event) {
  22156. const callbacks = loading[url];
  22157. for (let i = 0, il = callbacks.length; i < il; i++) {
  22158. const callback = callbacks[i];
  22159. if (callback.onProgress) callback.onProgress(event);
  22160. }
  22161. }, false);
  22162. request.addEventListener('error', function (event) {
  22163. const callbacks = loading[url];
  22164. delete loading[url];
  22165. for (let i = 0, il = callbacks.length; i < il; i++) {
  22166. const callback = callbacks[i];
  22167. if (callback.onError) callback.onError(event);
  22168. }
  22169. scope.manager.itemError(url);
  22170. scope.manager.itemEnd(url);
  22171. }, false);
  22172. request.addEventListener('abort', function (event) {
  22173. const callbacks = loading[url];
  22174. delete loading[url];
  22175. for (let i = 0, il = callbacks.length; i < il; i++) {
  22176. const callback = callbacks[i];
  22177. if (callback.onError) callback.onError(event);
  22178. }
  22179. scope.manager.itemError(url);
  22180. scope.manager.itemEnd(url);
  22181. }, false);
  22182. if (this.responseType !== undefined) request.responseType = this.responseType;
  22183. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22184. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22185. for (const header in this.requestHeader) {
  22186. request.setRequestHeader(header, this.requestHeader[header]);
  22187. }
  22188. request.send(null);
  22189. }
  22190. scope.manager.itemStart(url);
  22191. return request;
  22192. },
  22193. setResponseType: function (value) {
  22194. this.responseType = value;
  22195. return this;
  22196. },
  22197. setMimeType: function (value) {
  22198. this.mimeType = value;
  22199. return this;
  22200. }
  22201. });
  22202. function AnimationLoader(manager) {
  22203. Loader.call(this, manager);
  22204. }
  22205. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22206. constructor: AnimationLoader,
  22207. load: function (url, onLoad, onProgress, onError) {
  22208. const scope = this;
  22209. const loader = new FileLoader(scope.manager);
  22210. loader.setPath(scope.path);
  22211. loader.setRequestHeader(scope.requestHeader);
  22212. loader.setWithCredentials(scope.withCredentials);
  22213. loader.load(url, function (text) {
  22214. try {
  22215. onLoad(scope.parse(JSON.parse(text)));
  22216. } catch (e) {
  22217. if (onError) {
  22218. onError(e);
  22219. } else {
  22220. console.error(e);
  22221. }
  22222. scope.manager.itemError(url);
  22223. }
  22224. }, onProgress, onError);
  22225. },
  22226. parse: function (json) {
  22227. const animations = [];
  22228. for (let i = 0; i < json.length; i++) {
  22229. const clip = AnimationClip.parse(json[i]);
  22230. animations.push(clip);
  22231. }
  22232. return animations;
  22233. }
  22234. });
  22235. /**
  22236. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22237. *
  22238. * Sub classes have to implement the parse() method which will be used in load().
  22239. */
  22240. function CompressedTextureLoader(manager) {
  22241. Loader.call(this, manager);
  22242. }
  22243. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22244. constructor: CompressedTextureLoader,
  22245. load: function (url, onLoad, onProgress, onError) {
  22246. const scope = this;
  22247. const images = [];
  22248. const texture = new CompressedTexture();
  22249. texture.image = images;
  22250. const loader = new FileLoader(this.manager);
  22251. loader.setPath(this.path);
  22252. loader.setResponseType('arraybuffer');
  22253. loader.setRequestHeader(this.requestHeader);
  22254. loader.setWithCredentials(scope.withCredentials);
  22255. let loaded = 0;
  22256. function loadTexture(i) {
  22257. loader.load(url[i], function (buffer) {
  22258. const texDatas = scope.parse(buffer, true);
  22259. images[i] = {
  22260. width: texDatas.width,
  22261. height: texDatas.height,
  22262. format: texDatas.format,
  22263. mipmaps: texDatas.mipmaps
  22264. };
  22265. loaded += 1;
  22266. if (loaded === 6) {
  22267. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22268. texture.format = texDatas.format;
  22269. texture.needsUpdate = true;
  22270. if (onLoad) onLoad(texture);
  22271. }
  22272. }, onProgress, onError);
  22273. }
  22274. if (Array.isArray(url)) {
  22275. for (let i = 0, il = url.length; i < il; ++i) {
  22276. loadTexture(i);
  22277. }
  22278. } else {
  22279. // compressed cubemap texture stored in a single DDS file
  22280. loader.load(url, function (buffer) {
  22281. const texDatas = scope.parse(buffer, true);
  22282. if (texDatas.isCubemap) {
  22283. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22284. for (let f = 0; f < faces; f++) {
  22285. images[f] = {
  22286. mipmaps: []
  22287. };
  22288. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22289. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22290. images[f].format = texDatas.format;
  22291. images[f].width = texDatas.width;
  22292. images[f].height = texDatas.height;
  22293. }
  22294. }
  22295. } else {
  22296. texture.image.width = texDatas.width;
  22297. texture.image.height = texDatas.height;
  22298. texture.mipmaps = texDatas.mipmaps;
  22299. }
  22300. if (texDatas.mipmapCount === 1) {
  22301. texture.minFilter = LinearFilter;
  22302. }
  22303. texture.format = texDatas.format;
  22304. texture.needsUpdate = true;
  22305. if (onLoad) onLoad(texture);
  22306. }, onProgress, onError);
  22307. }
  22308. return texture;
  22309. }
  22310. });
  22311. function ImageLoader(manager) {
  22312. Loader.call(this, manager);
  22313. }
  22314. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22315. constructor: ImageLoader,
  22316. load: function (url, onLoad, onProgress, onError) {
  22317. if (this.path !== undefined) url = this.path + url;
  22318. url = this.manager.resolveURL(url);
  22319. const scope = this;
  22320. const cached = Cache.get(url);
  22321. if (cached !== undefined) {
  22322. scope.manager.itemStart(url);
  22323. setTimeout(function () {
  22324. if (onLoad) onLoad(cached);
  22325. scope.manager.itemEnd(url);
  22326. }, 0);
  22327. return cached;
  22328. }
  22329. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22330. function onImageLoad() {
  22331. image.removeEventListener('load', onImageLoad, false);
  22332. image.removeEventListener('error', onImageError, false);
  22333. Cache.add(url, this);
  22334. if (onLoad) onLoad(this);
  22335. scope.manager.itemEnd(url);
  22336. }
  22337. function onImageError(event) {
  22338. image.removeEventListener('load', onImageLoad, false);
  22339. image.removeEventListener('error', onImageError, false);
  22340. if (onError) onError(event);
  22341. scope.manager.itemError(url);
  22342. scope.manager.itemEnd(url);
  22343. }
  22344. image.addEventListener('load', onImageLoad, false);
  22345. image.addEventListener('error', onImageError, false);
  22346. if (url.substr(0, 5) !== 'data:') {
  22347. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22348. }
  22349. scope.manager.itemStart(url);
  22350. image.src = url;
  22351. return image;
  22352. }
  22353. });
  22354. function CubeTextureLoader(manager) {
  22355. Loader.call(this, manager);
  22356. }
  22357. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22358. constructor: CubeTextureLoader,
  22359. load: function (urls, onLoad, onProgress, onError) {
  22360. const texture = new CubeTexture();
  22361. const loader = new ImageLoader(this.manager);
  22362. loader.setCrossOrigin(this.crossOrigin);
  22363. loader.setPath(this.path);
  22364. let loaded = 0;
  22365. function loadTexture(i) {
  22366. loader.load(urls[i], function (image) {
  22367. texture.images[i] = image;
  22368. loaded++;
  22369. if (loaded === 6) {
  22370. texture.needsUpdate = true;
  22371. if (onLoad) onLoad(texture);
  22372. }
  22373. }, undefined, onError);
  22374. }
  22375. for (let i = 0; i < urls.length; ++i) {
  22376. loadTexture(i);
  22377. }
  22378. return texture;
  22379. }
  22380. });
  22381. /**
  22382. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22383. *
  22384. * Sub classes have to implement the parse() method which will be used in load().
  22385. */
  22386. function DataTextureLoader(manager) {
  22387. Loader.call(this, manager);
  22388. }
  22389. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22390. constructor: DataTextureLoader,
  22391. load: function (url, onLoad, onProgress, onError) {
  22392. const scope = this;
  22393. const texture = new DataTexture();
  22394. const loader = new FileLoader(this.manager);
  22395. loader.setResponseType('arraybuffer');
  22396. loader.setRequestHeader(this.requestHeader);
  22397. loader.setPath(this.path);
  22398. loader.setWithCredentials(scope.withCredentials);
  22399. loader.load(url, function (buffer) {
  22400. const texData = scope.parse(buffer);
  22401. if (!texData) return;
  22402. if (texData.image !== undefined) {
  22403. texture.image = texData.image;
  22404. } else if (texData.data !== undefined) {
  22405. texture.image.width = texData.width;
  22406. texture.image.height = texData.height;
  22407. texture.image.data = texData.data;
  22408. }
  22409. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22410. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22411. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22412. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22413. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22414. if (texData.format !== undefined) {
  22415. texture.format = texData.format;
  22416. }
  22417. if (texData.type !== undefined) {
  22418. texture.type = texData.type;
  22419. }
  22420. if (texData.mipmaps !== undefined) {
  22421. texture.mipmaps = texData.mipmaps;
  22422. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22423. }
  22424. if (texData.mipmapCount === 1) {
  22425. texture.minFilter = LinearFilter;
  22426. }
  22427. texture.needsUpdate = true;
  22428. if (onLoad) onLoad(texture, texData);
  22429. }, onProgress, onError);
  22430. return texture;
  22431. }
  22432. });
  22433. function TextureLoader(manager) {
  22434. Loader.call(this, manager);
  22435. }
  22436. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22437. constructor: TextureLoader,
  22438. load: function (url, onLoad, onProgress, onError) {
  22439. const texture = new Texture();
  22440. const loader = new ImageLoader(this.manager);
  22441. loader.setCrossOrigin(this.crossOrigin);
  22442. loader.setPath(this.path);
  22443. loader.load(url, function (image) {
  22444. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22445. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22446. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22447. texture.needsUpdate = true;
  22448. if (onLoad !== undefined) {
  22449. onLoad(texture);
  22450. }
  22451. }, onProgress, onError);
  22452. return texture;
  22453. }
  22454. });
  22455. /**
  22456. * Extensible curve object.
  22457. *
  22458. * Some common of curve methods:
  22459. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22460. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22461. * .getPoints(), .getSpacedPoints()
  22462. * .getLength()
  22463. * .updateArcLengths()
  22464. *
  22465. * This following curves inherit from THREE.Curve:
  22466. *
  22467. * -- 2D curves --
  22468. * THREE.ArcCurve
  22469. * THREE.CubicBezierCurve
  22470. * THREE.EllipseCurve
  22471. * THREE.LineCurve
  22472. * THREE.QuadraticBezierCurve
  22473. * THREE.SplineCurve
  22474. *
  22475. * -- 3D curves --
  22476. * THREE.CatmullRomCurve3
  22477. * THREE.CubicBezierCurve3
  22478. * THREE.LineCurve3
  22479. * THREE.QuadraticBezierCurve3
  22480. *
  22481. * A series of curves can be represented as a THREE.CurvePath.
  22482. *
  22483. **/
  22484. function Curve() {
  22485. this.type = 'Curve';
  22486. this.arcLengthDivisions = 200;
  22487. }
  22488. Object.assign(Curve.prototype, {
  22489. // Virtual base class method to overwrite and implement in subclasses
  22490. // - t [0 .. 1]
  22491. getPoint: function ()
  22492. /* t, optionalTarget */
  22493. {
  22494. console.warn('THREE.Curve: .getPoint() not implemented.');
  22495. return null;
  22496. },
  22497. // Get point at relative position in curve according to arc length
  22498. // - u [0 .. 1]
  22499. getPointAt: function (u, optionalTarget) {
  22500. const t = this.getUtoTmapping(u);
  22501. return this.getPoint(t, optionalTarget);
  22502. },
  22503. // Get sequence of points using getPoint( t )
  22504. getPoints: function (divisions = 5) {
  22505. const points = [];
  22506. for (let d = 0; d <= divisions; d++) {
  22507. points.push(this.getPoint(d / divisions));
  22508. }
  22509. return points;
  22510. },
  22511. // Get sequence of points using getPointAt( u )
  22512. getSpacedPoints: function (divisions = 5) {
  22513. const points = [];
  22514. for (let d = 0; d <= divisions; d++) {
  22515. points.push(this.getPointAt(d / divisions));
  22516. }
  22517. return points;
  22518. },
  22519. // Get total curve arc length
  22520. getLength: function () {
  22521. const lengths = this.getLengths();
  22522. return lengths[lengths.length - 1];
  22523. },
  22524. // Get list of cumulative segment lengths
  22525. getLengths: function (divisions) {
  22526. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22527. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22528. return this.cacheArcLengths;
  22529. }
  22530. this.needsUpdate = false;
  22531. const cache = [];
  22532. let current,
  22533. last = this.getPoint(0);
  22534. let sum = 0;
  22535. cache.push(0);
  22536. for (let p = 1; p <= divisions; p++) {
  22537. current = this.getPoint(p / divisions);
  22538. sum += current.distanceTo(last);
  22539. cache.push(sum);
  22540. last = current;
  22541. }
  22542. this.cacheArcLengths = cache;
  22543. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22544. },
  22545. updateArcLengths: function () {
  22546. this.needsUpdate = true;
  22547. this.getLengths();
  22548. },
  22549. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22550. getUtoTmapping: function (u, distance) {
  22551. const arcLengths = this.getLengths();
  22552. let i = 0;
  22553. const il = arcLengths.length;
  22554. let targetArcLength; // The targeted u distance value to get
  22555. if (distance) {
  22556. targetArcLength = distance;
  22557. } else {
  22558. targetArcLength = u * arcLengths[il - 1];
  22559. } // binary search for the index with largest value smaller than target u distance
  22560. let low = 0,
  22561. high = il - 1,
  22562. comparison;
  22563. while (low <= high) {
  22564. 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
  22565. comparison = arcLengths[i] - targetArcLength;
  22566. if (comparison < 0) {
  22567. low = i + 1;
  22568. } else if (comparison > 0) {
  22569. high = i - 1;
  22570. } else {
  22571. high = i;
  22572. break; // DONE
  22573. }
  22574. }
  22575. i = high;
  22576. if (arcLengths[i] === targetArcLength) {
  22577. return i / (il - 1);
  22578. } // we could get finer grain at lengths, or use simple interpolation between two points
  22579. const lengthBefore = arcLengths[i];
  22580. const lengthAfter = arcLengths[i + 1];
  22581. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22582. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22583. const t = (i + segmentFraction) / (il - 1);
  22584. return t;
  22585. },
  22586. // Returns a unit vector tangent at t
  22587. // In case any sub curve does not implement its tangent derivation,
  22588. // 2 points a small delta apart will be used to find its gradient
  22589. // which seems to give a reasonable approximation
  22590. getTangent: function (t, optionalTarget) {
  22591. const delta = 0.0001;
  22592. let t1 = t - delta;
  22593. let t2 = t + delta; // Capping in case of danger
  22594. if (t1 < 0) t1 = 0;
  22595. if (t2 > 1) t2 = 1;
  22596. const pt1 = this.getPoint(t1);
  22597. const pt2 = this.getPoint(t2);
  22598. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  22599. tangent.copy(pt2).sub(pt1).normalize();
  22600. return tangent;
  22601. },
  22602. getTangentAt: function (u, optionalTarget) {
  22603. const t = this.getUtoTmapping(u);
  22604. return this.getTangent(t, optionalTarget);
  22605. },
  22606. computeFrenetFrames: function (segments, closed) {
  22607. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22608. const normal = new Vector3();
  22609. const tangents = [];
  22610. const normals = [];
  22611. const binormals = [];
  22612. const vec = new Vector3();
  22613. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  22614. for (let i = 0; i <= segments; i++) {
  22615. const u = i / segments;
  22616. tangents[i] = this.getTangentAt(u, new Vector3());
  22617. tangents[i].normalize();
  22618. } // select an initial normal vector perpendicular to the first tangent vector,
  22619. // and in the direction of the minimum tangent xyz component
  22620. normals[0] = new Vector3();
  22621. binormals[0] = new Vector3();
  22622. let min = Number.MAX_VALUE;
  22623. const tx = Math.abs(tangents[0].x);
  22624. const ty = Math.abs(tangents[0].y);
  22625. const tz = Math.abs(tangents[0].z);
  22626. if (tx <= min) {
  22627. min = tx;
  22628. normal.set(1, 0, 0);
  22629. }
  22630. if (ty <= min) {
  22631. min = ty;
  22632. normal.set(0, 1, 0);
  22633. }
  22634. if (tz <= min) {
  22635. normal.set(0, 0, 1);
  22636. }
  22637. vec.crossVectors(tangents[0], normal).normalize();
  22638. normals[0].crossVectors(tangents[0], vec);
  22639. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22640. for (let i = 1; i <= segments; i++) {
  22641. normals[i] = normals[i - 1].clone();
  22642. binormals[i] = binormals[i - 1].clone();
  22643. vec.crossVectors(tangents[i - 1], tangents[i]);
  22644. if (vec.length() > Number.EPSILON) {
  22645. vec.normalize();
  22646. const theta = Math.acos(MathUtils.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22647. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22648. }
  22649. binormals[i].crossVectors(tangents[i], normals[i]);
  22650. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22651. if (closed === true) {
  22652. let theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  22653. theta /= segments;
  22654. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22655. theta = -theta;
  22656. }
  22657. for (let i = 1; i <= segments; i++) {
  22658. // twist a little...
  22659. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22660. binormals[i].crossVectors(tangents[i], normals[i]);
  22661. }
  22662. }
  22663. return {
  22664. tangents: tangents,
  22665. normals: normals,
  22666. binormals: binormals
  22667. };
  22668. },
  22669. clone: function () {
  22670. return new this.constructor().copy(this);
  22671. },
  22672. copy: function (source) {
  22673. this.arcLengthDivisions = source.arcLengthDivisions;
  22674. return this;
  22675. },
  22676. toJSON: function () {
  22677. const data = {
  22678. metadata: {
  22679. version: 4.5,
  22680. type: 'Curve',
  22681. generator: 'Curve.toJSON'
  22682. }
  22683. };
  22684. data.arcLengthDivisions = this.arcLengthDivisions;
  22685. data.type = this.type;
  22686. return data;
  22687. },
  22688. fromJSON: function (json) {
  22689. this.arcLengthDivisions = json.arcLengthDivisions;
  22690. return this;
  22691. }
  22692. });
  22693. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22694. Curve.call(this);
  22695. this.type = 'EllipseCurve';
  22696. this.aX = aX || 0;
  22697. this.aY = aY || 0;
  22698. this.xRadius = xRadius || 1;
  22699. this.yRadius = yRadius || 1;
  22700. this.aStartAngle = aStartAngle || 0;
  22701. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22702. this.aClockwise = aClockwise || false;
  22703. this.aRotation = aRotation || 0;
  22704. }
  22705. EllipseCurve.prototype = Object.create(Curve.prototype);
  22706. EllipseCurve.prototype.constructor = EllipseCurve;
  22707. EllipseCurve.prototype.isEllipseCurve = true;
  22708. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  22709. const point = optionalTarget || new Vector2();
  22710. const twoPi = Math.PI * 2;
  22711. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22712. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  22713. while (deltaAngle < 0) deltaAngle += twoPi;
  22714. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  22715. if (deltaAngle < Number.EPSILON) {
  22716. if (samePoints) {
  22717. deltaAngle = 0;
  22718. } else {
  22719. deltaAngle = twoPi;
  22720. }
  22721. }
  22722. if (this.aClockwise === true && !samePoints) {
  22723. if (deltaAngle === twoPi) {
  22724. deltaAngle = -twoPi;
  22725. } else {
  22726. deltaAngle = deltaAngle - twoPi;
  22727. }
  22728. }
  22729. const angle = this.aStartAngle + t * deltaAngle;
  22730. let x = this.aX + this.xRadius * Math.cos(angle);
  22731. let y = this.aY + this.yRadius * Math.sin(angle);
  22732. if (this.aRotation !== 0) {
  22733. const cos = Math.cos(this.aRotation);
  22734. const sin = Math.sin(this.aRotation);
  22735. const tx = x - this.aX;
  22736. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  22737. x = tx * cos - ty * sin + this.aX;
  22738. y = tx * sin + ty * cos + this.aY;
  22739. }
  22740. return point.set(x, y);
  22741. };
  22742. EllipseCurve.prototype.copy = function (source) {
  22743. Curve.prototype.copy.call(this, source);
  22744. this.aX = source.aX;
  22745. this.aY = source.aY;
  22746. this.xRadius = source.xRadius;
  22747. this.yRadius = source.yRadius;
  22748. this.aStartAngle = source.aStartAngle;
  22749. this.aEndAngle = source.aEndAngle;
  22750. this.aClockwise = source.aClockwise;
  22751. this.aRotation = source.aRotation;
  22752. return this;
  22753. };
  22754. EllipseCurve.prototype.toJSON = function () {
  22755. const data = Curve.prototype.toJSON.call(this);
  22756. data.aX = this.aX;
  22757. data.aY = this.aY;
  22758. data.xRadius = this.xRadius;
  22759. data.yRadius = this.yRadius;
  22760. data.aStartAngle = this.aStartAngle;
  22761. data.aEndAngle = this.aEndAngle;
  22762. data.aClockwise = this.aClockwise;
  22763. data.aRotation = this.aRotation;
  22764. return data;
  22765. };
  22766. EllipseCurve.prototype.fromJSON = function (json) {
  22767. Curve.prototype.fromJSON.call(this, json);
  22768. this.aX = json.aX;
  22769. this.aY = json.aY;
  22770. this.xRadius = json.xRadius;
  22771. this.yRadius = json.yRadius;
  22772. this.aStartAngle = json.aStartAngle;
  22773. this.aEndAngle = json.aEndAngle;
  22774. this.aClockwise = json.aClockwise;
  22775. this.aRotation = json.aRotation;
  22776. return this;
  22777. };
  22778. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22779. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22780. this.type = 'ArcCurve';
  22781. }
  22782. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  22783. ArcCurve.prototype.constructor = ArcCurve;
  22784. ArcCurve.prototype.isArcCurve = true;
  22785. /**
  22786. * Centripetal CatmullRom Curve - which is useful for avoiding
  22787. * cusps and self-intersections in non-uniform catmull rom curves.
  22788. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22789. *
  22790. * curve.type accepts centripetal(default), chordal and catmullrom
  22791. * curve.tension is used for catmullrom which defaults to 0.5
  22792. */
  22793. /*
  22794. Based on an optimized c++ solution in
  22795. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22796. - http://ideone.com/NoEbVM
  22797. This CubicPoly class could be used for reusing some variables and calculations,
  22798. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22799. which can be placed in CurveUtils.
  22800. */
  22801. function CubicPoly() {
  22802. let c0 = 0,
  22803. c1 = 0,
  22804. c2 = 0,
  22805. c3 = 0;
  22806. /*
  22807. * Compute coefficients for a cubic polynomial
  22808. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22809. * such that
  22810. * p(0) = x0, p(1) = x1
  22811. * and
  22812. * p'(0) = t0, p'(1) = t1.
  22813. */
  22814. function init(x0, x1, t0, t1) {
  22815. c0 = x0;
  22816. c1 = t0;
  22817. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22818. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22819. }
  22820. return {
  22821. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22822. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22823. },
  22824. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22825. // compute tangents when parameterized in [t1,t2]
  22826. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22827. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22828. t1 *= dt1;
  22829. t2 *= dt1;
  22830. init(x1, x2, t1, t2);
  22831. },
  22832. calc: function (t) {
  22833. const t2 = t * t;
  22834. const t3 = t2 * t;
  22835. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22836. }
  22837. };
  22838. } //
  22839. const tmp = new Vector3();
  22840. const px = new CubicPoly(),
  22841. py = new CubicPoly(),
  22842. pz = new CubicPoly();
  22843. function CatmullRomCurve3(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  22844. Curve.call(this);
  22845. this.type = 'CatmullRomCurve3';
  22846. this.points = points;
  22847. this.closed = closed;
  22848. this.curveType = curveType;
  22849. this.tension = tension;
  22850. }
  22851. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22852. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22853. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22854. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  22855. const point = optionalTarget;
  22856. const points = this.points;
  22857. const l = points.length;
  22858. const p = (l - (this.closed ? 0 : 1)) * t;
  22859. let intPoint = Math.floor(p);
  22860. let weight = p - intPoint;
  22861. if (this.closed) {
  22862. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22863. } else if (weight === 0 && intPoint === l - 1) {
  22864. intPoint = l - 2;
  22865. weight = 1;
  22866. }
  22867. let p0, p3; // 4 points (p1 & p2 defined below)
  22868. if (this.closed || intPoint > 0) {
  22869. p0 = points[(intPoint - 1) % l];
  22870. } else {
  22871. // extrapolate first point
  22872. tmp.subVectors(points[0], points[1]).add(points[0]);
  22873. p0 = tmp;
  22874. }
  22875. const p1 = points[intPoint % l];
  22876. const p2 = points[(intPoint + 1) % l];
  22877. if (this.closed || intPoint + 2 < l) {
  22878. p3 = points[(intPoint + 2) % l];
  22879. } else {
  22880. // extrapolate last point
  22881. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22882. p3 = tmp;
  22883. }
  22884. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22885. // init Centripetal / Chordal Catmull-Rom
  22886. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22887. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22888. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22889. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22890. if (dt1 < 1e-4) dt1 = 1.0;
  22891. if (dt0 < 1e-4) dt0 = dt1;
  22892. if (dt2 < 1e-4) dt2 = dt1;
  22893. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22894. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22895. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22896. } else if (this.curveType === 'catmullrom') {
  22897. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22898. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22899. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22900. }
  22901. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22902. return point;
  22903. };
  22904. CatmullRomCurve3.prototype.copy = function (source) {
  22905. Curve.prototype.copy.call(this, source);
  22906. this.points = [];
  22907. for (let i = 0, l = source.points.length; i < l; i++) {
  22908. const point = source.points[i];
  22909. this.points.push(point.clone());
  22910. }
  22911. this.closed = source.closed;
  22912. this.curveType = source.curveType;
  22913. this.tension = source.tension;
  22914. return this;
  22915. };
  22916. CatmullRomCurve3.prototype.toJSON = function () {
  22917. const data = Curve.prototype.toJSON.call(this);
  22918. data.points = [];
  22919. for (let i = 0, l = this.points.length; i < l; i++) {
  22920. const point = this.points[i];
  22921. data.points.push(point.toArray());
  22922. }
  22923. data.closed = this.closed;
  22924. data.curveType = this.curveType;
  22925. data.tension = this.tension;
  22926. return data;
  22927. };
  22928. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22929. Curve.prototype.fromJSON.call(this, json);
  22930. this.points = [];
  22931. for (let i = 0, l = json.points.length; i < l; i++) {
  22932. const point = json.points[i];
  22933. this.points.push(new Vector3().fromArray(point));
  22934. }
  22935. this.closed = json.closed;
  22936. this.curveType = json.curveType;
  22937. this.tension = json.tension;
  22938. return this;
  22939. };
  22940. /**
  22941. * Bezier Curves formulas obtained from
  22942. * http://en.wikipedia.org/wiki/Bézier_curve
  22943. */
  22944. function CatmullRom(t, p0, p1, p2, p3) {
  22945. const v0 = (p2 - p0) * 0.5;
  22946. const v1 = (p3 - p1) * 0.5;
  22947. const t2 = t * t;
  22948. const t3 = t * t2;
  22949. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22950. } //
  22951. function QuadraticBezierP0(t, p) {
  22952. const k = 1 - t;
  22953. return k * k * p;
  22954. }
  22955. function QuadraticBezierP1(t, p) {
  22956. return 2 * (1 - t) * t * p;
  22957. }
  22958. function QuadraticBezierP2(t, p) {
  22959. return t * t * p;
  22960. }
  22961. function QuadraticBezier(t, p0, p1, p2) {
  22962. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22963. } //
  22964. function CubicBezierP0(t, p) {
  22965. const k = 1 - t;
  22966. return k * k * k * p;
  22967. }
  22968. function CubicBezierP1(t, p) {
  22969. const k = 1 - t;
  22970. return 3 * k * k * t * p;
  22971. }
  22972. function CubicBezierP2(t, p) {
  22973. return 3 * (1 - t) * t * t * p;
  22974. }
  22975. function CubicBezierP3(t, p) {
  22976. return t * t * t * p;
  22977. }
  22978. function CubicBezier(t, p0, p1, p2, p3) {
  22979. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22980. }
  22981. function CubicBezierCurve(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  22982. Curve.call(this);
  22983. this.type = 'CubicBezierCurve';
  22984. this.v0 = v0;
  22985. this.v1 = v1;
  22986. this.v2 = v2;
  22987. this.v3 = v3;
  22988. }
  22989. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22990. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22991. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22992. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  22993. const point = optionalTarget;
  22994. const v0 = this.v0,
  22995. v1 = this.v1,
  22996. v2 = this.v2,
  22997. v3 = this.v3;
  22998. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22999. return point;
  23000. };
  23001. CubicBezierCurve.prototype.copy = function (source) {
  23002. Curve.prototype.copy.call(this, source);
  23003. this.v0.copy(source.v0);
  23004. this.v1.copy(source.v1);
  23005. this.v2.copy(source.v2);
  23006. this.v3.copy(source.v3);
  23007. return this;
  23008. };
  23009. CubicBezierCurve.prototype.toJSON = function () {
  23010. const data = Curve.prototype.toJSON.call(this);
  23011. data.v0 = this.v0.toArray();
  23012. data.v1 = this.v1.toArray();
  23013. data.v2 = this.v2.toArray();
  23014. data.v3 = this.v3.toArray();
  23015. return data;
  23016. };
  23017. CubicBezierCurve.prototype.fromJSON = function (json) {
  23018. Curve.prototype.fromJSON.call(this, json);
  23019. this.v0.fromArray(json.v0);
  23020. this.v1.fromArray(json.v1);
  23021. this.v2.fromArray(json.v2);
  23022. this.v3.fromArray(json.v3);
  23023. return this;
  23024. };
  23025. function CubicBezierCurve3(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  23026. Curve.call(this);
  23027. this.type = 'CubicBezierCurve3';
  23028. this.v0 = v0;
  23029. this.v1 = v1;
  23030. this.v2 = v2;
  23031. this.v3 = v3;
  23032. }
  23033. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23034. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23035. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23036. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23037. const point = optionalTarget;
  23038. const v0 = this.v0,
  23039. v1 = this.v1,
  23040. v2 = this.v2,
  23041. v3 = this.v3;
  23042. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  23043. return point;
  23044. };
  23045. CubicBezierCurve3.prototype.copy = function (source) {
  23046. Curve.prototype.copy.call(this, source);
  23047. this.v0.copy(source.v0);
  23048. this.v1.copy(source.v1);
  23049. this.v2.copy(source.v2);
  23050. this.v3.copy(source.v3);
  23051. return this;
  23052. };
  23053. CubicBezierCurve3.prototype.toJSON = function () {
  23054. const data = Curve.prototype.toJSON.call(this);
  23055. data.v0 = this.v0.toArray();
  23056. data.v1 = this.v1.toArray();
  23057. data.v2 = this.v2.toArray();
  23058. data.v3 = this.v3.toArray();
  23059. return data;
  23060. };
  23061. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23062. Curve.prototype.fromJSON.call(this, json);
  23063. this.v0.fromArray(json.v0);
  23064. this.v1.fromArray(json.v1);
  23065. this.v2.fromArray(json.v2);
  23066. this.v3.fromArray(json.v3);
  23067. return this;
  23068. };
  23069. function LineCurve(v1 = new Vector2(), v2 = new Vector2()) {
  23070. Curve.call(this);
  23071. this.type = 'LineCurve';
  23072. this.v1 = v1;
  23073. this.v2 = v2;
  23074. }
  23075. LineCurve.prototype = Object.create(Curve.prototype);
  23076. LineCurve.prototype.constructor = LineCurve;
  23077. LineCurve.prototype.isLineCurve = true;
  23078. LineCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23079. const point = optionalTarget;
  23080. if (t === 1) {
  23081. point.copy(this.v2);
  23082. } else {
  23083. point.copy(this.v2).sub(this.v1);
  23084. point.multiplyScalar(t).add(this.v1);
  23085. }
  23086. return point;
  23087. }; // Line curve is linear, so we can overwrite default getPointAt
  23088. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23089. return this.getPoint(u, optionalTarget);
  23090. };
  23091. LineCurve.prototype.getTangent = function (t, optionalTarget) {
  23092. const tangent = optionalTarget || new Vector2();
  23093. tangent.copy(this.v2).sub(this.v1).normalize();
  23094. return tangent;
  23095. };
  23096. LineCurve.prototype.copy = function (source) {
  23097. Curve.prototype.copy.call(this, source);
  23098. this.v1.copy(source.v1);
  23099. this.v2.copy(source.v2);
  23100. return this;
  23101. };
  23102. LineCurve.prototype.toJSON = function () {
  23103. const data = Curve.prototype.toJSON.call(this);
  23104. data.v1 = this.v1.toArray();
  23105. data.v2 = this.v2.toArray();
  23106. return data;
  23107. };
  23108. LineCurve.prototype.fromJSON = function (json) {
  23109. Curve.prototype.fromJSON.call(this, json);
  23110. this.v1.fromArray(json.v1);
  23111. this.v2.fromArray(json.v2);
  23112. return this;
  23113. };
  23114. function LineCurve3(v1 = new Vector3(), v2 = new Vector3()) {
  23115. Curve.call(this);
  23116. this.type = 'LineCurve3';
  23117. this.v1 = v1;
  23118. this.v2 = v2;
  23119. }
  23120. LineCurve3.prototype = Object.create(Curve.prototype);
  23121. LineCurve3.prototype.constructor = LineCurve3;
  23122. LineCurve3.prototype.isLineCurve3 = true;
  23123. LineCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23124. const point = optionalTarget;
  23125. if (t === 1) {
  23126. point.copy(this.v2);
  23127. } else {
  23128. point.copy(this.v2).sub(this.v1);
  23129. point.multiplyScalar(t).add(this.v1);
  23130. }
  23131. return point;
  23132. }; // Line curve is linear, so we can overwrite default getPointAt
  23133. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23134. return this.getPoint(u, optionalTarget);
  23135. };
  23136. LineCurve3.prototype.copy = function (source) {
  23137. Curve.prototype.copy.call(this, source);
  23138. this.v1.copy(source.v1);
  23139. this.v2.copy(source.v2);
  23140. return this;
  23141. };
  23142. LineCurve3.prototype.toJSON = function () {
  23143. const data = Curve.prototype.toJSON.call(this);
  23144. data.v1 = this.v1.toArray();
  23145. data.v2 = this.v2.toArray();
  23146. return data;
  23147. };
  23148. LineCurve3.prototype.fromJSON = function (json) {
  23149. Curve.prototype.fromJSON.call(this, json);
  23150. this.v1.fromArray(json.v1);
  23151. this.v2.fromArray(json.v2);
  23152. return this;
  23153. };
  23154. function QuadraticBezierCurve(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  23155. Curve.call(this);
  23156. this.type = 'QuadraticBezierCurve';
  23157. this.v0 = v0;
  23158. this.v1 = v1;
  23159. this.v2 = v2;
  23160. }
  23161. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23162. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23163. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23164. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23165. const point = optionalTarget;
  23166. const v0 = this.v0,
  23167. v1 = this.v1,
  23168. v2 = this.v2;
  23169. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23170. return point;
  23171. };
  23172. QuadraticBezierCurve.prototype.copy = function (source) {
  23173. Curve.prototype.copy.call(this, source);
  23174. this.v0.copy(source.v0);
  23175. this.v1.copy(source.v1);
  23176. this.v2.copy(source.v2);
  23177. return this;
  23178. };
  23179. QuadraticBezierCurve.prototype.toJSON = function () {
  23180. const data = Curve.prototype.toJSON.call(this);
  23181. data.v0 = this.v0.toArray();
  23182. data.v1 = this.v1.toArray();
  23183. data.v2 = this.v2.toArray();
  23184. return data;
  23185. };
  23186. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23187. Curve.prototype.fromJSON.call(this, json);
  23188. this.v0.fromArray(json.v0);
  23189. this.v1.fromArray(json.v1);
  23190. this.v2.fromArray(json.v2);
  23191. return this;
  23192. };
  23193. function QuadraticBezierCurve3(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  23194. Curve.call(this);
  23195. this.type = 'QuadraticBezierCurve3';
  23196. this.v0 = v0;
  23197. this.v1 = v1;
  23198. this.v2 = v2;
  23199. }
  23200. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23201. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23202. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23203. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23204. const point = optionalTarget;
  23205. const v0 = this.v0,
  23206. v1 = this.v1,
  23207. v2 = this.v2;
  23208. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  23209. return point;
  23210. };
  23211. QuadraticBezierCurve3.prototype.copy = function (source) {
  23212. Curve.prototype.copy.call(this, source);
  23213. this.v0.copy(source.v0);
  23214. this.v1.copy(source.v1);
  23215. this.v2.copy(source.v2);
  23216. return this;
  23217. };
  23218. QuadraticBezierCurve3.prototype.toJSON = function () {
  23219. const data = Curve.prototype.toJSON.call(this);
  23220. data.v0 = this.v0.toArray();
  23221. data.v1 = this.v1.toArray();
  23222. data.v2 = this.v2.toArray();
  23223. return data;
  23224. };
  23225. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23226. Curve.prototype.fromJSON.call(this, json);
  23227. this.v0.fromArray(json.v0);
  23228. this.v1.fromArray(json.v1);
  23229. this.v2.fromArray(json.v2);
  23230. return this;
  23231. };
  23232. function SplineCurve(points = []) {
  23233. Curve.call(this);
  23234. this.type = 'SplineCurve';
  23235. this.points = points;
  23236. }
  23237. SplineCurve.prototype = Object.create(Curve.prototype);
  23238. SplineCurve.prototype.constructor = SplineCurve;
  23239. SplineCurve.prototype.isSplineCurve = true;
  23240. SplineCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23241. const point = optionalTarget;
  23242. const points = this.points;
  23243. const p = (points.length - 1) * t;
  23244. const intPoint = Math.floor(p);
  23245. const weight = p - intPoint;
  23246. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23247. const p1 = points[intPoint];
  23248. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23249. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23250. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23251. return point;
  23252. };
  23253. SplineCurve.prototype.copy = function (source) {
  23254. Curve.prototype.copy.call(this, source);
  23255. this.points = [];
  23256. for (let i = 0, l = source.points.length; i < l; i++) {
  23257. const point = source.points[i];
  23258. this.points.push(point.clone());
  23259. }
  23260. return this;
  23261. };
  23262. SplineCurve.prototype.toJSON = function () {
  23263. const data = Curve.prototype.toJSON.call(this);
  23264. data.points = [];
  23265. for (let i = 0, l = this.points.length; i < l; i++) {
  23266. const point = this.points[i];
  23267. data.points.push(point.toArray());
  23268. }
  23269. return data;
  23270. };
  23271. SplineCurve.prototype.fromJSON = function (json) {
  23272. Curve.prototype.fromJSON.call(this, json);
  23273. this.points = [];
  23274. for (let i = 0, l = json.points.length; i < l; i++) {
  23275. const point = json.points[i];
  23276. this.points.push(new Vector2().fromArray(point));
  23277. }
  23278. return this;
  23279. };
  23280. var Curves =
  23281. /*#__PURE__*/
  23282. Object.freeze({
  23283. __proto__: null,
  23284. ArcCurve: ArcCurve,
  23285. CatmullRomCurve3: CatmullRomCurve3,
  23286. CubicBezierCurve: CubicBezierCurve,
  23287. CubicBezierCurve3: CubicBezierCurve3,
  23288. EllipseCurve: EllipseCurve,
  23289. LineCurve: LineCurve,
  23290. LineCurve3: LineCurve3,
  23291. QuadraticBezierCurve: QuadraticBezierCurve,
  23292. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23293. SplineCurve: SplineCurve
  23294. });
  23295. /**************************************************************
  23296. * Curved Path - a curve path is simply a array of connected
  23297. * curves, but retains the api of a curve
  23298. **************************************************************/
  23299. function CurvePath() {
  23300. Curve.call(this);
  23301. this.type = 'CurvePath';
  23302. this.curves = [];
  23303. this.autoClose = false; // Automatically closes the path
  23304. }
  23305. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23306. constructor: CurvePath,
  23307. add: function (curve) {
  23308. this.curves.push(curve);
  23309. },
  23310. closePath: function () {
  23311. // Add a line curve if start and end of lines are not connected
  23312. const startPoint = this.curves[0].getPoint(0);
  23313. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23314. if (!startPoint.equals(endPoint)) {
  23315. this.curves.push(new LineCurve(endPoint, startPoint));
  23316. }
  23317. },
  23318. // To get accurate point with reference to
  23319. // entire path distance at time t,
  23320. // following has to be done:
  23321. // 1. Length of each sub path have to be known
  23322. // 2. Locate and identify type of curve
  23323. // 3. Get t for the curve
  23324. // 4. Return curve.getPointAt(t')
  23325. getPoint: function (t) {
  23326. const d = t * this.getLength();
  23327. const curveLengths = this.getCurveLengths();
  23328. let i = 0; // To think about boundaries points.
  23329. while (i < curveLengths.length) {
  23330. if (curveLengths[i] >= d) {
  23331. const diff = curveLengths[i] - d;
  23332. const curve = this.curves[i];
  23333. const segmentLength = curve.getLength();
  23334. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23335. return curve.getPointAt(u);
  23336. }
  23337. i++;
  23338. }
  23339. return null; // loop where sum != 0, sum > d , sum+1 <d
  23340. },
  23341. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23342. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23343. // getPoint() depends on getLength
  23344. getLength: function () {
  23345. const lens = this.getCurveLengths();
  23346. return lens[lens.length - 1];
  23347. },
  23348. // cacheLengths must be recalculated.
  23349. updateArcLengths: function () {
  23350. this.needsUpdate = true;
  23351. this.cacheLengths = null;
  23352. this.getCurveLengths();
  23353. },
  23354. // Compute lengths and cache them
  23355. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23356. getCurveLengths: function () {
  23357. // We use cache values if curves and cache array are same length
  23358. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23359. return this.cacheLengths;
  23360. } // Get length of sub-curve
  23361. // Push sums into cached array
  23362. const lengths = [];
  23363. let sums = 0;
  23364. for (let i = 0, l = this.curves.length; i < l; i++) {
  23365. sums += this.curves[i].getLength();
  23366. lengths.push(sums);
  23367. }
  23368. this.cacheLengths = lengths;
  23369. return lengths;
  23370. },
  23371. getSpacedPoints: function (divisions = 40) {
  23372. const points = [];
  23373. for (let i = 0; i <= divisions; i++) {
  23374. points.push(this.getPoint(i / divisions));
  23375. }
  23376. if (this.autoClose) {
  23377. points.push(points[0]);
  23378. }
  23379. return points;
  23380. },
  23381. getPoints: function (divisions = 12) {
  23382. const points = [];
  23383. let last;
  23384. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  23385. const curve = curves[i];
  23386. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23387. const pts = curve.getPoints(resolution);
  23388. for (let j = 0; j < pts.length; j++) {
  23389. const point = pts[j];
  23390. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23391. points.push(point);
  23392. last = point;
  23393. }
  23394. }
  23395. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23396. points.push(points[0]);
  23397. }
  23398. return points;
  23399. },
  23400. copy: function (source) {
  23401. Curve.prototype.copy.call(this, source);
  23402. this.curves = [];
  23403. for (let i = 0, l = source.curves.length; i < l; i++) {
  23404. const curve = source.curves[i];
  23405. this.curves.push(curve.clone());
  23406. }
  23407. this.autoClose = source.autoClose;
  23408. return this;
  23409. },
  23410. toJSON: function () {
  23411. const data = Curve.prototype.toJSON.call(this);
  23412. data.autoClose = this.autoClose;
  23413. data.curves = [];
  23414. for (let i = 0, l = this.curves.length; i < l; i++) {
  23415. const curve = this.curves[i];
  23416. data.curves.push(curve.toJSON());
  23417. }
  23418. return data;
  23419. },
  23420. fromJSON: function (json) {
  23421. Curve.prototype.fromJSON.call(this, json);
  23422. this.autoClose = json.autoClose;
  23423. this.curves = [];
  23424. for (let i = 0, l = json.curves.length; i < l; i++) {
  23425. const curve = json.curves[i];
  23426. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23427. }
  23428. return this;
  23429. }
  23430. });
  23431. function Path(points) {
  23432. CurvePath.call(this);
  23433. this.type = 'Path';
  23434. this.currentPoint = new Vector2();
  23435. if (points) {
  23436. this.setFromPoints(points);
  23437. }
  23438. }
  23439. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23440. constructor: Path,
  23441. setFromPoints: function (points) {
  23442. this.moveTo(points[0].x, points[0].y);
  23443. for (let i = 1, l = points.length; i < l; i++) {
  23444. this.lineTo(points[i].x, points[i].y);
  23445. }
  23446. return this;
  23447. },
  23448. moveTo: function (x, y) {
  23449. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23450. return this;
  23451. },
  23452. lineTo: function (x, y) {
  23453. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23454. this.curves.push(curve);
  23455. this.currentPoint.set(x, y);
  23456. return this;
  23457. },
  23458. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23459. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23460. this.curves.push(curve);
  23461. this.currentPoint.set(aX, aY);
  23462. return this;
  23463. },
  23464. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23465. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23466. this.curves.push(curve);
  23467. this.currentPoint.set(aX, aY);
  23468. return this;
  23469. },
  23470. splineThru: function (pts
  23471. /*Array of Vector*/
  23472. ) {
  23473. const npts = [this.currentPoint.clone()].concat(pts);
  23474. const curve = new SplineCurve(npts);
  23475. this.curves.push(curve);
  23476. this.currentPoint.copy(pts[pts.length - 1]);
  23477. return this;
  23478. },
  23479. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23480. const x0 = this.currentPoint.x;
  23481. const y0 = this.currentPoint.y;
  23482. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23483. return this;
  23484. },
  23485. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23486. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23487. return this;
  23488. },
  23489. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23490. const x0 = this.currentPoint.x;
  23491. const y0 = this.currentPoint.y;
  23492. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23493. return this;
  23494. },
  23495. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23496. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23497. if (this.curves.length > 0) {
  23498. // if a previous curve is present, attempt to join
  23499. const firstPoint = curve.getPoint(0);
  23500. if (!firstPoint.equals(this.currentPoint)) {
  23501. this.lineTo(firstPoint.x, firstPoint.y);
  23502. }
  23503. }
  23504. this.curves.push(curve);
  23505. const lastPoint = curve.getPoint(1);
  23506. this.currentPoint.copy(lastPoint);
  23507. return this;
  23508. },
  23509. copy: function (source) {
  23510. CurvePath.prototype.copy.call(this, source);
  23511. this.currentPoint.copy(source.currentPoint);
  23512. return this;
  23513. },
  23514. toJSON: function () {
  23515. const data = CurvePath.prototype.toJSON.call(this);
  23516. data.currentPoint = this.currentPoint.toArray();
  23517. return data;
  23518. },
  23519. fromJSON: function (json) {
  23520. CurvePath.prototype.fromJSON.call(this, json);
  23521. this.currentPoint.fromArray(json.currentPoint);
  23522. return this;
  23523. }
  23524. });
  23525. function Shape(points) {
  23526. Path.call(this, points);
  23527. this.uuid = MathUtils.generateUUID();
  23528. this.type = 'Shape';
  23529. this.holes = [];
  23530. }
  23531. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23532. constructor: Shape,
  23533. getPointsHoles: function (divisions) {
  23534. const holesPts = [];
  23535. for (let i = 0, l = this.holes.length; i < l; i++) {
  23536. holesPts[i] = this.holes[i].getPoints(divisions);
  23537. }
  23538. return holesPts;
  23539. },
  23540. // get points of shape and holes (keypoints based on segments parameter)
  23541. extractPoints: function (divisions) {
  23542. return {
  23543. shape: this.getPoints(divisions),
  23544. holes: this.getPointsHoles(divisions)
  23545. };
  23546. },
  23547. copy: function (source) {
  23548. Path.prototype.copy.call(this, source);
  23549. this.holes = [];
  23550. for (let i = 0, l = source.holes.length; i < l; i++) {
  23551. const hole = source.holes[i];
  23552. this.holes.push(hole.clone());
  23553. }
  23554. return this;
  23555. },
  23556. toJSON: function () {
  23557. const data = Path.prototype.toJSON.call(this);
  23558. data.uuid = this.uuid;
  23559. data.holes = [];
  23560. for (let i = 0, l = this.holes.length; i < l; i++) {
  23561. const hole = this.holes[i];
  23562. data.holes.push(hole.toJSON());
  23563. }
  23564. return data;
  23565. },
  23566. fromJSON: function (json) {
  23567. Path.prototype.fromJSON.call(this, json);
  23568. this.uuid = json.uuid;
  23569. this.holes = [];
  23570. for (let i = 0, l = json.holes.length; i < l; i++) {
  23571. const hole = json.holes[i];
  23572. this.holes.push(new Path().fromJSON(hole));
  23573. }
  23574. return this;
  23575. }
  23576. });
  23577. function Light(color, intensity = 1) {
  23578. Object3D.call(this);
  23579. this.type = 'Light';
  23580. this.color = new Color(color);
  23581. this.intensity = intensity;
  23582. }
  23583. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23584. constructor: Light,
  23585. isLight: true,
  23586. copy: function (source) {
  23587. Object3D.prototype.copy.call(this, source);
  23588. this.color.copy(source.color);
  23589. this.intensity = source.intensity;
  23590. return this;
  23591. },
  23592. toJSON: function (meta) {
  23593. const data = Object3D.prototype.toJSON.call(this, meta);
  23594. data.object.color = this.color.getHex();
  23595. data.object.intensity = this.intensity;
  23596. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23597. if (this.distance !== undefined) data.object.distance = this.distance;
  23598. if (this.angle !== undefined) data.object.angle = this.angle;
  23599. if (this.decay !== undefined) data.object.decay = this.decay;
  23600. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23601. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23602. return data;
  23603. }
  23604. });
  23605. function HemisphereLight(skyColor, groundColor, intensity) {
  23606. Light.call(this, skyColor, intensity);
  23607. this.type = 'HemisphereLight';
  23608. this.position.copy(Object3D.DefaultUp);
  23609. this.updateMatrix();
  23610. this.groundColor = new Color(groundColor);
  23611. }
  23612. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23613. constructor: HemisphereLight,
  23614. isHemisphereLight: true,
  23615. copy: function (source) {
  23616. Light.prototype.copy.call(this, source);
  23617. this.groundColor.copy(source.groundColor);
  23618. return this;
  23619. }
  23620. });
  23621. function LightShadow(camera) {
  23622. this.camera = camera;
  23623. this.bias = 0;
  23624. this.normalBias = 0;
  23625. this.radius = 1;
  23626. this.mapSize = new Vector2(512, 512);
  23627. this.map = null;
  23628. this.mapPass = null;
  23629. this.matrix = new Matrix4();
  23630. this.autoUpdate = true;
  23631. this.needsUpdate = false;
  23632. this._frustum = new Frustum();
  23633. this._frameExtents = new Vector2(1, 1);
  23634. this._viewportCount = 1;
  23635. this._viewports = [new Vector4(0, 0, 1, 1)];
  23636. }
  23637. Object.assign(LightShadow.prototype, {
  23638. _projScreenMatrix: new Matrix4(),
  23639. _lightPositionWorld: new Vector3(),
  23640. _lookTarget: new Vector3(),
  23641. getViewportCount: function () {
  23642. return this._viewportCount;
  23643. },
  23644. getFrustum: function () {
  23645. return this._frustum;
  23646. },
  23647. updateMatrices: function (light) {
  23648. const shadowCamera = this.camera,
  23649. shadowMatrix = this.matrix,
  23650. projScreenMatrix = this._projScreenMatrix,
  23651. lookTarget = this._lookTarget,
  23652. lightPositionWorld = this._lightPositionWorld;
  23653. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23654. shadowCamera.position.copy(lightPositionWorld);
  23655. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23656. shadowCamera.lookAt(lookTarget);
  23657. shadowCamera.updateMatrixWorld();
  23658. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23659. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23660. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  23661. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23662. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23663. },
  23664. getViewport: function (viewportIndex) {
  23665. return this._viewports[viewportIndex];
  23666. },
  23667. getFrameExtents: function () {
  23668. return this._frameExtents;
  23669. },
  23670. copy: function (source) {
  23671. this.camera = source.camera.clone();
  23672. this.bias = source.bias;
  23673. this.radius = source.radius;
  23674. this.mapSize.copy(source.mapSize);
  23675. return this;
  23676. },
  23677. clone: function () {
  23678. return new this.constructor().copy(this);
  23679. },
  23680. toJSON: function () {
  23681. const object = {};
  23682. if (this.bias !== 0) object.bias = this.bias;
  23683. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23684. if (this.radius !== 1) object.radius = this.radius;
  23685. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23686. object.camera = this.camera.toJSON(false).object;
  23687. delete object.camera.matrix;
  23688. return object;
  23689. }
  23690. });
  23691. function SpotLightShadow() {
  23692. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  23693. this.focus = 1;
  23694. }
  23695. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23696. constructor: SpotLightShadow,
  23697. isSpotLightShadow: true,
  23698. updateMatrices: function (light) {
  23699. const camera = this.camera;
  23700. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  23701. const aspect = this.mapSize.width / this.mapSize.height;
  23702. const far = light.distance || camera.far;
  23703. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23704. camera.fov = fov;
  23705. camera.aspect = aspect;
  23706. camera.far = far;
  23707. camera.updateProjectionMatrix();
  23708. }
  23709. LightShadow.prototype.updateMatrices.call(this, light);
  23710. }
  23711. });
  23712. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  23713. Light.call(this, color, intensity);
  23714. this.type = 'SpotLight';
  23715. this.position.copy(Object3D.DefaultUp);
  23716. this.updateMatrix();
  23717. this.target = new Object3D();
  23718. Object.defineProperty(this, 'power', {
  23719. get: function () {
  23720. // intensity = power per solid angle.
  23721. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23722. return this.intensity * Math.PI;
  23723. },
  23724. set: function (power) {
  23725. // intensity = power per solid angle.
  23726. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23727. this.intensity = power / Math.PI;
  23728. }
  23729. });
  23730. this.distance = distance !== undefined ? distance : 0;
  23731. this.angle = angle !== undefined ? angle : Math.PI / 3;
  23732. this.penumbra = penumbra !== undefined ? penumbra : 0;
  23733. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23734. this.shadow = new SpotLightShadow();
  23735. }
  23736. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  23737. constructor: SpotLight,
  23738. isSpotLight: true,
  23739. copy: function (source) {
  23740. Light.prototype.copy.call(this, source);
  23741. this.distance = source.distance;
  23742. this.angle = source.angle;
  23743. this.penumbra = source.penumbra;
  23744. this.decay = source.decay;
  23745. this.target = source.target.clone();
  23746. this.shadow = source.shadow.clone();
  23747. return this;
  23748. }
  23749. });
  23750. function PointLightShadow() {
  23751. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  23752. this._frameExtents = new Vector2(4, 2);
  23753. this._viewportCount = 6;
  23754. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23755. // following orientation:
  23756. //
  23757. // xzXZ
  23758. // y Y
  23759. //
  23760. // X - Positive x direction
  23761. // x - Negative x direction
  23762. // Y - Positive y direction
  23763. // y - Negative y direction
  23764. // Z - Positive z direction
  23765. // z - Negative z direction
  23766. // positive X
  23767. new Vector4(2, 1, 1, 1), // negative X
  23768. new Vector4(0, 1, 1, 1), // positive Z
  23769. new Vector4(3, 1, 1, 1), // negative Z
  23770. new Vector4(1, 1, 1, 1), // positive Y
  23771. new Vector4(3, 0, 1, 1), // negative Y
  23772. new Vector4(1, 0, 1, 1)];
  23773. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  23774. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  23775. }
  23776. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23777. constructor: PointLightShadow,
  23778. isPointLightShadow: true,
  23779. updateMatrices: function (light, viewportIndex = 0) {
  23780. const camera = this.camera,
  23781. shadowMatrix = this.matrix,
  23782. lightPositionWorld = this._lightPositionWorld,
  23783. lookTarget = this._lookTarget,
  23784. projScreenMatrix = this._projScreenMatrix;
  23785. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23786. camera.position.copy(lightPositionWorld);
  23787. lookTarget.copy(camera.position);
  23788. lookTarget.add(this._cubeDirections[viewportIndex]);
  23789. camera.up.copy(this._cubeUps[viewportIndex]);
  23790. camera.lookAt(lookTarget);
  23791. camera.updateMatrixWorld();
  23792. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23793. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23794. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23795. }
  23796. });
  23797. function PointLight(color, intensity, distance, decay) {
  23798. Light.call(this, color, intensity);
  23799. this.type = 'PointLight';
  23800. Object.defineProperty(this, 'power', {
  23801. get: function () {
  23802. // intensity = power per solid angle.
  23803. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23804. return this.intensity * 4 * Math.PI;
  23805. },
  23806. set: function (power) {
  23807. // intensity = power per solid angle.
  23808. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23809. this.intensity = power / (4 * Math.PI);
  23810. }
  23811. });
  23812. this.distance = distance !== undefined ? distance : 0;
  23813. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23814. this.shadow = new PointLightShadow();
  23815. }
  23816. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23817. constructor: PointLight,
  23818. isPointLight: true,
  23819. copy: function (source) {
  23820. Light.prototype.copy.call(this, source);
  23821. this.distance = source.distance;
  23822. this.decay = source.decay;
  23823. this.shadow = source.shadow.clone();
  23824. return this;
  23825. }
  23826. });
  23827. function OrthographicCamera(left, right, top, bottom, near, far) {
  23828. Camera.call(this);
  23829. this.type = 'OrthographicCamera';
  23830. this.zoom = 1;
  23831. this.view = null;
  23832. this.left = left !== undefined ? left : -1;
  23833. this.right = right !== undefined ? right : 1;
  23834. this.top = top !== undefined ? top : 1;
  23835. this.bottom = bottom !== undefined ? bottom : -1;
  23836. this.near = near !== undefined ? near : 0.1;
  23837. this.far = far !== undefined ? far : 2000;
  23838. this.updateProjectionMatrix();
  23839. }
  23840. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23841. constructor: OrthographicCamera,
  23842. isOrthographicCamera: true,
  23843. copy: function (source, recursive) {
  23844. Camera.prototype.copy.call(this, source, recursive);
  23845. this.left = source.left;
  23846. this.right = source.right;
  23847. this.top = source.top;
  23848. this.bottom = source.bottom;
  23849. this.near = source.near;
  23850. this.far = source.far;
  23851. this.zoom = source.zoom;
  23852. this.view = source.view === null ? null : Object.assign({}, source.view);
  23853. return this;
  23854. },
  23855. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23856. if (this.view === null) {
  23857. this.view = {
  23858. enabled: true,
  23859. fullWidth: 1,
  23860. fullHeight: 1,
  23861. offsetX: 0,
  23862. offsetY: 0,
  23863. width: 1,
  23864. height: 1
  23865. };
  23866. }
  23867. this.view.enabled = true;
  23868. this.view.fullWidth = fullWidth;
  23869. this.view.fullHeight = fullHeight;
  23870. this.view.offsetX = x;
  23871. this.view.offsetY = y;
  23872. this.view.width = width;
  23873. this.view.height = height;
  23874. this.updateProjectionMatrix();
  23875. },
  23876. clearViewOffset: function () {
  23877. if (this.view !== null) {
  23878. this.view.enabled = false;
  23879. }
  23880. this.updateProjectionMatrix();
  23881. },
  23882. updateProjectionMatrix: function () {
  23883. const dx = (this.right - this.left) / (2 * this.zoom);
  23884. const dy = (this.top - this.bottom) / (2 * this.zoom);
  23885. const cx = (this.right + this.left) / 2;
  23886. const cy = (this.top + this.bottom) / 2;
  23887. let left = cx - dx;
  23888. let right = cx + dx;
  23889. let top = cy + dy;
  23890. let bottom = cy - dy;
  23891. if (this.view !== null && this.view.enabled) {
  23892. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  23893. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  23894. left += scaleW * this.view.offsetX;
  23895. right = left + scaleW * this.view.width;
  23896. top -= scaleH * this.view.offsetY;
  23897. bottom = top - scaleH * this.view.height;
  23898. }
  23899. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23900. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  23901. },
  23902. toJSON: function (meta) {
  23903. const data = Object3D.prototype.toJSON.call(this, meta);
  23904. data.object.zoom = this.zoom;
  23905. data.object.left = this.left;
  23906. data.object.right = this.right;
  23907. data.object.top = this.top;
  23908. data.object.bottom = this.bottom;
  23909. data.object.near = this.near;
  23910. data.object.far = this.far;
  23911. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23912. return data;
  23913. }
  23914. });
  23915. function DirectionalLightShadow() {
  23916. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23917. }
  23918. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23919. constructor: DirectionalLightShadow,
  23920. isDirectionalLightShadow: true,
  23921. updateMatrices: function (light) {
  23922. LightShadow.prototype.updateMatrices.call(this, light);
  23923. }
  23924. });
  23925. function DirectionalLight(color, intensity) {
  23926. Light.call(this, color, intensity);
  23927. this.type = 'DirectionalLight';
  23928. this.position.copy(Object3D.DefaultUp);
  23929. this.updateMatrix();
  23930. this.target = new Object3D();
  23931. this.shadow = new DirectionalLightShadow();
  23932. }
  23933. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23934. constructor: DirectionalLight,
  23935. isDirectionalLight: true,
  23936. copy: function (source) {
  23937. Light.prototype.copy.call(this, source);
  23938. this.target = source.target.clone();
  23939. this.shadow = source.shadow.clone();
  23940. return this;
  23941. }
  23942. });
  23943. function AmbientLight(color, intensity) {
  23944. Light.call(this, color, intensity);
  23945. this.type = 'AmbientLight';
  23946. }
  23947. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23948. constructor: AmbientLight,
  23949. isAmbientLight: true
  23950. });
  23951. function RectAreaLight(color, intensity, width, height) {
  23952. Light.call(this, color, intensity);
  23953. this.type = 'RectAreaLight';
  23954. this.width = width !== undefined ? width : 10;
  23955. this.height = height !== undefined ? height : 10;
  23956. }
  23957. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23958. constructor: RectAreaLight,
  23959. isRectAreaLight: true,
  23960. copy: function (source) {
  23961. Light.prototype.copy.call(this, source);
  23962. this.width = source.width;
  23963. this.height = source.height;
  23964. return this;
  23965. },
  23966. toJSON: function (meta) {
  23967. const data = Light.prototype.toJSON.call(this, meta);
  23968. data.object.width = this.width;
  23969. data.object.height = this.height;
  23970. return data;
  23971. }
  23972. });
  23973. /**
  23974. * Primary reference:
  23975. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23976. *
  23977. * Secondary reference:
  23978. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23979. */
  23980. // 3-band SH defined by 9 coefficients
  23981. class SphericalHarmonics3 {
  23982. constructor() {
  23983. Object.defineProperty(this, 'isSphericalHarmonics3', {
  23984. value: true
  23985. });
  23986. this.coefficients = [];
  23987. for (let i = 0; i < 9; i++) {
  23988. this.coefficients.push(new Vector3());
  23989. }
  23990. }
  23991. set(coefficients) {
  23992. for (let i = 0; i < 9; i++) {
  23993. this.coefficients[i].copy(coefficients[i]);
  23994. }
  23995. return this;
  23996. }
  23997. zero() {
  23998. for (let i = 0; i < 9; i++) {
  23999. this.coefficients[i].set(0, 0, 0);
  24000. }
  24001. return this;
  24002. } // get the radiance in the direction of the normal
  24003. // target is a Vector3
  24004. getAt(normal, target) {
  24005. // normal is assumed to be unit length
  24006. const x = normal.x,
  24007. y = normal.y,
  24008. z = normal.z;
  24009. const coeff = this.coefficients; // band 0
  24010. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24011. target.addScaledVector(coeff[1], 0.488603 * y);
  24012. target.addScaledVector(coeff[2], 0.488603 * z);
  24013. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  24014. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24015. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24016. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24017. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24018. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24019. return target;
  24020. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24021. // target is a Vector3
  24022. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24023. getIrradianceAt(normal, target) {
  24024. // normal is assumed to be unit length
  24025. const x = normal.x,
  24026. y = normal.y,
  24027. z = normal.z;
  24028. const coeff = this.coefficients; // band 0
  24029. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24030. // band 1
  24031. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24032. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24033. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  24034. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24035. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24036. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24037. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24038. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24039. return target;
  24040. }
  24041. add(sh) {
  24042. for (let i = 0; i < 9; i++) {
  24043. this.coefficients[i].add(sh.coefficients[i]);
  24044. }
  24045. return this;
  24046. }
  24047. addScaledSH(sh, s) {
  24048. for (let i = 0; i < 9; i++) {
  24049. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24050. }
  24051. return this;
  24052. }
  24053. scale(s) {
  24054. for (let i = 0; i < 9; i++) {
  24055. this.coefficients[i].multiplyScalar(s);
  24056. }
  24057. return this;
  24058. }
  24059. lerp(sh, alpha) {
  24060. for (let i = 0; i < 9; i++) {
  24061. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24062. }
  24063. return this;
  24064. }
  24065. equals(sh) {
  24066. for (let i = 0; i < 9; i++) {
  24067. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24068. return false;
  24069. }
  24070. }
  24071. return true;
  24072. }
  24073. copy(sh) {
  24074. return this.set(sh.coefficients);
  24075. }
  24076. clone() {
  24077. return new this.constructor().copy(this);
  24078. }
  24079. fromArray(array, offset = 0) {
  24080. const coefficients = this.coefficients;
  24081. for (let i = 0; i < 9; i++) {
  24082. coefficients[i].fromArray(array, offset + i * 3);
  24083. }
  24084. return this;
  24085. }
  24086. toArray(array = [], offset = 0) {
  24087. const coefficients = this.coefficients;
  24088. for (let i = 0; i < 9; i++) {
  24089. coefficients[i].toArray(array, offset + i * 3);
  24090. }
  24091. return array;
  24092. } // evaluate the basis functions
  24093. // shBasis is an Array[ 9 ]
  24094. static getBasisAt(normal, shBasis) {
  24095. // normal is assumed to be unit length
  24096. const x = normal.x,
  24097. y = normal.y,
  24098. z = normal.z; // band 0
  24099. shBasis[0] = 0.282095; // band 1
  24100. shBasis[1] = 0.488603 * y;
  24101. shBasis[2] = 0.488603 * z;
  24102. shBasis[3] = 0.488603 * x; // band 2
  24103. shBasis[4] = 1.092548 * x * y;
  24104. shBasis[5] = 1.092548 * y * z;
  24105. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24106. shBasis[7] = 1.092548 * x * z;
  24107. shBasis[8] = 0.546274 * (x * x - y * y);
  24108. }
  24109. }
  24110. exports.SphericalHarmonics3 = SphericalHarmonics3;
  24111. function LightProbe(sh, intensity) {
  24112. Light.call(this, undefined, intensity);
  24113. this.type = 'LightProbe';
  24114. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24115. }
  24116. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24117. constructor: LightProbe,
  24118. isLightProbe: true,
  24119. copy: function (source) {
  24120. Light.prototype.copy.call(this, source);
  24121. this.sh.copy(source.sh);
  24122. return this;
  24123. },
  24124. fromJSON: function (json) {
  24125. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24126. this.sh.fromArray(json.sh);
  24127. return this;
  24128. },
  24129. toJSON: function (meta) {
  24130. const data = Light.prototype.toJSON.call(this, meta);
  24131. data.object.sh = this.sh.toArray();
  24132. return data;
  24133. }
  24134. });
  24135. function MaterialLoader(manager) {
  24136. Loader.call(this, manager);
  24137. this.textures = {};
  24138. }
  24139. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24140. constructor: MaterialLoader,
  24141. load: function (url, onLoad, onProgress, onError) {
  24142. const scope = this;
  24143. const loader = new FileLoader(scope.manager);
  24144. loader.setPath(scope.path);
  24145. loader.setRequestHeader(scope.requestHeader);
  24146. loader.setWithCredentials(scope.withCredentials);
  24147. loader.load(url, function (text) {
  24148. try {
  24149. onLoad(scope.parse(JSON.parse(text)));
  24150. } catch (e) {
  24151. if (onError) {
  24152. onError(e);
  24153. } else {
  24154. console.error(e);
  24155. }
  24156. scope.manager.itemError(url);
  24157. }
  24158. }, onProgress, onError);
  24159. },
  24160. parse: function (json) {
  24161. const textures = this.textures;
  24162. function getTexture(name) {
  24163. if (textures[name] === undefined) {
  24164. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24165. }
  24166. return textures[name];
  24167. }
  24168. const material = new Materials[json.type]();
  24169. if (json.uuid !== undefined) material.uuid = json.uuid;
  24170. if (json.name !== undefined) material.name = json.name;
  24171. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24172. if (json.roughness !== undefined) material.roughness = json.roughness;
  24173. if (json.metalness !== undefined) material.metalness = json.metalness;
  24174. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24175. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24176. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24177. if (json.shininess !== undefined) material.shininess = json.shininess;
  24178. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24179. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24180. if (json.fog !== undefined) material.fog = json.fog;
  24181. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24182. if (json.blending !== undefined) material.blending = json.blending;
  24183. if (json.combine !== undefined) material.combine = json.combine;
  24184. if (json.side !== undefined) material.side = json.side;
  24185. if (json.opacity !== undefined) material.opacity = json.opacity;
  24186. if (json.transparent !== undefined) material.transparent = json.transparent;
  24187. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24188. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24189. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24190. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24191. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24192. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24193. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24194. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24195. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24196. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24197. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24198. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24199. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24200. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24201. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24202. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24203. if (json.rotation !== undefined) material.rotation = json.rotation;
  24204. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24205. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24206. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24207. if (json.scale !== undefined) material.scale = json.scale;
  24208. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24209. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24210. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24211. if (json.skinning !== undefined) material.skinning = json.skinning;
  24212. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24213. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24214. if (json.dithering !== undefined) material.dithering = json.dithering;
  24215. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  24216. if (json.visible !== undefined) material.visible = json.visible;
  24217. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24218. if (json.userData !== undefined) material.userData = json.userData;
  24219. if (json.vertexColors !== undefined) {
  24220. if (typeof json.vertexColors === 'number') {
  24221. material.vertexColors = json.vertexColors > 0 ? true : false;
  24222. } else {
  24223. material.vertexColors = json.vertexColors;
  24224. }
  24225. } // Shader Material
  24226. if (json.uniforms !== undefined) {
  24227. for (const name in json.uniforms) {
  24228. const uniform = json.uniforms[name];
  24229. material.uniforms[name] = {};
  24230. switch (uniform.type) {
  24231. case 't':
  24232. material.uniforms[name].value = getTexture(uniform.value);
  24233. break;
  24234. case 'c':
  24235. material.uniforms[name].value = new Color().setHex(uniform.value);
  24236. break;
  24237. case 'v2':
  24238. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24239. break;
  24240. case 'v3':
  24241. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24242. break;
  24243. case 'v4':
  24244. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24245. break;
  24246. case 'm3':
  24247. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24248. break;
  24249. case 'm4':
  24250. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24251. break;
  24252. default:
  24253. material.uniforms[name].value = uniform.value;
  24254. }
  24255. }
  24256. }
  24257. if (json.defines !== undefined) material.defines = json.defines;
  24258. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24259. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24260. if (json.extensions !== undefined) {
  24261. for (const key in json.extensions) {
  24262. material.extensions[key] = json.extensions[key];
  24263. }
  24264. } // Deprecated
  24265. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24266. // for PointsMaterial
  24267. if (json.size !== undefined) material.size = json.size;
  24268. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24269. if (json.map !== undefined) material.map = getTexture(json.map);
  24270. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24271. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24272. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24273. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24274. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24275. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24276. if (json.normalScale !== undefined) {
  24277. let normalScale = json.normalScale;
  24278. if (Array.isArray(normalScale) === false) {
  24279. // Blender exporter used to export a scalar. See #7459
  24280. normalScale = [normalScale, normalScale];
  24281. }
  24282. material.normalScale = new Vector2().fromArray(normalScale);
  24283. }
  24284. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24285. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24286. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24287. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24288. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24289. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24290. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24291. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24292. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24293. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24294. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24295. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24296. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24297. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24298. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24299. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24300. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24301. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24302. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24303. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24304. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24305. if (json.transmission !== undefined) material.transmission = json.transmission;
  24306. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24307. return material;
  24308. },
  24309. setTextures: function (value) {
  24310. this.textures = value;
  24311. return this;
  24312. }
  24313. });
  24314. const LoaderUtils = {
  24315. decodeText: function (array) {
  24316. if (typeof TextDecoder !== 'undefined') {
  24317. return new TextDecoder().decode(array);
  24318. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24319. // throws a "maximum call stack size exceeded" error for large arrays.
  24320. let s = '';
  24321. for (let i = 0, il = array.length; i < il; i++) {
  24322. // Implicitly assumes little-endian.
  24323. s += String.fromCharCode(array[i]);
  24324. }
  24325. try {
  24326. // merges multi-byte utf-8 characters.
  24327. return decodeURIComponent(escape(s));
  24328. } catch (e) {
  24329. // see #16358
  24330. return s;
  24331. }
  24332. },
  24333. extractUrlBase: function (url) {
  24334. const index = url.lastIndexOf('/');
  24335. if (index === -1) return './';
  24336. return url.substr(0, index + 1);
  24337. }
  24338. };
  24339. exports.LoaderUtils = LoaderUtils;
  24340. function InstancedBufferGeometry() {
  24341. BufferGeometry.call(this);
  24342. this.type = 'InstancedBufferGeometry';
  24343. this.instanceCount = Infinity;
  24344. }
  24345. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24346. constructor: InstancedBufferGeometry,
  24347. isInstancedBufferGeometry: true,
  24348. copy: function (source) {
  24349. BufferGeometry.prototype.copy.call(this, source);
  24350. this.instanceCount = source.instanceCount;
  24351. return this;
  24352. },
  24353. clone: function () {
  24354. return new this.constructor().copy(this);
  24355. },
  24356. toJSON: function () {
  24357. const data = BufferGeometry.prototype.toJSON.call(this);
  24358. data.instanceCount = this.instanceCount;
  24359. data.isInstancedBufferGeometry = true;
  24360. return data;
  24361. }
  24362. });
  24363. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24364. if (typeof normalized === 'number') {
  24365. meshPerAttribute = normalized;
  24366. normalized = false;
  24367. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24368. }
  24369. BufferAttribute.call(this, array, itemSize, normalized);
  24370. this.meshPerAttribute = meshPerAttribute || 1;
  24371. }
  24372. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24373. constructor: InstancedBufferAttribute,
  24374. isInstancedBufferAttribute: true,
  24375. copy: function (source) {
  24376. BufferAttribute.prototype.copy.call(this, source);
  24377. this.meshPerAttribute = source.meshPerAttribute;
  24378. return this;
  24379. },
  24380. toJSON: function () {
  24381. const data = BufferAttribute.prototype.toJSON.call(this);
  24382. data.meshPerAttribute = this.meshPerAttribute;
  24383. data.isInstancedBufferAttribute = true;
  24384. return data;
  24385. }
  24386. });
  24387. function BufferGeometryLoader(manager) {
  24388. Loader.call(this, manager);
  24389. }
  24390. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24391. constructor: BufferGeometryLoader,
  24392. load: function (url, onLoad, onProgress, onError) {
  24393. const scope = this;
  24394. const loader = new FileLoader(scope.manager);
  24395. loader.setPath(scope.path);
  24396. loader.setRequestHeader(scope.requestHeader);
  24397. loader.setWithCredentials(scope.withCredentials);
  24398. loader.load(url, function (text) {
  24399. try {
  24400. onLoad(scope.parse(JSON.parse(text)));
  24401. } catch (e) {
  24402. if (onError) {
  24403. onError(e);
  24404. } else {
  24405. console.error(e);
  24406. }
  24407. scope.manager.itemError(url);
  24408. }
  24409. }, onProgress, onError);
  24410. },
  24411. parse: function (json) {
  24412. const interleavedBufferMap = {};
  24413. const arrayBufferMap = {};
  24414. function getInterleavedBuffer(json, uuid) {
  24415. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24416. const interleavedBuffers = json.interleavedBuffers;
  24417. const interleavedBuffer = interleavedBuffers[uuid];
  24418. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24419. const array = getTypedArray(interleavedBuffer.type, buffer);
  24420. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24421. ib.uuid = interleavedBuffer.uuid;
  24422. interleavedBufferMap[uuid] = ib;
  24423. return ib;
  24424. }
  24425. function getArrayBuffer(json, uuid) {
  24426. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24427. const arrayBuffers = json.arrayBuffers;
  24428. const arrayBuffer = arrayBuffers[uuid];
  24429. const ab = new Uint32Array(arrayBuffer).buffer;
  24430. arrayBufferMap[uuid] = ab;
  24431. return ab;
  24432. }
  24433. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24434. const index = json.data.index;
  24435. if (index !== undefined) {
  24436. const typedArray = getTypedArray(index.type, index.array);
  24437. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24438. }
  24439. const attributes = json.data.attributes;
  24440. for (const key in attributes) {
  24441. const attribute = attributes[key];
  24442. let bufferAttribute;
  24443. if (attribute.isInterleavedBufferAttribute) {
  24444. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24445. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24446. } else {
  24447. const typedArray = getTypedArray(attribute.type, attribute.array);
  24448. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24449. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24450. }
  24451. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24452. geometry.setAttribute(key, bufferAttribute);
  24453. }
  24454. const morphAttributes = json.data.morphAttributes;
  24455. if (morphAttributes) {
  24456. for (const key in morphAttributes) {
  24457. const attributeArray = morphAttributes[key];
  24458. const array = [];
  24459. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24460. const attribute = attributeArray[i];
  24461. let bufferAttribute;
  24462. if (attribute.isInterleavedBufferAttribute) {
  24463. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24464. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24465. } else {
  24466. const typedArray = getTypedArray(attribute.type, attribute.array);
  24467. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24468. }
  24469. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24470. array.push(bufferAttribute);
  24471. }
  24472. geometry.morphAttributes[key] = array;
  24473. }
  24474. }
  24475. const morphTargetsRelative = json.data.morphTargetsRelative;
  24476. if (morphTargetsRelative) {
  24477. geometry.morphTargetsRelative = true;
  24478. }
  24479. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24480. if (groups !== undefined) {
  24481. for (let i = 0, n = groups.length; i !== n; ++i) {
  24482. const group = groups[i];
  24483. geometry.addGroup(group.start, group.count, group.materialIndex);
  24484. }
  24485. }
  24486. const boundingSphere = json.data.boundingSphere;
  24487. if (boundingSphere !== undefined) {
  24488. const center = new Vector3();
  24489. if (boundingSphere.center !== undefined) {
  24490. center.fromArray(boundingSphere.center);
  24491. }
  24492. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24493. }
  24494. if (json.name) geometry.name = json.name;
  24495. if (json.userData) geometry.userData = json.userData;
  24496. return geometry;
  24497. }
  24498. });
  24499. class ObjectLoader extends Loader {
  24500. constructor(manager) {
  24501. super(manager);
  24502. }
  24503. load(url, onLoad, onProgress, onError) {
  24504. const scope = this;
  24505. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24506. this.resourcePath = this.resourcePath || path;
  24507. const loader = new FileLoader(this.manager);
  24508. loader.setPath(this.path);
  24509. loader.setRequestHeader(this.requestHeader);
  24510. loader.setWithCredentials(this.withCredentials);
  24511. loader.load(url, function (text) {
  24512. let json = null;
  24513. try {
  24514. json = JSON.parse(text);
  24515. } catch (error) {
  24516. if (onError !== undefined) onError(error);
  24517. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24518. return;
  24519. }
  24520. const metadata = json.metadata;
  24521. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24522. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24523. return;
  24524. }
  24525. scope.parse(json, onLoad);
  24526. }, onProgress, onError);
  24527. }
  24528. parse(json, onLoad) {
  24529. const animations = this.parseAnimations(json.animations);
  24530. const shapes = this.parseShapes(json.shapes);
  24531. const geometries = this.parseGeometries(json.geometries, shapes);
  24532. const images = this.parseImages(json.images, function () {
  24533. if (onLoad !== undefined) onLoad(object);
  24534. });
  24535. const textures = this.parseTextures(json.textures, images);
  24536. const materials = this.parseMaterials(json.materials, textures);
  24537. const object = this.parseObject(json.object, geometries, materials, animations);
  24538. const skeletons = this.parseSkeletons(json.skeletons, object);
  24539. this.bindSkeletons(object, skeletons); //
  24540. if (onLoad !== undefined) {
  24541. let hasImages = false;
  24542. for (const uuid in images) {
  24543. if (images[uuid] instanceof HTMLImageElement) {
  24544. hasImages = true;
  24545. break;
  24546. }
  24547. }
  24548. if (hasImages === false) onLoad(object);
  24549. }
  24550. return object;
  24551. }
  24552. parseShapes(json) {
  24553. const shapes = {};
  24554. if (json !== undefined) {
  24555. for (let i = 0, l = json.length; i < l; i++) {
  24556. const shape = new Shape().fromJSON(json[i]);
  24557. shapes[shape.uuid] = shape;
  24558. }
  24559. }
  24560. return shapes;
  24561. }
  24562. parseSkeletons(json, object) {
  24563. const skeletons = {};
  24564. const bones = {}; // generate bone lookup table
  24565. object.traverse(function (child) {
  24566. if (child.isBone) bones[child.uuid] = child;
  24567. }); // create skeletons
  24568. if (json !== undefined) {
  24569. for (let i = 0, l = json.length; i < l; i++) {
  24570. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24571. skeletons[skeleton.uuid] = skeleton;
  24572. }
  24573. }
  24574. return skeletons;
  24575. }
  24576. parseGeometries(json, shapes) {
  24577. const geometries = {};
  24578. let geometryShapes;
  24579. if (json !== undefined) {
  24580. const bufferGeometryLoader = new BufferGeometryLoader();
  24581. for (let i = 0, l = json.length; i < l; i++) {
  24582. let geometry;
  24583. const data = json[i];
  24584. switch (data.type) {
  24585. case 'PlaneGeometry':
  24586. case 'PlaneBufferGeometry':
  24587. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24588. break;
  24589. case 'BoxGeometry':
  24590. case 'BoxBufferGeometry':
  24591. case 'CubeGeometry':
  24592. // backwards compatible
  24593. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24594. break;
  24595. case 'CircleGeometry':
  24596. case 'CircleBufferGeometry':
  24597. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24598. break;
  24599. case 'CylinderGeometry':
  24600. case 'CylinderBufferGeometry':
  24601. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24602. break;
  24603. case 'ConeGeometry':
  24604. case 'ConeBufferGeometry':
  24605. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24606. break;
  24607. case 'SphereGeometry':
  24608. case 'SphereBufferGeometry':
  24609. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24610. break;
  24611. case 'DodecahedronGeometry':
  24612. case 'DodecahedronBufferGeometry':
  24613. case 'IcosahedronGeometry':
  24614. case 'IcosahedronBufferGeometry':
  24615. case 'OctahedronGeometry':
  24616. case 'OctahedronBufferGeometry':
  24617. case 'TetrahedronGeometry':
  24618. case 'TetrahedronBufferGeometry':
  24619. geometry = new Geometries[data.type](data.radius, data.detail);
  24620. break;
  24621. case 'RingGeometry':
  24622. case 'RingBufferGeometry':
  24623. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24624. break;
  24625. case 'TorusGeometry':
  24626. case 'TorusBufferGeometry':
  24627. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24628. break;
  24629. case 'TorusKnotGeometry':
  24630. case 'TorusKnotBufferGeometry':
  24631. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24632. break;
  24633. case 'TubeGeometry':
  24634. case 'TubeBufferGeometry':
  24635. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24636. // User defined curves or instances of CurvePath will not be deserialized.
  24637. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24638. break;
  24639. case 'LatheGeometry':
  24640. case 'LatheBufferGeometry':
  24641. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24642. break;
  24643. case 'PolyhedronGeometry':
  24644. case 'PolyhedronBufferGeometry':
  24645. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24646. break;
  24647. case 'ShapeGeometry':
  24648. case 'ShapeBufferGeometry':
  24649. geometryShapes = [];
  24650. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  24651. const shape = shapes[data.shapes[j]];
  24652. geometryShapes.push(shape);
  24653. }
  24654. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24655. break;
  24656. case 'ExtrudeGeometry':
  24657. case 'ExtrudeBufferGeometry':
  24658. geometryShapes = [];
  24659. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  24660. const shape = shapes[data.shapes[j]];
  24661. geometryShapes.push(shape);
  24662. }
  24663. const extrudePath = data.options.extrudePath;
  24664. if (extrudePath !== undefined) {
  24665. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24666. }
  24667. geometry = new Geometries[data.type](geometryShapes, data.options);
  24668. break;
  24669. case 'BufferGeometry':
  24670. case 'InstancedBufferGeometry':
  24671. geometry = bufferGeometryLoader.parse(data);
  24672. break;
  24673. case 'Geometry':
  24674. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  24675. break;
  24676. default:
  24677. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24678. continue;
  24679. }
  24680. geometry.uuid = data.uuid;
  24681. if (data.name !== undefined) geometry.name = data.name;
  24682. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24683. geometries[data.uuid] = geometry;
  24684. }
  24685. }
  24686. return geometries;
  24687. }
  24688. parseMaterials(json, textures) {
  24689. const cache = {}; // MultiMaterial
  24690. const materials = {};
  24691. if (json !== undefined) {
  24692. const loader = new MaterialLoader();
  24693. loader.setTextures(textures);
  24694. for (let i = 0, l = json.length; i < l; i++) {
  24695. const data = json[i];
  24696. if (data.type === 'MultiMaterial') {
  24697. // Deprecated
  24698. const array = [];
  24699. for (let j = 0; j < data.materials.length; j++) {
  24700. const material = data.materials[j];
  24701. if (cache[material.uuid] === undefined) {
  24702. cache[material.uuid] = loader.parse(material);
  24703. }
  24704. array.push(cache[material.uuid]);
  24705. }
  24706. materials[data.uuid] = array;
  24707. } else {
  24708. if (cache[data.uuid] === undefined) {
  24709. cache[data.uuid] = loader.parse(data);
  24710. }
  24711. materials[data.uuid] = cache[data.uuid];
  24712. }
  24713. }
  24714. }
  24715. return materials;
  24716. }
  24717. parseAnimations(json) {
  24718. const animations = {};
  24719. if (json !== undefined) {
  24720. for (let i = 0; i < json.length; i++) {
  24721. const data = json[i];
  24722. const clip = AnimationClip.parse(data);
  24723. animations[clip.uuid] = clip;
  24724. }
  24725. }
  24726. return animations;
  24727. }
  24728. parseImages(json, onLoad) {
  24729. const scope = this;
  24730. const images = {};
  24731. let loader;
  24732. function loadImage(url) {
  24733. scope.manager.itemStart(url);
  24734. return loader.load(url, function () {
  24735. scope.manager.itemEnd(url);
  24736. }, undefined, function () {
  24737. scope.manager.itemError(url);
  24738. scope.manager.itemEnd(url);
  24739. });
  24740. }
  24741. function deserializeImage(image) {
  24742. if (typeof image === 'string') {
  24743. const url = image;
  24744. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24745. return loadImage(path);
  24746. } else {
  24747. if (image.data) {
  24748. return {
  24749. data: getTypedArray(image.type, image.data),
  24750. width: image.width,
  24751. height: image.height
  24752. };
  24753. } else {
  24754. return null;
  24755. }
  24756. }
  24757. }
  24758. if (json !== undefined && json.length > 0) {
  24759. const manager = new LoadingManager(onLoad);
  24760. loader = new ImageLoader(manager);
  24761. loader.setCrossOrigin(this.crossOrigin);
  24762. for (let i = 0, il = json.length; i < il; i++) {
  24763. const image = json[i];
  24764. const url = image.url;
  24765. if (Array.isArray(url)) {
  24766. // load array of images e.g CubeTexture
  24767. images[image.uuid] = [];
  24768. for (let j = 0, jl = url.length; j < jl; j++) {
  24769. const currentUrl = url[j];
  24770. const deserializedImage = deserializeImage(currentUrl);
  24771. if (deserializedImage !== null) {
  24772. if (deserializedImage instanceof HTMLImageElement) {
  24773. images[image.uuid].push(deserializedImage);
  24774. } else {
  24775. // special case: handle array of data textures for cube textures
  24776. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24777. }
  24778. }
  24779. }
  24780. } else {
  24781. // load single image
  24782. const deserializedImage = deserializeImage(image.url);
  24783. if (deserializedImage !== null) {
  24784. images[image.uuid] = deserializedImage;
  24785. }
  24786. }
  24787. }
  24788. }
  24789. return images;
  24790. }
  24791. parseTextures(json, images) {
  24792. function parseConstant(value, type) {
  24793. if (typeof value === 'number') return value;
  24794. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24795. return type[value];
  24796. }
  24797. const textures = {};
  24798. if (json !== undefined) {
  24799. for (let i = 0, l = json.length; i < l; i++) {
  24800. const data = json[i];
  24801. if (data.image === undefined) {
  24802. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24803. }
  24804. if (images[data.image] === undefined) {
  24805. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24806. }
  24807. let texture;
  24808. const image = images[data.image];
  24809. if (Array.isArray(image)) {
  24810. texture = new CubeTexture(image);
  24811. if (image.length === 6) texture.needsUpdate = true;
  24812. } else {
  24813. if (image && image.data) {
  24814. texture = new DataTexture(image.data, image.width, image.height);
  24815. } else {
  24816. texture = new Texture(image);
  24817. }
  24818. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24819. }
  24820. texture.uuid = data.uuid;
  24821. if (data.name !== undefined) texture.name = data.name;
  24822. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24823. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24824. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24825. if (data.center !== undefined) texture.center.fromArray(data.center);
  24826. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24827. if (data.wrap !== undefined) {
  24828. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24829. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24830. }
  24831. if (data.format !== undefined) texture.format = data.format;
  24832. if (data.type !== undefined) texture.type = data.type;
  24833. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24834. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24835. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24836. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24837. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24838. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24839. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24840. textures[data.uuid] = texture;
  24841. }
  24842. }
  24843. return textures;
  24844. }
  24845. parseObject(data, geometries, materials, animations) {
  24846. let object;
  24847. function getGeometry(name) {
  24848. if (geometries[name] === undefined) {
  24849. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24850. }
  24851. return geometries[name];
  24852. }
  24853. function getMaterial(name) {
  24854. if (name === undefined) return undefined;
  24855. if (Array.isArray(name)) {
  24856. const array = [];
  24857. for (let i = 0, l = name.length; i < l; i++) {
  24858. const uuid = name[i];
  24859. if (materials[uuid] === undefined) {
  24860. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24861. }
  24862. array.push(materials[uuid]);
  24863. }
  24864. return array;
  24865. }
  24866. if (materials[name] === undefined) {
  24867. console.warn('THREE.ObjectLoader: Undefined material', name);
  24868. }
  24869. return materials[name];
  24870. }
  24871. let geometry, material;
  24872. switch (data.type) {
  24873. case 'Scene':
  24874. object = new Scene();
  24875. if (data.background !== undefined) {
  24876. if (Number.isInteger(data.background)) {
  24877. object.background = new Color(data.background);
  24878. }
  24879. }
  24880. if (data.fog !== undefined) {
  24881. if (data.fog.type === 'Fog') {
  24882. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24883. } else if (data.fog.type === 'FogExp2') {
  24884. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24885. }
  24886. }
  24887. break;
  24888. case 'PerspectiveCamera':
  24889. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24890. if (data.focus !== undefined) object.focus = data.focus;
  24891. if (data.zoom !== undefined) object.zoom = data.zoom;
  24892. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24893. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24894. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24895. break;
  24896. case 'OrthographicCamera':
  24897. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24898. if (data.zoom !== undefined) object.zoom = data.zoom;
  24899. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24900. break;
  24901. case 'AmbientLight':
  24902. object = new AmbientLight(data.color, data.intensity);
  24903. break;
  24904. case 'DirectionalLight':
  24905. object = new DirectionalLight(data.color, data.intensity);
  24906. break;
  24907. case 'PointLight':
  24908. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24909. break;
  24910. case 'RectAreaLight':
  24911. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24912. break;
  24913. case 'SpotLight':
  24914. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24915. break;
  24916. case 'HemisphereLight':
  24917. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24918. break;
  24919. case 'LightProbe':
  24920. object = new LightProbe().fromJSON(data);
  24921. break;
  24922. case 'SkinnedMesh':
  24923. geometry = getGeometry(data.geometry);
  24924. material = getMaterial(data.material);
  24925. object = new SkinnedMesh(geometry, material);
  24926. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24927. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24928. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24929. break;
  24930. case 'Mesh':
  24931. geometry = getGeometry(data.geometry);
  24932. material = getMaterial(data.material);
  24933. object = new Mesh(geometry, material);
  24934. break;
  24935. case 'InstancedMesh':
  24936. geometry = getGeometry(data.geometry);
  24937. material = getMaterial(data.material);
  24938. const count = data.count;
  24939. const instanceMatrix = data.instanceMatrix;
  24940. object = new InstancedMesh(geometry, material, count);
  24941. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24942. break;
  24943. case 'LOD':
  24944. object = new LOD();
  24945. break;
  24946. case 'Line':
  24947. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  24948. break;
  24949. case 'LineLoop':
  24950. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24951. break;
  24952. case 'LineSegments':
  24953. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24954. break;
  24955. case 'PointCloud':
  24956. case 'Points':
  24957. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24958. break;
  24959. case 'Sprite':
  24960. object = new Sprite(getMaterial(data.material));
  24961. break;
  24962. case 'Group':
  24963. object = new Group();
  24964. break;
  24965. case 'Bone':
  24966. object = new Bone();
  24967. break;
  24968. default:
  24969. object = new Object3D();
  24970. }
  24971. object.uuid = data.uuid;
  24972. if (data.name !== undefined) object.name = data.name;
  24973. if (data.matrix !== undefined) {
  24974. object.matrix.fromArray(data.matrix);
  24975. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24976. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24977. } else {
  24978. if (data.position !== undefined) object.position.fromArray(data.position);
  24979. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24980. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24981. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24982. }
  24983. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24984. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24985. if (data.shadow) {
  24986. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24987. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24988. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24989. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24990. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24991. }
  24992. if (data.visible !== undefined) object.visible = data.visible;
  24993. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24994. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24995. if (data.userData !== undefined) object.userData = data.userData;
  24996. if (data.layers !== undefined) object.layers.mask = data.layers;
  24997. if (data.children !== undefined) {
  24998. const children = data.children;
  24999. for (let i = 0; i < children.length; i++) {
  25000. object.add(this.parseObject(children[i], geometries, materials, animations));
  25001. }
  25002. }
  25003. if (data.animations !== undefined) {
  25004. const objectAnimations = data.animations;
  25005. for (let i = 0; i < objectAnimations.length; i++) {
  25006. const uuid = objectAnimations[i];
  25007. object.animations.push(animations[uuid]);
  25008. }
  25009. }
  25010. if (data.type === 'LOD') {
  25011. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  25012. const levels = data.levels;
  25013. for (let l = 0; l < levels.length; l++) {
  25014. const level = levels[l];
  25015. const child = object.getObjectByProperty('uuid', level.object);
  25016. if (child !== undefined) {
  25017. object.addLevel(child, level.distance);
  25018. }
  25019. }
  25020. }
  25021. return object;
  25022. }
  25023. bindSkeletons(object, skeletons) {
  25024. if (Object.keys(skeletons).length === 0) return;
  25025. object.traverse(function (child) {
  25026. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  25027. const skeleton = skeletons[child.skeleton];
  25028. if (skeleton === undefined) {
  25029. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  25030. } else {
  25031. child.bind(skeleton, child.bindMatrix);
  25032. }
  25033. }
  25034. });
  25035. }
  25036. /* DEPRECATED */
  25037. setTexturePath(value) {
  25038. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  25039. return this.setResourcePath(value);
  25040. }
  25041. }
  25042. exports.ObjectLoader = ObjectLoader;
  25043. const TEXTURE_MAPPING = {
  25044. UVMapping: UVMapping,
  25045. CubeReflectionMapping: CubeReflectionMapping,
  25046. CubeRefractionMapping: CubeRefractionMapping,
  25047. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25048. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25049. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25050. CubeUVRefractionMapping: CubeUVRefractionMapping
  25051. };
  25052. const TEXTURE_WRAPPING = {
  25053. RepeatWrapping: RepeatWrapping,
  25054. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25055. MirroredRepeatWrapping: MirroredRepeatWrapping
  25056. };
  25057. const TEXTURE_FILTER = {
  25058. NearestFilter: NearestFilter,
  25059. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25060. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25061. LinearFilter: LinearFilter,
  25062. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25063. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25064. };
  25065. function ImageBitmapLoader(manager) {
  25066. if (typeof createImageBitmap === 'undefined') {
  25067. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25068. }
  25069. if (typeof fetch === 'undefined') {
  25070. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25071. }
  25072. Loader.call(this, manager);
  25073. this.options = {
  25074. premultiplyAlpha: 'none'
  25075. };
  25076. }
  25077. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25078. constructor: ImageBitmapLoader,
  25079. isImageBitmapLoader: true,
  25080. setOptions: function setOptions(options) {
  25081. this.options = options;
  25082. return this;
  25083. },
  25084. load: function (url, onLoad, onProgress, onError) {
  25085. if (url === undefined) url = '';
  25086. if (this.path !== undefined) url = this.path + url;
  25087. url = this.manager.resolveURL(url);
  25088. const scope = this;
  25089. const cached = Cache.get(url);
  25090. if (cached !== undefined) {
  25091. scope.manager.itemStart(url);
  25092. setTimeout(function () {
  25093. if (onLoad) onLoad(cached);
  25094. scope.manager.itemEnd(url);
  25095. }, 0);
  25096. return cached;
  25097. }
  25098. const fetchOptions = {};
  25099. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25100. fetch(url, fetchOptions).then(function (res) {
  25101. return res.blob();
  25102. }).then(function (blob) {
  25103. return createImageBitmap(blob, scope.options);
  25104. }).then(function (imageBitmap) {
  25105. Cache.add(url, imageBitmap);
  25106. if (onLoad) onLoad(imageBitmap);
  25107. scope.manager.itemEnd(url);
  25108. }).catch(function (e) {
  25109. if (onError) onError(e);
  25110. scope.manager.itemError(url);
  25111. scope.manager.itemEnd(url);
  25112. });
  25113. scope.manager.itemStart(url);
  25114. }
  25115. });
  25116. function ShapePath() {
  25117. this.type = 'ShapePath';
  25118. this.color = new Color();
  25119. this.subPaths = [];
  25120. this.currentPath = null;
  25121. }
  25122. Object.assign(ShapePath.prototype, {
  25123. moveTo: function (x, y) {
  25124. this.currentPath = new Path();
  25125. this.subPaths.push(this.currentPath);
  25126. this.currentPath.moveTo(x, y);
  25127. return this;
  25128. },
  25129. lineTo: function (x, y) {
  25130. this.currentPath.lineTo(x, y);
  25131. return this;
  25132. },
  25133. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25134. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25135. return this;
  25136. },
  25137. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25138. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25139. return this;
  25140. },
  25141. splineThru: function (pts) {
  25142. this.currentPath.splineThru(pts);
  25143. return this;
  25144. },
  25145. toShapes: function (isCCW, noHoles) {
  25146. function toShapesNoHoles(inSubpaths) {
  25147. const shapes = [];
  25148. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  25149. const tmpPath = inSubpaths[i];
  25150. const tmpShape = new Shape();
  25151. tmpShape.curves = tmpPath.curves;
  25152. shapes.push(tmpShape);
  25153. }
  25154. return shapes;
  25155. }
  25156. function isPointInsidePolygon(inPt, inPolygon) {
  25157. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25158. // toggling of inside/outside at every single! intersection point of an edge
  25159. // with the horizontal line through inPt, left of inPt
  25160. // not counting lowerY endpoints of edges and whole edges on that line
  25161. let inside = false;
  25162. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25163. let edgeLowPt = inPolygon[p];
  25164. let edgeHighPt = inPolygon[q];
  25165. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25166. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25167. if (Math.abs(edgeDy) > Number.EPSILON) {
  25168. // not parallel
  25169. if (edgeDy < 0) {
  25170. edgeLowPt = inPolygon[q];
  25171. edgeDx = -edgeDx;
  25172. edgeHighPt = inPolygon[p];
  25173. edgeDy = -edgeDy;
  25174. }
  25175. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25176. if (inPt.y === edgeLowPt.y) {
  25177. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25178. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25179. } else {
  25180. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25181. if (perpEdge === 0) return true; // inPt is on contour ?
  25182. if (perpEdge < 0) continue;
  25183. inside = !inside; // true intersection left of inPt
  25184. }
  25185. } else {
  25186. // parallel or collinear
  25187. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25188. // edge lies on the same horizontal line as inPt
  25189. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25190. // continue;
  25191. }
  25192. }
  25193. return inside;
  25194. }
  25195. const isClockWise = ShapeUtils.isClockWise;
  25196. const subPaths = this.subPaths;
  25197. if (subPaths.length === 0) return [];
  25198. if (noHoles === true) return toShapesNoHoles(subPaths);
  25199. let solid, tmpPath, tmpShape;
  25200. const shapes = [];
  25201. if (subPaths.length === 1) {
  25202. tmpPath = subPaths[0];
  25203. tmpShape = new Shape();
  25204. tmpShape.curves = tmpPath.curves;
  25205. shapes.push(tmpShape);
  25206. return shapes;
  25207. }
  25208. let holesFirst = !isClockWise(subPaths[0].getPoints());
  25209. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25210. const betterShapeHoles = [];
  25211. const newShapes = [];
  25212. let newShapeHoles = [];
  25213. let mainIdx = 0;
  25214. let tmpPoints;
  25215. newShapes[mainIdx] = undefined;
  25216. newShapeHoles[mainIdx] = [];
  25217. for (let i = 0, l = subPaths.length; i < l; i++) {
  25218. tmpPath = subPaths[i];
  25219. tmpPoints = tmpPath.getPoints();
  25220. solid = isClockWise(tmpPoints);
  25221. solid = isCCW ? !solid : solid;
  25222. if (solid) {
  25223. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25224. newShapes[mainIdx] = {
  25225. s: new Shape(),
  25226. p: tmpPoints
  25227. };
  25228. newShapes[mainIdx].s.curves = tmpPath.curves;
  25229. if (holesFirst) mainIdx++;
  25230. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25231. } else {
  25232. newShapeHoles[mainIdx].push({
  25233. h: tmpPath,
  25234. p: tmpPoints[0]
  25235. }); //console.log('ccw', i);
  25236. }
  25237. } // only Holes? -> probably all Shapes with wrong orientation
  25238. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25239. if (newShapes.length > 1) {
  25240. let ambiguous = false;
  25241. const toChange = [];
  25242. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25243. betterShapeHoles[sIdx] = [];
  25244. }
  25245. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25246. const sho = newShapeHoles[sIdx];
  25247. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  25248. const ho = sho[hIdx];
  25249. let hole_unassigned = true;
  25250. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25251. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25252. if (sIdx !== s2Idx) toChange.push({
  25253. froms: sIdx,
  25254. tos: s2Idx,
  25255. hole: hIdx
  25256. });
  25257. if (hole_unassigned) {
  25258. hole_unassigned = false;
  25259. betterShapeHoles[s2Idx].push(ho);
  25260. } else {
  25261. ambiguous = true;
  25262. }
  25263. }
  25264. }
  25265. if (hole_unassigned) {
  25266. betterShapeHoles[sIdx].push(ho);
  25267. }
  25268. }
  25269. } // console.log("ambiguous: ", ambiguous);
  25270. if (toChange.length > 0) {
  25271. // console.log("to change: ", toChange);
  25272. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25273. }
  25274. }
  25275. let tmpHoles;
  25276. for (let i = 0, il = newShapes.length; i < il; i++) {
  25277. tmpShape = newShapes[i].s;
  25278. shapes.push(tmpShape);
  25279. tmpHoles = newShapeHoles[i];
  25280. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  25281. tmpShape.holes.push(tmpHoles[j].h);
  25282. }
  25283. } //console.log("shape", shapes);
  25284. return shapes;
  25285. }
  25286. });
  25287. function Font(data) {
  25288. this.type = 'Font';
  25289. this.data = data;
  25290. }
  25291. Object.assign(Font.prototype, {
  25292. isFont: true,
  25293. generateShapes: function (text, size = 100) {
  25294. const shapes = [];
  25295. const paths = createPaths(text, size, this.data);
  25296. for (let p = 0, pl = paths.length; p < pl; p++) {
  25297. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25298. }
  25299. return shapes;
  25300. }
  25301. });
  25302. function createPaths(text, size, data) {
  25303. const chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  25304. const scale = size / data.resolution;
  25305. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25306. const paths = [];
  25307. let offsetX = 0,
  25308. offsetY = 0;
  25309. for (let i = 0; i < chars.length; i++) {
  25310. const char = chars[i];
  25311. if (char === '\n') {
  25312. offsetX = 0;
  25313. offsetY -= line_height;
  25314. } else {
  25315. const ret = createPath(char, scale, offsetX, offsetY, data);
  25316. offsetX += ret.offsetX;
  25317. paths.push(ret.path);
  25318. }
  25319. }
  25320. return paths;
  25321. }
  25322. function createPath(char, scale, offsetX, offsetY, data) {
  25323. const glyph = data.glyphs[char] || data.glyphs['?'];
  25324. if (!glyph) {
  25325. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25326. return;
  25327. }
  25328. const path = new ShapePath();
  25329. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25330. if (glyph.o) {
  25331. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25332. for (let i = 0, l = outline.length; i < l;) {
  25333. const action = outline[i++];
  25334. switch (action) {
  25335. case 'm':
  25336. // moveTo
  25337. x = outline[i++] * scale + offsetX;
  25338. y = outline[i++] * scale + offsetY;
  25339. path.moveTo(x, y);
  25340. break;
  25341. case 'l':
  25342. // lineTo
  25343. x = outline[i++] * scale + offsetX;
  25344. y = outline[i++] * scale + offsetY;
  25345. path.lineTo(x, y);
  25346. break;
  25347. case 'q':
  25348. // quadraticCurveTo
  25349. cpx = outline[i++] * scale + offsetX;
  25350. cpy = outline[i++] * scale + offsetY;
  25351. cpx1 = outline[i++] * scale + offsetX;
  25352. cpy1 = outline[i++] * scale + offsetY;
  25353. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25354. break;
  25355. case 'b':
  25356. // bezierCurveTo
  25357. cpx = outline[i++] * scale + offsetX;
  25358. cpy = outline[i++] * scale + offsetY;
  25359. cpx1 = outline[i++] * scale + offsetX;
  25360. cpy1 = outline[i++] * scale + offsetY;
  25361. cpx2 = outline[i++] * scale + offsetX;
  25362. cpy2 = outline[i++] * scale + offsetY;
  25363. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25364. break;
  25365. }
  25366. }
  25367. }
  25368. return {
  25369. offsetX: glyph.ha * scale,
  25370. path: path
  25371. };
  25372. }
  25373. function FontLoader(manager) {
  25374. Loader.call(this, manager);
  25375. }
  25376. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25377. constructor: FontLoader,
  25378. load: function (url, onLoad, onProgress, onError) {
  25379. const scope = this;
  25380. const loader = new FileLoader(this.manager);
  25381. loader.setPath(this.path);
  25382. loader.setRequestHeader(this.requestHeader);
  25383. loader.setWithCredentials(scope.withCredentials);
  25384. loader.load(url, function (text) {
  25385. let json;
  25386. try {
  25387. json = JSON.parse(text);
  25388. } catch (e) {
  25389. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25390. json = JSON.parse(text.substring(65, text.length - 2));
  25391. }
  25392. const font = scope.parse(json);
  25393. if (onLoad) onLoad(font);
  25394. }, onProgress, onError);
  25395. },
  25396. parse: function (json) {
  25397. return new Font(json);
  25398. }
  25399. });
  25400. let _context;
  25401. const AudioContext = {
  25402. getContext: function () {
  25403. if (_context === undefined) {
  25404. _context = new (window.AudioContext || window.webkitAudioContext)();
  25405. }
  25406. return _context;
  25407. },
  25408. setContext: function (value) {
  25409. _context = value;
  25410. }
  25411. };
  25412. exports.AudioContext = AudioContext;
  25413. function AudioLoader(manager) {
  25414. Loader.call(this, manager);
  25415. }
  25416. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25417. constructor: AudioLoader,
  25418. load: function (url, onLoad, onProgress, onError) {
  25419. const scope = this;
  25420. const loader = new FileLoader(scope.manager);
  25421. loader.setResponseType('arraybuffer');
  25422. loader.setPath(scope.path);
  25423. loader.setRequestHeader(scope.requestHeader);
  25424. loader.setWithCredentials(scope.withCredentials);
  25425. loader.load(url, function (buffer) {
  25426. try {
  25427. // Create a copy of the buffer. The `decodeAudioData` method
  25428. // detaches the buffer when complete, preventing reuse.
  25429. const bufferCopy = buffer.slice(0);
  25430. const context = AudioContext.getContext();
  25431. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25432. onLoad(audioBuffer);
  25433. });
  25434. } catch (e) {
  25435. if (onError) {
  25436. onError(e);
  25437. } else {
  25438. console.error(e);
  25439. }
  25440. scope.manager.itemError(url);
  25441. }
  25442. }, onProgress, onError);
  25443. }
  25444. });
  25445. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25446. LightProbe.call(this, undefined, intensity);
  25447. const color1 = new Color().set(skyColor);
  25448. const color2 = new Color().set(groundColor);
  25449. const sky = new Vector3(color1.r, color1.g, color1.b);
  25450. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25451. const c0 = Math.sqrt(Math.PI);
  25452. const c1 = c0 * Math.sqrt(0.75);
  25453. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25454. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25455. }
  25456. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25457. constructor: HemisphereLightProbe,
  25458. isHemisphereLightProbe: true,
  25459. copy: function (source) {
  25460. // modifying colors not currently supported
  25461. LightProbe.prototype.copy.call(this, source);
  25462. return this;
  25463. },
  25464. toJSON: function (meta) {
  25465. const data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25466. return data;
  25467. }
  25468. });
  25469. function AmbientLightProbe(color, intensity) {
  25470. LightProbe.call(this, undefined, intensity);
  25471. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25472. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25473. }
  25474. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25475. constructor: AmbientLightProbe,
  25476. isAmbientLightProbe: true,
  25477. copy: function (source) {
  25478. // modifying color not currently supported
  25479. LightProbe.prototype.copy.call(this, source);
  25480. return this;
  25481. },
  25482. toJSON: function (meta) {
  25483. const data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25484. return data;
  25485. }
  25486. });
  25487. const _eyeRight = new Matrix4();
  25488. const _eyeLeft = new Matrix4();
  25489. function StereoCamera() {
  25490. this.type = 'StereoCamera';
  25491. this.aspect = 1;
  25492. this.eyeSep = 0.064;
  25493. this.cameraL = new PerspectiveCamera();
  25494. this.cameraL.layers.enable(1);
  25495. this.cameraL.matrixAutoUpdate = false;
  25496. this.cameraR = new PerspectiveCamera();
  25497. this.cameraR.layers.enable(2);
  25498. this.cameraR.matrixAutoUpdate = false;
  25499. this._cache = {
  25500. focus: null,
  25501. fov: null,
  25502. aspect: null,
  25503. near: null,
  25504. far: null,
  25505. zoom: null,
  25506. eyeSep: null
  25507. };
  25508. }
  25509. Object.assign(StereoCamera.prototype, {
  25510. update: function (camera) {
  25511. const cache = this._cache;
  25512. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25513. if (needsUpdate) {
  25514. cache.focus = camera.focus;
  25515. cache.fov = camera.fov;
  25516. cache.aspect = camera.aspect * this.aspect;
  25517. cache.near = camera.near;
  25518. cache.far = camera.far;
  25519. cache.zoom = camera.zoom;
  25520. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25521. // http://paulbourke.net/stereographics/stereorender/
  25522. const projectionMatrix = camera.projectionMatrix.clone();
  25523. const eyeSepHalf = cache.eyeSep / 2;
  25524. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25525. const ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25526. let xmin, xmax; // translate xOffset
  25527. _eyeLeft.elements[12] = -eyeSepHalf;
  25528. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25529. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25530. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25531. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25532. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25533. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25534. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25535. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25536. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25537. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25538. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25539. }
  25540. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25541. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25542. }
  25543. });
  25544. class Clock {
  25545. constructor(autoStart) {
  25546. this.autoStart = autoStart !== undefined ? autoStart : true;
  25547. this.startTime = 0;
  25548. this.oldTime = 0;
  25549. this.elapsedTime = 0;
  25550. this.running = false;
  25551. }
  25552. start() {
  25553. this.startTime = now();
  25554. this.oldTime = this.startTime;
  25555. this.elapsedTime = 0;
  25556. this.running = true;
  25557. }
  25558. stop() {
  25559. this.getElapsedTime();
  25560. this.running = false;
  25561. this.autoStart = false;
  25562. }
  25563. getElapsedTime() {
  25564. this.getDelta();
  25565. return this.elapsedTime;
  25566. }
  25567. getDelta() {
  25568. let diff = 0;
  25569. if (this.autoStart && !this.running) {
  25570. this.start();
  25571. return 0;
  25572. }
  25573. if (this.running) {
  25574. const newTime = now();
  25575. diff = (newTime - this.oldTime) / 1000;
  25576. this.oldTime = newTime;
  25577. this.elapsedTime += diff;
  25578. }
  25579. return diff;
  25580. }
  25581. }
  25582. exports.Clock = Clock;
  25583. function now() {
  25584. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25585. }
  25586. const _position$2 =
  25587. /*@__PURE__*/
  25588. new Vector3();
  25589. const _quaternion$3 =
  25590. /*@__PURE__*/
  25591. new Quaternion();
  25592. const _scale$1 =
  25593. /*@__PURE__*/
  25594. new Vector3();
  25595. const _orientation =
  25596. /*@__PURE__*/
  25597. new Vector3();
  25598. class AudioListener extends Object3D {
  25599. constructor() {
  25600. super();
  25601. this.type = 'AudioListener';
  25602. this.context = AudioContext.getContext();
  25603. this.gain = this.context.createGain();
  25604. this.gain.connect(this.context.destination);
  25605. this.filter = null;
  25606. this.timeDelta = 0; // private
  25607. this._clock = new Clock();
  25608. }
  25609. getInput() {
  25610. return this.gain;
  25611. }
  25612. removeFilter() {
  25613. if (this.filter !== null) {
  25614. this.gain.disconnect(this.filter);
  25615. this.filter.disconnect(this.context.destination);
  25616. this.gain.connect(this.context.destination);
  25617. this.filter = null;
  25618. }
  25619. return this;
  25620. }
  25621. getFilter() {
  25622. return this.filter;
  25623. }
  25624. setFilter(value) {
  25625. if (this.filter !== null) {
  25626. this.gain.disconnect(this.filter);
  25627. this.filter.disconnect(this.context.destination);
  25628. } else {
  25629. this.gain.disconnect(this.context.destination);
  25630. }
  25631. this.filter = value;
  25632. this.gain.connect(this.filter);
  25633. this.filter.connect(this.context.destination);
  25634. return this;
  25635. }
  25636. getMasterVolume() {
  25637. return this.gain.gain.value;
  25638. }
  25639. setMasterVolume(value) {
  25640. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25641. return this;
  25642. }
  25643. updateMatrixWorld(force) {
  25644. super.updateMatrixWorld(force);
  25645. const listener = this.context.listener;
  25646. const up = this.up;
  25647. this.timeDelta = this._clock.getDelta();
  25648. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25649. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25650. if (listener.positionX) {
  25651. // code path for Chrome (see #14393)
  25652. const endTime = this.context.currentTime + this.timeDelta;
  25653. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25654. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25655. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25656. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25657. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25658. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25659. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25660. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25661. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25662. } else {
  25663. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25664. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25665. }
  25666. }
  25667. }
  25668. exports.AudioListener = AudioListener;
  25669. class Audio extends Object3D {
  25670. constructor(listener) {
  25671. super();
  25672. this.type = 'Audio';
  25673. this.listener = listener;
  25674. this.context = listener.context;
  25675. this.gain = this.context.createGain();
  25676. this.gain.connect(listener.getInput());
  25677. this.autoplay = false;
  25678. this.buffer = null;
  25679. this.detune = 0;
  25680. this.loop = false;
  25681. this.loopStart = 0;
  25682. this.loopEnd = 0;
  25683. this.offset = 0;
  25684. this.duration = undefined;
  25685. this.playbackRate = 1;
  25686. this.isPlaying = false;
  25687. this.hasPlaybackControl = true;
  25688. this.source = null;
  25689. this.sourceType = 'empty';
  25690. this._startedAt = 0;
  25691. this._progress = 0;
  25692. this._connected = false;
  25693. this.filters = [];
  25694. }
  25695. getOutput() {
  25696. return this.gain;
  25697. }
  25698. setNodeSource(audioNode) {
  25699. this.hasPlaybackControl = false;
  25700. this.sourceType = 'audioNode';
  25701. this.source = audioNode;
  25702. this.connect();
  25703. return this;
  25704. }
  25705. setMediaElementSource(mediaElement) {
  25706. this.hasPlaybackControl = false;
  25707. this.sourceType = 'mediaNode';
  25708. this.source = this.context.createMediaElementSource(mediaElement);
  25709. this.connect();
  25710. return this;
  25711. }
  25712. setMediaStreamSource(mediaStream) {
  25713. this.hasPlaybackControl = false;
  25714. this.sourceType = 'mediaStreamNode';
  25715. this.source = this.context.createMediaStreamSource(mediaStream);
  25716. this.connect();
  25717. return this;
  25718. }
  25719. setBuffer(audioBuffer) {
  25720. this.buffer = audioBuffer;
  25721. this.sourceType = 'buffer';
  25722. if (this.autoplay) this.play();
  25723. return this;
  25724. }
  25725. play(delay = 0) {
  25726. if (this.isPlaying === true) {
  25727. console.warn('THREE.Audio: Audio is already playing.');
  25728. return;
  25729. }
  25730. if (this.hasPlaybackControl === false) {
  25731. console.warn('THREE.Audio: this Audio has no playback control.');
  25732. return;
  25733. }
  25734. this._startedAt = this.context.currentTime + delay;
  25735. const source = this.context.createBufferSource();
  25736. source.buffer = this.buffer;
  25737. source.loop = this.loop;
  25738. source.loopStart = this.loopStart;
  25739. source.loopEnd = this.loopEnd;
  25740. source.onended = this.onEnded.bind(this);
  25741. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25742. this.isPlaying = true;
  25743. this.source = source;
  25744. this.setDetune(this.detune);
  25745. this.setPlaybackRate(this.playbackRate);
  25746. return this.connect();
  25747. }
  25748. pause() {
  25749. if (this.hasPlaybackControl === false) {
  25750. console.warn('THREE.Audio: this Audio has no playback control.');
  25751. return;
  25752. }
  25753. if (this.isPlaying === true) {
  25754. // update current progress
  25755. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25756. if (this.loop === true) {
  25757. // ensure _progress does not exceed duration with looped audios
  25758. this._progress = this._progress % (this.duration || this.buffer.duration);
  25759. }
  25760. this.source.stop();
  25761. this.source.onended = null;
  25762. this.isPlaying = false;
  25763. }
  25764. return this;
  25765. }
  25766. stop() {
  25767. if (this.hasPlaybackControl === false) {
  25768. console.warn('THREE.Audio: this Audio has no playback control.');
  25769. return;
  25770. }
  25771. this._progress = 0;
  25772. this.source.stop();
  25773. this.source.onended = null;
  25774. this.isPlaying = false;
  25775. return this;
  25776. }
  25777. connect() {
  25778. if (this.filters.length > 0) {
  25779. this.source.connect(this.filters[0]);
  25780. for (let i = 1, l = this.filters.length; i < l; i++) {
  25781. this.filters[i - 1].connect(this.filters[i]);
  25782. }
  25783. this.filters[this.filters.length - 1].connect(this.getOutput());
  25784. } else {
  25785. this.source.connect(this.getOutput());
  25786. }
  25787. this._connected = true;
  25788. return this;
  25789. }
  25790. disconnect() {
  25791. if (this.filters.length > 0) {
  25792. this.source.disconnect(this.filters[0]);
  25793. for (let i = 1, l = this.filters.length; i < l; i++) {
  25794. this.filters[i - 1].disconnect(this.filters[i]);
  25795. }
  25796. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25797. } else {
  25798. this.source.disconnect(this.getOutput());
  25799. }
  25800. this._connected = false;
  25801. return this;
  25802. }
  25803. getFilters() {
  25804. return this.filters;
  25805. }
  25806. setFilters(value) {
  25807. if (!value) value = [];
  25808. if (this._connected === true) {
  25809. this.disconnect();
  25810. this.filters = value.slice();
  25811. this.connect();
  25812. } else {
  25813. this.filters = value.slice();
  25814. }
  25815. return this;
  25816. }
  25817. setDetune(value) {
  25818. this.detune = value;
  25819. if (this.source.detune === undefined) return; // only set detune when available
  25820. if (this.isPlaying === true) {
  25821. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25822. }
  25823. return this;
  25824. }
  25825. getDetune() {
  25826. return this.detune;
  25827. }
  25828. getFilter() {
  25829. return this.getFilters()[0];
  25830. }
  25831. setFilter(filter) {
  25832. return this.setFilters(filter ? [filter] : []);
  25833. }
  25834. setPlaybackRate(value) {
  25835. if (this.hasPlaybackControl === false) {
  25836. console.warn('THREE.Audio: this Audio has no playback control.');
  25837. return;
  25838. }
  25839. this.playbackRate = value;
  25840. if (this.isPlaying === true) {
  25841. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25842. }
  25843. return this;
  25844. }
  25845. getPlaybackRate() {
  25846. return this.playbackRate;
  25847. }
  25848. onEnded() {
  25849. this.isPlaying = false;
  25850. }
  25851. getLoop() {
  25852. if (this.hasPlaybackControl === false) {
  25853. console.warn('THREE.Audio: this Audio has no playback control.');
  25854. return false;
  25855. }
  25856. return this.loop;
  25857. }
  25858. setLoop(value) {
  25859. if (this.hasPlaybackControl === false) {
  25860. console.warn('THREE.Audio: this Audio has no playback control.');
  25861. return;
  25862. }
  25863. this.loop = value;
  25864. if (this.isPlaying === true) {
  25865. this.source.loop = this.loop;
  25866. }
  25867. return this;
  25868. }
  25869. setLoopStart(value) {
  25870. this.loopStart = value;
  25871. return this;
  25872. }
  25873. setLoopEnd(value) {
  25874. this.loopEnd = value;
  25875. return this;
  25876. }
  25877. getVolume() {
  25878. return this.gain.gain.value;
  25879. }
  25880. setVolume(value) {
  25881. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25882. return this;
  25883. }
  25884. }
  25885. exports.Audio = Audio;
  25886. const _position$3 =
  25887. /*@__PURE__*/
  25888. new Vector3();
  25889. const _quaternion$4 =
  25890. /*@__PURE__*/
  25891. new Quaternion();
  25892. const _scale$2 =
  25893. /*@__PURE__*/
  25894. new Vector3();
  25895. const _orientation$1 =
  25896. /*@__PURE__*/
  25897. new Vector3();
  25898. class PositionalAudio extends Audio {
  25899. constructor(listener) {
  25900. super(listener);
  25901. this.panner = this.context.createPanner();
  25902. this.panner.panningModel = 'HRTF';
  25903. this.panner.connect(this.gain);
  25904. }
  25905. getOutput() {
  25906. return this.panner;
  25907. }
  25908. getRefDistance() {
  25909. return this.panner.refDistance;
  25910. }
  25911. setRefDistance(value) {
  25912. this.panner.refDistance = value;
  25913. return this;
  25914. }
  25915. getRolloffFactor() {
  25916. return this.panner.rolloffFactor;
  25917. }
  25918. setRolloffFactor(value) {
  25919. this.panner.rolloffFactor = value;
  25920. return this;
  25921. }
  25922. getDistanceModel() {
  25923. return this.panner.distanceModel;
  25924. }
  25925. setDistanceModel(value) {
  25926. this.panner.distanceModel = value;
  25927. return this;
  25928. }
  25929. getMaxDistance() {
  25930. return this.panner.maxDistance;
  25931. }
  25932. setMaxDistance(value) {
  25933. this.panner.maxDistance = value;
  25934. return this;
  25935. }
  25936. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25937. this.panner.coneInnerAngle = coneInnerAngle;
  25938. this.panner.coneOuterAngle = coneOuterAngle;
  25939. this.panner.coneOuterGain = coneOuterGain;
  25940. return this;
  25941. }
  25942. updateMatrixWorld(force) {
  25943. super.updateMatrixWorld(force);
  25944. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25945. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25946. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25947. const panner = this.panner;
  25948. if (panner.positionX) {
  25949. // code path for Chrome and Firefox (see #14393)
  25950. const endTime = this.context.currentTime + this.listener.timeDelta;
  25951. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25952. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25953. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25954. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25955. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25956. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25957. } else {
  25958. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25959. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25960. }
  25961. }
  25962. }
  25963. exports.PositionalAudio = PositionalAudio;
  25964. class AudioAnalyser {
  25965. constructor(audio, fftSize = 2048) {
  25966. this.analyser = audio.context.createAnalyser();
  25967. this.analyser.fftSize = fftSize;
  25968. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25969. audio.getOutput().connect(this.analyser);
  25970. }
  25971. getFrequencyData() {
  25972. this.analyser.getByteFrequencyData(this.data);
  25973. return this.data;
  25974. }
  25975. getAverageFrequency() {
  25976. let value = 0;
  25977. const data = this.getFrequencyData();
  25978. for (let i = 0; i < data.length; i++) {
  25979. value += data[i];
  25980. }
  25981. return value / data.length;
  25982. }
  25983. }
  25984. exports.AudioAnalyser = AudioAnalyser;
  25985. function PropertyMixer(binding, typeName, valueSize) {
  25986. this.binding = binding;
  25987. this.valueSize = valueSize;
  25988. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25989. //
  25990. // interpolators can use .buffer as their .result
  25991. // the data then goes to 'incoming'
  25992. //
  25993. // 'accu0' and 'accu1' are used frame-interleaved for
  25994. // the cumulative result and are compared to detect
  25995. // changes
  25996. //
  25997. // 'orig' stores the original state of the property
  25998. //
  25999. // 'add' is used for additive cumulative results
  26000. //
  26001. // 'work' is optional and is only present for quaternion types. It is used
  26002. // to store intermediate quaternion multiplication results
  26003. switch (typeName) {
  26004. case 'quaternion':
  26005. mixFunction = this._slerp;
  26006. mixFunctionAdditive = this._slerpAdditive;
  26007. setIdentity = this._setAdditiveIdentityQuaternion;
  26008. this.buffer = new Float64Array(valueSize * 6);
  26009. this._workIndex = 5;
  26010. break;
  26011. case 'string':
  26012. case 'bool':
  26013. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  26014. // additive is not relevant for non-numeric types
  26015. mixFunctionAdditive = this._select;
  26016. setIdentity = this._setAdditiveIdentityOther;
  26017. this.buffer = new Array(valueSize * 5);
  26018. break;
  26019. default:
  26020. mixFunction = this._lerp;
  26021. mixFunctionAdditive = this._lerpAdditive;
  26022. setIdentity = this._setAdditiveIdentityNumeric;
  26023. this.buffer = new Float64Array(valueSize * 5);
  26024. }
  26025. this._mixBufferRegion = mixFunction;
  26026. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26027. this._setIdentity = setIdentity;
  26028. this._origIndex = 3;
  26029. this._addIndex = 4;
  26030. this.cumulativeWeight = 0;
  26031. this.cumulativeWeightAdditive = 0;
  26032. this.useCount = 0;
  26033. this.referenceCount = 0;
  26034. }
  26035. Object.assign(PropertyMixer.prototype, {
  26036. // accumulate data in the 'incoming' region into 'accu<i>'
  26037. accumulate: function (accuIndex, weight) {
  26038. // note: happily accumulating nothing when weight = 0, the caller knows
  26039. // the weight and shouldn't have made the call in the first place
  26040. const buffer = this.buffer,
  26041. stride = this.valueSize,
  26042. offset = accuIndex * stride + stride;
  26043. let currentWeight = this.cumulativeWeight;
  26044. if (currentWeight === 0) {
  26045. // accuN := incoming * weight
  26046. for (let i = 0; i !== stride; ++i) {
  26047. buffer[offset + i] = buffer[i];
  26048. }
  26049. currentWeight = weight;
  26050. } else {
  26051. // accuN := accuN + incoming * weight
  26052. currentWeight += weight;
  26053. const mix = weight / currentWeight;
  26054. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26055. }
  26056. this.cumulativeWeight = currentWeight;
  26057. },
  26058. // accumulate data in the 'incoming' region into 'add'
  26059. accumulateAdditive: function (weight) {
  26060. const buffer = this.buffer,
  26061. stride = this.valueSize,
  26062. offset = stride * this._addIndex;
  26063. if (this.cumulativeWeightAdditive === 0) {
  26064. // add = identity
  26065. this._setIdentity();
  26066. } // add := add + incoming * weight
  26067. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  26068. this.cumulativeWeightAdditive += weight;
  26069. },
  26070. // apply the state of 'accu<i>' to the binding when accus differ
  26071. apply: function (accuIndex) {
  26072. const stride = this.valueSize,
  26073. buffer = this.buffer,
  26074. offset = accuIndex * stride + stride,
  26075. weight = this.cumulativeWeight,
  26076. weightAdditive = this.cumulativeWeightAdditive,
  26077. binding = this.binding;
  26078. this.cumulativeWeight = 0;
  26079. this.cumulativeWeightAdditive = 0;
  26080. if (weight < 1) {
  26081. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26082. const originalValueOffset = stride * this._origIndex;
  26083. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26084. }
  26085. if (weightAdditive > 0) {
  26086. // accuN := accuN + additive accuN
  26087. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  26088. }
  26089. for (let i = stride, e = stride + stride; i !== e; ++i) {
  26090. if (buffer[i] !== buffer[i + stride]) {
  26091. // value has changed -> update scene graph
  26092. binding.setValue(buffer, offset);
  26093. break;
  26094. }
  26095. }
  26096. },
  26097. // remember the state of the bound property and copy it to both accus
  26098. saveOriginalState: function () {
  26099. const binding = this.binding;
  26100. const buffer = this.buffer,
  26101. stride = this.valueSize,
  26102. originalValueOffset = stride * this._origIndex;
  26103. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26104. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  26105. buffer[i] = buffer[originalValueOffset + i % stride];
  26106. } // Add to identity for additive
  26107. this._setIdentity();
  26108. this.cumulativeWeight = 0;
  26109. this.cumulativeWeightAdditive = 0;
  26110. },
  26111. // apply the state previously taken via 'saveOriginalState' to the binding
  26112. restoreOriginalState: function () {
  26113. const originalValueOffset = this.valueSize * 3;
  26114. this.binding.setValue(this.buffer, originalValueOffset);
  26115. },
  26116. _setAdditiveIdentityNumeric: function () {
  26117. const startIndex = this._addIndex * this.valueSize;
  26118. const endIndex = startIndex + this.valueSize;
  26119. for (let i = startIndex; i < endIndex; i++) {
  26120. this.buffer[i] = 0;
  26121. }
  26122. },
  26123. _setAdditiveIdentityQuaternion: function () {
  26124. this._setAdditiveIdentityNumeric();
  26125. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  26126. },
  26127. _setAdditiveIdentityOther: function () {
  26128. const startIndex = this._origIndex * this.valueSize;
  26129. const targetIndex = this._addIndex * this.valueSize;
  26130. for (let i = 0; i < this.valueSize; i++) {
  26131. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  26132. }
  26133. },
  26134. // mix functions
  26135. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26136. if (t >= 0.5) {
  26137. for (let i = 0; i !== stride; ++i) {
  26138. buffer[dstOffset + i] = buffer[srcOffset + i];
  26139. }
  26140. }
  26141. },
  26142. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26143. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26144. },
  26145. _slerpAdditive: function (buffer, dstOffset, srcOffset, t, stride) {
  26146. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  26147. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  26148. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  26149. },
  26150. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26151. const s = 1 - t;
  26152. for (let i = 0; i !== stride; ++i) {
  26153. const j = dstOffset + i;
  26154. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26155. }
  26156. },
  26157. _lerpAdditive: function (buffer, dstOffset, srcOffset, t, stride) {
  26158. for (let i = 0; i !== stride; ++i) {
  26159. const j = dstOffset + i;
  26160. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  26161. }
  26162. }
  26163. }); // Characters [].:/ are reserved for track binding syntax.
  26164. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26165. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26166. // only latin characters, and the unicode \p{L} is not yet supported. So
  26167. // instead, we exclude reserved characters and match everything else.
  26168. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26169. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26170. // be matched to parse the rest of the track name.
  26171. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26172. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26173. // characters. Accessor may contain any character except closing bracket.
  26174. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26175. // contain any non-bracket characters.
  26176. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26177. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26178. const _supportedObjectNames = ['material', 'materials', 'bones'];
  26179. function Composite(targetGroup, path, optionalParsedPath) {
  26180. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26181. this._targetGroup = targetGroup;
  26182. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26183. }
  26184. Object.assign(Composite.prototype, {
  26185. getValue: function (array, offset) {
  26186. this.bind(); // bind all binding
  26187. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26188. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26189. if (binding !== undefined) binding.getValue(array, offset);
  26190. },
  26191. setValue: function (array, offset) {
  26192. const bindings = this._bindings;
  26193. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26194. bindings[i].setValue(array, offset);
  26195. }
  26196. },
  26197. bind: function () {
  26198. const bindings = this._bindings;
  26199. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26200. bindings[i].bind();
  26201. }
  26202. },
  26203. unbind: function () {
  26204. const bindings = this._bindings;
  26205. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26206. bindings[i].unbind();
  26207. }
  26208. }
  26209. });
  26210. function PropertyBinding(rootNode, path, parsedPath) {
  26211. this.path = path;
  26212. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26213. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26214. this.rootNode = rootNode;
  26215. }
  26216. Object.assign(PropertyBinding, {
  26217. Composite: Composite,
  26218. create: function (root, path, parsedPath) {
  26219. if (!(root && root.isAnimationObjectGroup)) {
  26220. return new PropertyBinding(root, path, parsedPath);
  26221. } else {
  26222. return new PropertyBinding.Composite(root, path, parsedPath);
  26223. }
  26224. },
  26225. /**
  26226. * Replaces spaces with underscores and removes unsupported characters from
  26227. * node names, to ensure compatibility with parseTrackName().
  26228. *
  26229. * @param {string} name Node name to be sanitized.
  26230. * @return {string}
  26231. */
  26232. sanitizeNodeName: function (name) {
  26233. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26234. },
  26235. parseTrackName: function (trackName) {
  26236. const matches = _trackRe.exec(trackName);
  26237. if (!matches) {
  26238. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26239. }
  26240. const results = {
  26241. // directoryName: matches[ 1 ], // (tschw) currently unused
  26242. nodeName: matches[2],
  26243. objectName: matches[3],
  26244. objectIndex: matches[4],
  26245. propertyName: matches[5],
  26246. // required
  26247. propertyIndex: matches[6]
  26248. };
  26249. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26250. if (lastDot !== undefined && lastDot !== -1) {
  26251. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  26252. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26253. // 'bar' could be the objectName, or part of a nodeName (which can
  26254. // include '.' characters).
  26255. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26256. results.nodeName = results.nodeName.substring(0, lastDot);
  26257. results.objectName = objectName;
  26258. }
  26259. }
  26260. if (results.propertyName === null || results.propertyName.length === 0) {
  26261. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26262. }
  26263. return results;
  26264. },
  26265. findNode: function (root, nodeName) {
  26266. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26267. return root;
  26268. } // search into skeleton bones.
  26269. if (root.skeleton) {
  26270. const bone = root.skeleton.getBoneByName(nodeName);
  26271. if (bone !== undefined) {
  26272. return bone;
  26273. }
  26274. } // search into node subtree.
  26275. if (root.children) {
  26276. const searchNodeSubtree = function (children) {
  26277. for (let i = 0; i < children.length; i++) {
  26278. const childNode = children[i];
  26279. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26280. return childNode;
  26281. }
  26282. const result = searchNodeSubtree(childNode.children);
  26283. if (result) return result;
  26284. }
  26285. return null;
  26286. };
  26287. const subTreeNode = searchNodeSubtree(root.children);
  26288. if (subTreeNode) {
  26289. return subTreeNode;
  26290. }
  26291. }
  26292. return null;
  26293. }
  26294. });
  26295. Object.assign(PropertyBinding.prototype, {
  26296. // prototype, continued
  26297. // these are used to "bind" a nonexistent property
  26298. _getValue_unavailable: function () {},
  26299. _setValue_unavailable: function () {},
  26300. BindingType: {
  26301. Direct: 0,
  26302. EntireArray: 1,
  26303. ArrayElement: 2,
  26304. HasFromToArray: 3
  26305. },
  26306. Versioning: {
  26307. None: 0,
  26308. NeedsUpdate: 1,
  26309. MatrixWorldNeedsUpdate: 2
  26310. },
  26311. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26312. buffer[offset] = this.node[this.propertyName];
  26313. }, function getValue_array(buffer, offset) {
  26314. const source = this.resolvedProperty;
  26315. for (let i = 0, n = source.length; i !== n; ++i) {
  26316. buffer[offset++] = source[i];
  26317. }
  26318. }, function getValue_arrayElement(buffer, offset) {
  26319. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26320. }, function getValue_toArray(buffer, offset) {
  26321. this.resolvedProperty.toArray(buffer, offset);
  26322. }],
  26323. SetterByBindingTypeAndVersioning: [[// Direct
  26324. function setValue_direct(buffer, offset) {
  26325. this.targetObject[this.propertyName] = buffer[offset];
  26326. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26327. this.targetObject[this.propertyName] = buffer[offset];
  26328. this.targetObject.needsUpdate = true;
  26329. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26330. this.targetObject[this.propertyName] = buffer[offset];
  26331. this.targetObject.matrixWorldNeedsUpdate = true;
  26332. }], [// EntireArray
  26333. function setValue_array(buffer, offset) {
  26334. const dest = this.resolvedProperty;
  26335. for (let i = 0, n = dest.length; i !== n; ++i) {
  26336. dest[i] = buffer[offset++];
  26337. }
  26338. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26339. const dest = this.resolvedProperty;
  26340. for (let i = 0, n = dest.length; i !== n; ++i) {
  26341. dest[i] = buffer[offset++];
  26342. }
  26343. this.targetObject.needsUpdate = true;
  26344. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26345. const dest = this.resolvedProperty;
  26346. for (let i = 0, n = dest.length; i !== n; ++i) {
  26347. dest[i] = buffer[offset++];
  26348. }
  26349. this.targetObject.matrixWorldNeedsUpdate = true;
  26350. }], [// ArrayElement
  26351. function setValue_arrayElement(buffer, offset) {
  26352. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26353. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26354. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26355. this.targetObject.needsUpdate = true;
  26356. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26357. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26358. this.targetObject.matrixWorldNeedsUpdate = true;
  26359. }], [// HasToFromArray
  26360. function setValue_fromArray(buffer, offset) {
  26361. this.resolvedProperty.fromArray(buffer, offset);
  26362. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26363. this.resolvedProperty.fromArray(buffer, offset);
  26364. this.targetObject.needsUpdate = true;
  26365. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26366. this.resolvedProperty.fromArray(buffer, offset);
  26367. this.targetObject.matrixWorldNeedsUpdate = true;
  26368. }]],
  26369. getValue: function getValue_unbound(targetArray, offset) {
  26370. this.bind();
  26371. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26372. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26373. // prototype version of these methods with one that represents
  26374. // the bound state. When the property is not found, the methods
  26375. // become no-ops.
  26376. },
  26377. setValue: function getValue_unbound(sourceArray, offset) {
  26378. this.bind();
  26379. this.setValue(sourceArray, offset);
  26380. },
  26381. // create getter / setter pair for a property in the scene graph
  26382. bind: function () {
  26383. let targetObject = this.node;
  26384. const parsedPath = this.parsedPath;
  26385. const objectName = parsedPath.objectName;
  26386. const propertyName = parsedPath.propertyName;
  26387. let propertyIndex = parsedPath.propertyIndex;
  26388. if (!targetObject) {
  26389. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26390. this.node = targetObject;
  26391. } // set fail state so we can just 'return' on error
  26392. this.getValue = this._getValue_unavailable;
  26393. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26394. if (!targetObject) {
  26395. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26396. return;
  26397. }
  26398. if (objectName) {
  26399. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26400. switch (objectName) {
  26401. case 'materials':
  26402. if (!targetObject.material) {
  26403. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26404. return;
  26405. }
  26406. if (!targetObject.material.materials) {
  26407. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26408. return;
  26409. }
  26410. targetObject = targetObject.material.materials;
  26411. break;
  26412. case 'bones':
  26413. if (!targetObject.skeleton) {
  26414. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26415. return;
  26416. } // potential future optimization: skip this if propertyIndex is already an integer
  26417. // and convert the integer string to a true integer.
  26418. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26419. for (let i = 0; i < targetObject.length; i++) {
  26420. if (targetObject[i].name === objectIndex) {
  26421. objectIndex = i;
  26422. break;
  26423. }
  26424. }
  26425. break;
  26426. default:
  26427. if (targetObject[objectName] === undefined) {
  26428. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26429. return;
  26430. }
  26431. targetObject = targetObject[objectName];
  26432. }
  26433. if (objectIndex !== undefined) {
  26434. if (targetObject[objectIndex] === undefined) {
  26435. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26436. return;
  26437. }
  26438. targetObject = targetObject[objectIndex];
  26439. }
  26440. } // resolve property
  26441. const nodeProperty = targetObject[propertyName];
  26442. if (nodeProperty === undefined) {
  26443. const nodeName = parsedPath.nodeName;
  26444. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26445. return;
  26446. } // determine versioning scheme
  26447. let versioning = this.Versioning.None;
  26448. this.targetObject = targetObject;
  26449. if (targetObject.needsUpdate !== undefined) {
  26450. // material
  26451. versioning = this.Versioning.NeedsUpdate;
  26452. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26453. // node transform
  26454. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26455. } // determine how the property gets bound
  26456. let bindingType = this.BindingType.Direct;
  26457. if (propertyIndex !== undefined) {
  26458. // access a sub element of the property array (only primitives are supported right now)
  26459. if (propertyName === "morphTargetInfluences") {
  26460. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26461. // support resolving morphTarget names into indices.
  26462. if (!targetObject.geometry) {
  26463. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26464. return;
  26465. }
  26466. if (targetObject.geometry.isBufferGeometry) {
  26467. if (!targetObject.geometry.morphAttributes) {
  26468. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26469. return;
  26470. }
  26471. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26472. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26473. }
  26474. } else {
  26475. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  26476. return;
  26477. }
  26478. }
  26479. bindingType = this.BindingType.ArrayElement;
  26480. this.resolvedProperty = nodeProperty;
  26481. this.propertyIndex = propertyIndex;
  26482. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26483. // must use copy for Object3D.Euler/Quaternion
  26484. bindingType = this.BindingType.HasFromToArray;
  26485. this.resolvedProperty = nodeProperty;
  26486. } else if (Array.isArray(nodeProperty)) {
  26487. bindingType = this.BindingType.EntireArray;
  26488. this.resolvedProperty = nodeProperty;
  26489. } else {
  26490. this.propertyName = propertyName;
  26491. } // select getter / setter
  26492. this.getValue = this.GetterByBindingType[bindingType];
  26493. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26494. },
  26495. unbind: function () {
  26496. this.node = null; // back to the prototype version of getValue / setValue
  26497. // note: avoiding to mutate the shape of 'this' via 'delete'
  26498. this.getValue = this._getValue_unbound;
  26499. this.setValue = this._setValue_unbound;
  26500. }
  26501. }); // DECLARE ALIAS AFTER assign prototype
  26502. Object.assign(PropertyBinding.prototype, {
  26503. // initial state of these methods that calls 'bind'
  26504. _getValue_unbound: PropertyBinding.prototype.getValue,
  26505. _setValue_unbound: PropertyBinding.prototype.setValue
  26506. });
  26507. /**
  26508. *
  26509. * A group of objects that receives a shared animation state.
  26510. *
  26511. * Usage:
  26512. *
  26513. * - Add objects you would otherwise pass as 'root' to the
  26514. * constructor or the .clipAction method of AnimationMixer.
  26515. *
  26516. * - Instead pass this object as 'root'.
  26517. *
  26518. * - You can also add and remove objects later when the mixer
  26519. * is running.
  26520. *
  26521. * Note:
  26522. *
  26523. * Objects of this class appear as one object to the mixer,
  26524. * so cache control of the individual objects must be done
  26525. * on the group.
  26526. *
  26527. * Limitation:
  26528. *
  26529. * - The animated properties must be compatible among the
  26530. * all objects in the group.
  26531. *
  26532. * - A single property can either be controlled through a
  26533. * target group or directly, but not both.
  26534. */
  26535. function AnimationObjectGroup() {
  26536. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  26537. this._objects = Array.prototype.slice.call(arguments);
  26538. this.nCachedObjects_ = 0; // threshold
  26539. // note: read by PropertyBinding.Composite
  26540. const indices = {};
  26541. this._indicesByUUID = indices; // for bookkeeping
  26542. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26543. indices[arguments[i].uuid] = i;
  26544. }
  26545. this._paths = []; // inside: string
  26546. this._parsedPaths = []; // inside: { we don't care, here }
  26547. this._bindings = []; // inside: Array< PropertyBinding >
  26548. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26549. const scope = this;
  26550. this.stats = {
  26551. objects: {
  26552. get total() {
  26553. return scope._objects.length;
  26554. },
  26555. get inUse() {
  26556. return this.total - scope.nCachedObjects_;
  26557. }
  26558. },
  26559. get bindingsPerObject() {
  26560. return scope._bindings.length;
  26561. }
  26562. };
  26563. }
  26564. Object.assign(AnimationObjectGroup.prototype, {
  26565. isAnimationObjectGroup: true,
  26566. add: function () {
  26567. const objects = this._objects,
  26568. indicesByUUID = this._indicesByUUID,
  26569. paths = this._paths,
  26570. parsedPaths = this._parsedPaths,
  26571. bindings = this._bindings,
  26572. nBindings = bindings.length;
  26573. let knownObject = undefined,
  26574. nObjects = objects.length,
  26575. nCachedObjects = this.nCachedObjects_;
  26576. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26577. const object = arguments[i],
  26578. uuid = object.uuid;
  26579. let index = indicesByUUID[uuid];
  26580. if (index === undefined) {
  26581. // unknown object -> add it to the ACTIVE region
  26582. index = nObjects++;
  26583. indicesByUUID[uuid] = index;
  26584. objects.push(object); // accounting is done, now do the same for all bindings
  26585. for (let j = 0, m = nBindings; j !== m; ++j) {
  26586. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26587. }
  26588. } else if (index < nCachedObjects) {
  26589. knownObject = objects[index]; // move existing object to the ACTIVE region
  26590. const firstActiveIndex = --nCachedObjects,
  26591. lastCachedObject = objects[firstActiveIndex];
  26592. indicesByUUID[lastCachedObject.uuid] = index;
  26593. objects[index] = lastCachedObject;
  26594. indicesByUUID[uuid] = firstActiveIndex;
  26595. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26596. for (let j = 0, m = nBindings; j !== m; ++j) {
  26597. const bindingsForPath = bindings[j],
  26598. lastCached = bindingsForPath[firstActiveIndex];
  26599. let binding = bindingsForPath[index];
  26600. bindingsForPath[index] = lastCached;
  26601. if (binding === undefined) {
  26602. // since we do not bother to create new bindings
  26603. // for objects that are cached, the binding may
  26604. // or may not exist
  26605. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26606. }
  26607. bindingsForPath[firstActiveIndex] = binding;
  26608. }
  26609. } else if (objects[index] !== knownObject) {
  26610. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26611. } // else the object is already where we want it to be
  26612. } // for arguments
  26613. this.nCachedObjects_ = nCachedObjects;
  26614. },
  26615. remove: function () {
  26616. const objects = this._objects,
  26617. indicesByUUID = this._indicesByUUID,
  26618. bindings = this._bindings,
  26619. nBindings = bindings.length;
  26620. let nCachedObjects = this.nCachedObjects_;
  26621. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26622. const object = arguments[i],
  26623. uuid = object.uuid,
  26624. index = indicesByUUID[uuid];
  26625. if (index !== undefined && index >= nCachedObjects) {
  26626. // move existing object into the CACHED region
  26627. const lastCachedIndex = nCachedObjects++,
  26628. firstActiveObject = objects[lastCachedIndex];
  26629. indicesByUUID[firstActiveObject.uuid] = index;
  26630. objects[index] = firstActiveObject;
  26631. indicesByUUID[uuid] = lastCachedIndex;
  26632. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26633. for (let j = 0, m = nBindings; j !== m; ++j) {
  26634. const bindingsForPath = bindings[j],
  26635. firstActive = bindingsForPath[lastCachedIndex],
  26636. binding = bindingsForPath[index];
  26637. bindingsForPath[index] = firstActive;
  26638. bindingsForPath[lastCachedIndex] = binding;
  26639. }
  26640. }
  26641. } // for arguments
  26642. this.nCachedObjects_ = nCachedObjects;
  26643. },
  26644. // remove & forget
  26645. uncache: function () {
  26646. const objects = this._objects,
  26647. indicesByUUID = this._indicesByUUID,
  26648. bindings = this._bindings,
  26649. nBindings = bindings.length;
  26650. let nCachedObjects = this.nCachedObjects_,
  26651. nObjects = objects.length;
  26652. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26653. const object = arguments[i],
  26654. uuid = object.uuid,
  26655. index = indicesByUUID[uuid];
  26656. if (index !== undefined) {
  26657. delete indicesByUUID[uuid];
  26658. if (index < nCachedObjects) {
  26659. // object is cached, shrink the CACHED region
  26660. const firstActiveIndex = --nCachedObjects,
  26661. lastCachedObject = objects[firstActiveIndex],
  26662. lastIndex = --nObjects,
  26663. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26664. indicesByUUID[lastCachedObject.uuid] = index;
  26665. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26666. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26667. objects[firstActiveIndex] = lastObject;
  26668. objects.pop(); // accounting is done, now do the same for all bindings
  26669. for (let j = 0, m = nBindings; j !== m; ++j) {
  26670. const bindingsForPath = bindings[j],
  26671. lastCached = bindingsForPath[firstActiveIndex],
  26672. last = bindingsForPath[lastIndex];
  26673. bindingsForPath[index] = lastCached;
  26674. bindingsForPath[firstActiveIndex] = last;
  26675. bindingsForPath.pop();
  26676. }
  26677. } else {
  26678. // object is active, just swap with the last and pop
  26679. const lastIndex = --nObjects,
  26680. lastObject = objects[lastIndex];
  26681. if (lastIndex > 0) {
  26682. indicesByUUID[lastObject.uuid] = index;
  26683. }
  26684. objects[index] = lastObject;
  26685. objects.pop(); // accounting is done, now do the same for all bindings
  26686. for (let j = 0, m = nBindings; j !== m; ++j) {
  26687. const bindingsForPath = bindings[j];
  26688. bindingsForPath[index] = bindingsForPath[lastIndex];
  26689. bindingsForPath.pop();
  26690. }
  26691. } // cached or active
  26692. } // if object is known
  26693. } // for arguments
  26694. this.nCachedObjects_ = nCachedObjects;
  26695. },
  26696. // Internal interface used by befriended PropertyBinding.Composite:
  26697. subscribe_: function (path, parsedPath) {
  26698. // returns an array of bindings for the given path that is changed
  26699. // according to the contained objects in the group
  26700. const indicesByPath = this._bindingsIndicesByPath;
  26701. let index = indicesByPath[path];
  26702. const bindings = this._bindings;
  26703. if (index !== undefined) return bindings[index];
  26704. const paths = this._paths,
  26705. parsedPaths = this._parsedPaths,
  26706. objects = this._objects,
  26707. nObjects = objects.length,
  26708. nCachedObjects = this.nCachedObjects_,
  26709. bindingsForPath = new Array(nObjects);
  26710. index = bindings.length;
  26711. indicesByPath[path] = index;
  26712. paths.push(path);
  26713. parsedPaths.push(parsedPath);
  26714. bindings.push(bindingsForPath);
  26715. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26716. const object = objects[i];
  26717. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26718. }
  26719. return bindingsForPath;
  26720. },
  26721. unsubscribe_: function (path) {
  26722. // tells the group to forget about a property path and no longer
  26723. // update the array previously obtained with 'subscribe_'
  26724. const indicesByPath = this._bindingsIndicesByPath,
  26725. index = indicesByPath[path];
  26726. if (index !== undefined) {
  26727. const paths = this._paths,
  26728. parsedPaths = this._parsedPaths,
  26729. bindings = this._bindings,
  26730. lastBindingsIndex = bindings.length - 1,
  26731. lastBindings = bindings[lastBindingsIndex],
  26732. lastBindingsPath = path[lastBindingsIndex];
  26733. indicesByPath[lastBindingsPath] = index;
  26734. bindings[index] = lastBindings;
  26735. bindings.pop();
  26736. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26737. parsedPaths.pop();
  26738. paths[index] = paths[lastBindingsIndex];
  26739. paths.pop();
  26740. }
  26741. }
  26742. });
  26743. class AnimationAction {
  26744. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26745. this._mixer = mixer;
  26746. this._clip = clip;
  26747. this._localRoot = localRoot;
  26748. this.blendMode = blendMode;
  26749. const tracks = clip.tracks,
  26750. nTracks = tracks.length,
  26751. interpolants = new Array(nTracks);
  26752. const interpolantSettings = {
  26753. endingStart: ZeroCurvatureEnding,
  26754. endingEnd: ZeroCurvatureEnding
  26755. };
  26756. for (let i = 0; i !== nTracks; ++i) {
  26757. const interpolant = tracks[i].createInterpolant(null);
  26758. interpolants[i] = interpolant;
  26759. interpolant.settings = interpolantSettings;
  26760. }
  26761. this._interpolantSettings = interpolantSettings;
  26762. this._interpolants = interpolants; // bound by the mixer
  26763. // inside: PropertyMixer (managed by the mixer)
  26764. this._propertyBindings = new Array(nTracks);
  26765. this._cacheIndex = null; // for the memory manager
  26766. this._byClipCacheIndex = null; // for the memory manager
  26767. this._timeScaleInterpolant = null;
  26768. this._weightInterpolant = null;
  26769. this.loop = LoopRepeat;
  26770. this._loopCount = -1; // global mixer time when the action is to be started
  26771. // it's set back to 'null' upon start of the action
  26772. this._startTime = null; // scaled local time of the action
  26773. // gets clamped or wrapped to 0..clip.duration according to loop
  26774. this.time = 0;
  26775. this.timeScale = 1;
  26776. this._effectiveTimeScale = 1;
  26777. this.weight = 1;
  26778. this._effectiveWeight = 1;
  26779. this.repetitions = Infinity; // no. of repetitions when looping
  26780. this.paused = false; // true -> zero effective time scale
  26781. this.enabled = true; // false -> zero effective weight
  26782. this.clampWhenFinished = false; // keep feeding the last frame?
  26783. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26784. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26785. } // State & Scheduling
  26786. play() {
  26787. this._mixer._activateAction(this);
  26788. return this;
  26789. }
  26790. stop() {
  26791. this._mixer._deactivateAction(this);
  26792. return this.reset();
  26793. }
  26794. reset() {
  26795. this.paused = false;
  26796. this.enabled = true;
  26797. this.time = 0; // restart clip
  26798. this._loopCount = -1; // forget previous loops
  26799. this._startTime = null; // forget scheduling
  26800. return this.stopFading().stopWarping();
  26801. }
  26802. isRunning() {
  26803. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26804. } // return true when play has been called
  26805. isScheduled() {
  26806. return this._mixer._isActiveAction(this);
  26807. }
  26808. startAt(time) {
  26809. this._startTime = time;
  26810. return this;
  26811. }
  26812. setLoop(mode, repetitions) {
  26813. this.loop = mode;
  26814. this.repetitions = repetitions;
  26815. return this;
  26816. } // Weight
  26817. // set the weight stopping any scheduled fading
  26818. // although .enabled = false yields an effective weight of zero, this
  26819. // method does *not* change .enabled, because it would be confusing
  26820. setEffectiveWeight(weight) {
  26821. this.weight = weight; // note: same logic as when updated at runtime
  26822. this._effectiveWeight = this.enabled ? weight : 0;
  26823. return this.stopFading();
  26824. } // return the weight considering fading and .enabled
  26825. getEffectiveWeight() {
  26826. return this._effectiveWeight;
  26827. }
  26828. fadeIn(duration) {
  26829. return this._scheduleFading(duration, 0, 1);
  26830. }
  26831. fadeOut(duration) {
  26832. return this._scheduleFading(duration, 1, 0);
  26833. }
  26834. crossFadeFrom(fadeOutAction, duration, warp) {
  26835. fadeOutAction.fadeOut(duration);
  26836. this.fadeIn(duration);
  26837. if (warp) {
  26838. const fadeInDuration = this._clip.duration,
  26839. fadeOutDuration = fadeOutAction._clip.duration,
  26840. startEndRatio = fadeOutDuration / fadeInDuration,
  26841. endStartRatio = fadeInDuration / fadeOutDuration;
  26842. fadeOutAction.warp(1.0, startEndRatio, duration);
  26843. this.warp(endStartRatio, 1.0, duration);
  26844. }
  26845. return this;
  26846. }
  26847. crossFadeTo(fadeInAction, duration, warp) {
  26848. return fadeInAction.crossFadeFrom(this, duration, warp);
  26849. }
  26850. stopFading() {
  26851. const weightInterpolant = this._weightInterpolant;
  26852. if (weightInterpolant !== null) {
  26853. this._weightInterpolant = null;
  26854. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26855. }
  26856. return this;
  26857. } // Time Scale Control
  26858. // set the time scale stopping any scheduled warping
  26859. // although .paused = true yields an effective time scale of zero, this
  26860. // method does *not* change .paused, because it would be confusing
  26861. setEffectiveTimeScale(timeScale) {
  26862. this.timeScale = timeScale;
  26863. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26864. return this.stopWarping();
  26865. } // return the time scale considering warping and .paused
  26866. getEffectiveTimeScale() {
  26867. return this._effectiveTimeScale;
  26868. }
  26869. setDuration(duration) {
  26870. this.timeScale = this._clip.duration / duration;
  26871. return this.stopWarping();
  26872. }
  26873. syncWith(action) {
  26874. this.time = action.time;
  26875. this.timeScale = action.timeScale;
  26876. return this.stopWarping();
  26877. }
  26878. halt(duration) {
  26879. return this.warp(this._effectiveTimeScale, 0, duration);
  26880. }
  26881. warp(startTimeScale, endTimeScale, duration) {
  26882. const mixer = this._mixer,
  26883. now = mixer.time,
  26884. timeScale = this.timeScale;
  26885. let interpolant = this._timeScaleInterpolant;
  26886. if (interpolant === null) {
  26887. interpolant = mixer._lendControlInterpolant();
  26888. this._timeScaleInterpolant = interpolant;
  26889. }
  26890. const times = interpolant.parameterPositions,
  26891. values = interpolant.sampleValues;
  26892. times[0] = now;
  26893. times[1] = now + duration;
  26894. values[0] = startTimeScale / timeScale;
  26895. values[1] = endTimeScale / timeScale;
  26896. return this;
  26897. }
  26898. stopWarping() {
  26899. const timeScaleInterpolant = this._timeScaleInterpolant;
  26900. if (timeScaleInterpolant !== null) {
  26901. this._timeScaleInterpolant = null;
  26902. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26903. }
  26904. return this;
  26905. } // Object Accessors
  26906. getMixer() {
  26907. return this._mixer;
  26908. }
  26909. getClip() {
  26910. return this._clip;
  26911. }
  26912. getRoot() {
  26913. return this._localRoot || this._mixer._root;
  26914. } // Interna
  26915. _update(time, deltaTime, timeDirection, accuIndex) {
  26916. // called by the mixer
  26917. if (!this.enabled) {
  26918. // call ._updateWeight() to update ._effectiveWeight
  26919. this._updateWeight(time);
  26920. return;
  26921. }
  26922. const startTime = this._startTime;
  26923. if (startTime !== null) {
  26924. // check for scheduled start of action
  26925. const timeRunning = (time - startTime) * timeDirection;
  26926. if (timeRunning < 0 || timeDirection === 0) {
  26927. return; // yet to come / don't decide when delta = 0
  26928. } // start
  26929. this._startTime = null; // unschedule
  26930. deltaTime = timeDirection * timeRunning;
  26931. } // apply time scale and advance time
  26932. deltaTime *= this._updateTimeScale(time);
  26933. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26934. // an effective weight of 0
  26935. const weight = this._updateWeight(time);
  26936. if (weight > 0) {
  26937. const interpolants = this._interpolants;
  26938. const propertyMixers = this._propertyBindings;
  26939. switch (this.blendMode) {
  26940. case AdditiveAnimationBlendMode:
  26941. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26942. interpolants[j].evaluate(clipTime);
  26943. propertyMixers[j].accumulateAdditive(weight);
  26944. }
  26945. break;
  26946. case NormalAnimationBlendMode:
  26947. default:
  26948. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26949. interpolants[j].evaluate(clipTime);
  26950. propertyMixers[j].accumulate(accuIndex, weight);
  26951. }
  26952. }
  26953. }
  26954. }
  26955. _updateWeight(time) {
  26956. let weight = 0;
  26957. if (this.enabled) {
  26958. weight = this.weight;
  26959. const interpolant = this._weightInterpolant;
  26960. if (interpolant !== null) {
  26961. const interpolantValue = interpolant.evaluate(time)[0];
  26962. weight *= interpolantValue;
  26963. if (time > interpolant.parameterPositions[1]) {
  26964. this.stopFading();
  26965. if (interpolantValue === 0) {
  26966. // faded out, disable
  26967. this.enabled = false;
  26968. }
  26969. }
  26970. }
  26971. }
  26972. this._effectiveWeight = weight;
  26973. return weight;
  26974. }
  26975. _updateTimeScale(time) {
  26976. let timeScale = 0;
  26977. if (!this.paused) {
  26978. timeScale = this.timeScale;
  26979. const interpolant = this._timeScaleInterpolant;
  26980. if (interpolant !== null) {
  26981. const interpolantValue = interpolant.evaluate(time)[0];
  26982. timeScale *= interpolantValue;
  26983. if (time > interpolant.parameterPositions[1]) {
  26984. this.stopWarping();
  26985. if (timeScale === 0) {
  26986. // motion has halted, pause
  26987. this.paused = true;
  26988. } else {
  26989. // warp done - apply final time scale
  26990. this.timeScale = timeScale;
  26991. }
  26992. }
  26993. }
  26994. }
  26995. this._effectiveTimeScale = timeScale;
  26996. return timeScale;
  26997. }
  26998. _updateTime(deltaTime) {
  26999. const duration = this._clip.duration;
  27000. const loop = this.loop;
  27001. let time = this.time + deltaTime;
  27002. let loopCount = this._loopCount;
  27003. const pingPong = loop === LoopPingPong;
  27004. if (deltaTime === 0) {
  27005. if (loopCount === -1) return time;
  27006. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27007. }
  27008. if (loop === LoopOnce) {
  27009. if (loopCount === -1) {
  27010. // just started
  27011. this._loopCount = 0;
  27012. this._setEndings(true, true, false);
  27013. }
  27014. handle_stop: {
  27015. if (time >= duration) {
  27016. time = duration;
  27017. } else if (time < 0) {
  27018. time = 0;
  27019. } else {
  27020. this.time = time;
  27021. break handle_stop;
  27022. }
  27023. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27024. this.time = time;
  27025. this._mixer.dispatchEvent({
  27026. type: 'finished',
  27027. action: this,
  27028. direction: deltaTime < 0 ? -1 : 1
  27029. });
  27030. }
  27031. } else {
  27032. // repetitive Repeat or PingPong
  27033. if (loopCount === -1) {
  27034. // just started
  27035. if (deltaTime >= 0) {
  27036. loopCount = 0;
  27037. this._setEndings(true, this.repetitions === 0, pingPong);
  27038. } else {
  27039. // when looping in reverse direction, the initial
  27040. // transition through zero counts as a repetition,
  27041. // so leave loopCount at -1
  27042. this._setEndings(this.repetitions === 0, true, pingPong);
  27043. }
  27044. }
  27045. if (time >= duration || time < 0) {
  27046. // wrap around
  27047. const loopDelta = Math.floor(time / duration); // signed
  27048. time -= duration * loopDelta;
  27049. loopCount += Math.abs(loopDelta);
  27050. const pending = this.repetitions - loopCount;
  27051. if (pending <= 0) {
  27052. // have to stop (switch state, clamp time, fire event)
  27053. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27054. time = deltaTime > 0 ? duration : 0;
  27055. this.time = time;
  27056. this._mixer.dispatchEvent({
  27057. type: 'finished',
  27058. action: this,
  27059. direction: deltaTime > 0 ? 1 : -1
  27060. });
  27061. } else {
  27062. // keep running
  27063. if (pending === 1) {
  27064. // entering the last round
  27065. const atStart = deltaTime < 0;
  27066. this._setEndings(atStart, !atStart, pingPong);
  27067. } else {
  27068. this._setEndings(false, false, pingPong);
  27069. }
  27070. this._loopCount = loopCount;
  27071. this.time = time;
  27072. this._mixer.dispatchEvent({
  27073. type: 'loop',
  27074. action: this,
  27075. loopDelta: loopDelta
  27076. });
  27077. }
  27078. } else {
  27079. this.time = time;
  27080. }
  27081. if (pingPong && (loopCount & 1) === 1) {
  27082. // invert time for the "pong round"
  27083. return duration - time;
  27084. }
  27085. }
  27086. return time;
  27087. }
  27088. _setEndings(atStart, atEnd, pingPong) {
  27089. const settings = this._interpolantSettings;
  27090. if (pingPong) {
  27091. settings.endingStart = ZeroSlopeEnding;
  27092. settings.endingEnd = ZeroSlopeEnding;
  27093. } else {
  27094. // assuming for LoopOnce atStart == atEnd == true
  27095. if (atStart) {
  27096. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27097. } else {
  27098. settings.endingStart = WrapAroundEnding;
  27099. }
  27100. if (atEnd) {
  27101. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27102. } else {
  27103. settings.endingEnd = WrapAroundEnding;
  27104. }
  27105. }
  27106. }
  27107. _scheduleFading(duration, weightNow, weightThen) {
  27108. const mixer = this._mixer,
  27109. now = mixer.time;
  27110. let interpolant = this._weightInterpolant;
  27111. if (interpolant === null) {
  27112. interpolant = mixer._lendControlInterpolant();
  27113. this._weightInterpolant = interpolant;
  27114. }
  27115. const times = interpolant.parameterPositions,
  27116. values = interpolant.sampleValues;
  27117. times[0] = now;
  27118. values[0] = weightNow;
  27119. times[1] = now + duration;
  27120. values[1] = weightThen;
  27121. return this;
  27122. }
  27123. }
  27124. function AnimationMixer(root) {
  27125. this._root = root;
  27126. this._initMemoryManager();
  27127. this._accuIndex = 0;
  27128. this.time = 0;
  27129. this.timeScale = 1.0;
  27130. }
  27131. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27132. constructor: AnimationMixer,
  27133. _bindAction: function (action, prototypeAction) {
  27134. const root = action._localRoot || this._root,
  27135. tracks = action._clip.tracks,
  27136. nTracks = tracks.length,
  27137. bindings = action._propertyBindings,
  27138. interpolants = action._interpolants,
  27139. rootUuid = root.uuid,
  27140. bindingsByRoot = this._bindingsByRootAndName;
  27141. let bindingsByName = bindingsByRoot[rootUuid];
  27142. if (bindingsByName === undefined) {
  27143. bindingsByName = {};
  27144. bindingsByRoot[rootUuid] = bindingsByName;
  27145. }
  27146. for (let i = 0; i !== nTracks; ++i) {
  27147. const track = tracks[i],
  27148. trackName = track.name;
  27149. let binding = bindingsByName[trackName];
  27150. if (binding !== undefined) {
  27151. bindings[i] = binding;
  27152. } else {
  27153. binding = bindings[i];
  27154. if (binding !== undefined) {
  27155. // existing binding, make sure the cache knows
  27156. if (binding._cacheIndex === null) {
  27157. ++binding.referenceCount;
  27158. this._addInactiveBinding(binding, rootUuid, trackName);
  27159. }
  27160. continue;
  27161. }
  27162. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27163. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27164. ++binding.referenceCount;
  27165. this._addInactiveBinding(binding, rootUuid, trackName);
  27166. bindings[i] = binding;
  27167. }
  27168. interpolants[i].resultBuffer = binding.buffer;
  27169. }
  27170. },
  27171. _activateAction: function (action) {
  27172. if (!this._isActiveAction(action)) {
  27173. if (action._cacheIndex === null) {
  27174. // this action has been forgotten by the cache, but the user
  27175. // appears to be still using it -> rebind
  27176. const rootUuid = (action._localRoot || this._root).uuid,
  27177. clipUuid = action._clip.uuid,
  27178. actionsForClip = this._actionsByClip[clipUuid];
  27179. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27180. this._addInactiveAction(action, clipUuid, rootUuid);
  27181. }
  27182. const bindings = action._propertyBindings; // increment reference counts / sort out state
  27183. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27184. const binding = bindings[i];
  27185. if (binding.useCount++ === 0) {
  27186. this._lendBinding(binding);
  27187. binding.saveOriginalState();
  27188. }
  27189. }
  27190. this._lendAction(action);
  27191. }
  27192. },
  27193. _deactivateAction: function (action) {
  27194. if (this._isActiveAction(action)) {
  27195. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  27196. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27197. const binding = bindings[i];
  27198. if (--binding.useCount === 0) {
  27199. binding.restoreOriginalState();
  27200. this._takeBackBinding(binding);
  27201. }
  27202. }
  27203. this._takeBackAction(action);
  27204. }
  27205. },
  27206. // Memory manager
  27207. _initMemoryManager: function () {
  27208. this._actions = []; // 'nActiveActions' followed by inactive ones
  27209. this._nActiveActions = 0;
  27210. this._actionsByClip = {}; // inside:
  27211. // {
  27212. // knownActions: Array< AnimationAction > - used as prototypes
  27213. // actionByRoot: AnimationAction - lookup
  27214. // }
  27215. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27216. this._nActiveBindings = 0;
  27217. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27218. this._controlInterpolants = []; // same game as above
  27219. this._nActiveControlInterpolants = 0;
  27220. const scope = this;
  27221. this.stats = {
  27222. actions: {
  27223. get total() {
  27224. return scope._actions.length;
  27225. },
  27226. get inUse() {
  27227. return scope._nActiveActions;
  27228. }
  27229. },
  27230. bindings: {
  27231. get total() {
  27232. return scope._bindings.length;
  27233. },
  27234. get inUse() {
  27235. return scope._nActiveBindings;
  27236. }
  27237. },
  27238. controlInterpolants: {
  27239. get total() {
  27240. return scope._controlInterpolants.length;
  27241. },
  27242. get inUse() {
  27243. return scope._nActiveControlInterpolants;
  27244. }
  27245. }
  27246. };
  27247. },
  27248. // Memory management for AnimationAction objects
  27249. _isActiveAction: function (action) {
  27250. const index = action._cacheIndex;
  27251. return index !== null && index < this._nActiveActions;
  27252. },
  27253. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27254. const actions = this._actions,
  27255. actionsByClip = this._actionsByClip;
  27256. let actionsForClip = actionsByClip[clipUuid];
  27257. if (actionsForClip === undefined) {
  27258. actionsForClip = {
  27259. knownActions: [action],
  27260. actionByRoot: {}
  27261. };
  27262. action._byClipCacheIndex = 0;
  27263. actionsByClip[clipUuid] = actionsForClip;
  27264. } else {
  27265. const knownActions = actionsForClip.knownActions;
  27266. action._byClipCacheIndex = knownActions.length;
  27267. knownActions.push(action);
  27268. }
  27269. action._cacheIndex = actions.length;
  27270. actions.push(action);
  27271. actionsForClip.actionByRoot[rootUuid] = action;
  27272. },
  27273. _removeInactiveAction: function (action) {
  27274. const actions = this._actions,
  27275. lastInactiveAction = actions[actions.length - 1],
  27276. cacheIndex = action._cacheIndex;
  27277. lastInactiveAction._cacheIndex = cacheIndex;
  27278. actions[cacheIndex] = lastInactiveAction;
  27279. actions.pop();
  27280. action._cacheIndex = null;
  27281. const clipUuid = action._clip.uuid,
  27282. actionsByClip = this._actionsByClip,
  27283. actionsForClip = actionsByClip[clipUuid],
  27284. knownActionsForClip = actionsForClip.knownActions,
  27285. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27286. byClipCacheIndex = action._byClipCacheIndex;
  27287. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27288. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27289. knownActionsForClip.pop();
  27290. action._byClipCacheIndex = null;
  27291. const actionByRoot = actionsForClip.actionByRoot,
  27292. rootUuid = (action._localRoot || this._root).uuid;
  27293. delete actionByRoot[rootUuid];
  27294. if (knownActionsForClip.length === 0) {
  27295. delete actionsByClip[clipUuid];
  27296. }
  27297. this._removeInactiveBindingsForAction(action);
  27298. },
  27299. _removeInactiveBindingsForAction: function (action) {
  27300. const bindings = action._propertyBindings;
  27301. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27302. const binding = bindings[i];
  27303. if (--binding.referenceCount === 0) {
  27304. this._removeInactiveBinding(binding);
  27305. }
  27306. }
  27307. },
  27308. _lendAction: function (action) {
  27309. // [ active actions | inactive actions ]
  27310. // [ active actions >| inactive actions ]
  27311. // s a
  27312. // <-swap->
  27313. // a s
  27314. const actions = this._actions,
  27315. prevIndex = action._cacheIndex,
  27316. lastActiveIndex = this._nActiveActions++,
  27317. firstInactiveAction = actions[lastActiveIndex];
  27318. action._cacheIndex = lastActiveIndex;
  27319. actions[lastActiveIndex] = action;
  27320. firstInactiveAction._cacheIndex = prevIndex;
  27321. actions[prevIndex] = firstInactiveAction;
  27322. },
  27323. _takeBackAction: function (action) {
  27324. // [ active actions | inactive actions ]
  27325. // [ active actions |< inactive actions ]
  27326. // a s
  27327. // <-swap->
  27328. // s a
  27329. const actions = this._actions,
  27330. prevIndex = action._cacheIndex,
  27331. firstInactiveIndex = --this._nActiveActions,
  27332. lastActiveAction = actions[firstInactiveIndex];
  27333. action._cacheIndex = firstInactiveIndex;
  27334. actions[firstInactiveIndex] = action;
  27335. lastActiveAction._cacheIndex = prevIndex;
  27336. actions[prevIndex] = lastActiveAction;
  27337. },
  27338. // Memory management for PropertyMixer objects
  27339. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27340. const bindingsByRoot = this._bindingsByRootAndName,
  27341. bindings = this._bindings;
  27342. let bindingByName = bindingsByRoot[rootUuid];
  27343. if (bindingByName === undefined) {
  27344. bindingByName = {};
  27345. bindingsByRoot[rootUuid] = bindingByName;
  27346. }
  27347. bindingByName[trackName] = binding;
  27348. binding._cacheIndex = bindings.length;
  27349. bindings.push(binding);
  27350. },
  27351. _removeInactiveBinding: function (binding) {
  27352. const bindings = this._bindings,
  27353. propBinding = binding.binding,
  27354. rootUuid = propBinding.rootNode.uuid,
  27355. trackName = propBinding.path,
  27356. bindingsByRoot = this._bindingsByRootAndName,
  27357. bindingByName = bindingsByRoot[rootUuid],
  27358. lastInactiveBinding = bindings[bindings.length - 1],
  27359. cacheIndex = binding._cacheIndex;
  27360. lastInactiveBinding._cacheIndex = cacheIndex;
  27361. bindings[cacheIndex] = lastInactiveBinding;
  27362. bindings.pop();
  27363. delete bindingByName[trackName];
  27364. if (Object.keys(bindingByName).length === 0) {
  27365. delete bindingsByRoot[rootUuid];
  27366. }
  27367. },
  27368. _lendBinding: function (binding) {
  27369. const bindings = this._bindings,
  27370. prevIndex = binding._cacheIndex,
  27371. lastActiveIndex = this._nActiveBindings++,
  27372. firstInactiveBinding = bindings[lastActiveIndex];
  27373. binding._cacheIndex = lastActiveIndex;
  27374. bindings[lastActiveIndex] = binding;
  27375. firstInactiveBinding._cacheIndex = prevIndex;
  27376. bindings[prevIndex] = firstInactiveBinding;
  27377. },
  27378. _takeBackBinding: function (binding) {
  27379. const bindings = this._bindings,
  27380. prevIndex = binding._cacheIndex,
  27381. firstInactiveIndex = --this._nActiveBindings,
  27382. lastActiveBinding = bindings[firstInactiveIndex];
  27383. binding._cacheIndex = firstInactiveIndex;
  27384. bindings[firstInactiveIndex] = binding;
  27385. lastActiveBinding._cacheIndex = prevIndex;
  27386. bindings[prevIndex] = lastActiveBinding;
  27387. },
  27388. // Memory management of Interpolants for weight and time scale
  27389. _lendControlInterpolant: function () {
  27390. const interpolants = this._controlInterpolants,
  27391. lastActiveIndex = this._nActiveControlInterpolants++;
  27392. let interpolant = interpolants[lastActiveIndex];
  27393. if (interpolant === undefined) {
  27394. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27395. interpolant.__cacheIndex = lastActiveIndex;
  27396. interpolants[lastActiveIndex] = interpolant;
  27397. }
  27398. return interpolant;
  27399. },
  27400. _takeBackControlInterpolant: function (interpolant) {
  27401. const interpolants = this._controlInterpolants,
  27402. prevIndex = interpolant.__cacheIndex,
  27403. firstInactiveIndex = --this._nActiveControlInterpolants,
  27404. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27405. interpolant.__cacheIndex = firstInactiveIndex;
  27406. interpolants[firstInactiveIndex] = interpolant;
  27407. lastActiveInterpolant.__cacheIndex = prevIndex;
  27408. interpolants[prevIndex] = lastActiveInterpolant;
  27409. },
  27410. _controlInterpolantsResultBuffer: new Float32Array(1),
  27411. // return an action for a clip optionally using a custom root target
  27412. // object (this method allocates a lot of dynamic memory in case a
  27413. // previously unknown clip/root combination is specified)
  27414. clipAction: function (clip, optionalRoot, blendMode) {
  27415. const root = optionalRoot || this._root,
  27416. rootUuid = root.uuid;
  27417. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  27418. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27419. const actionsForClip = this._actionsByClip[clipUuid];
  27420. let prototypeAction = null;
  27421. if (blendMode === undefined) {
  27422. if (clipObject !== null) {
  27423. blendMode = clipObject.blendMode;
  27424. } else {
  27425. blendMode = NormalAnimationBlendMode;
  27426. }
  27427. }
  27428. if (actionsForClip !== undefined) {
  27429. const existingAction = actionsForClip.actionByRoot[rootUuid];
  27430. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  27431. return existingAction;
  27432. } // we know the clip, so we don't have to parse all
  27433. // the bindings again but can just copy
  27434. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27435. if (clipObject === null) clipObject = prototypeAction._clip;
  27436. } // clip must be known when specified via string
  27437. if (clipObject === null) return null; // allocate all resources required to run it
  27438. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27439. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27440. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27441. return newAction;
  27442. },
  27443. // get an existing action
  27444. existingAction: function (clip, optionalRoot) {
  27445. const root = optionalRoot || this._root,
  27446. rootUuid = root.uuid,
  27447. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27448. clipUuid = clipObject ? clipObject.uuid : clip,
  27449. actionsForClip = this._actionsByClip[clipUuid];
  27450. if (actionsForClip !== undefined) {
  27451. return actionsForClip.actionByRoot[rootUuid] || null;
  27452. }
  27453. return null;
  27454. },
  27455. // deactivates all previously scheduled actions
  27456. stopAllAction: function () {
  27457. const actions = this._actions,
  27458. nActions = this._nActiveActions;
  27459. for (let i = nActions - 1; i >= 0; --i) {
  27460. actions[i].stop();
  27461. }
  27462. return this;
  27463. },
  27464. // advance the time and update apply the animation
  27465. update: function (deltaTime) {
  27466. deltaTime *= this.timeScale;
  27467. const actions = this._actions,
  27468. nActions = this._nActiveActions,
  27469. time = this.time += deltaTime,
  27470. timeDirection = Math.sign(deltaTime),
  27471. accuIndex = this._accuIndex ^= 1; // run active actions
  27472. for (let i = 0; i !== nActions; ++i) {
  27473. const action = actions[i];
  27474. action._update(time, deltaTime, timeDirection, accuIndex);
  27475. } // update scene graph
  27476. const bindings = this._bindings,
  27477. nBindings = this._nActiveBindings;
  27478. for (let i = 0; i !== nBindings; ++i) {
  27479. bindings[i].apply(accuIndex);
  27480. }
  27481. return this;
  27482. },
  27483. // Allows you to seek to a specific time in an animation.
  27484. setTime: function (timeInSeconds) {
  27485. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27486. for (let i = 0; i < this._actions.length; i++) {
  27487. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27488. }
  27489. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27490. },
  27491. // return this mixer's root target object
  27492. getRoot: function () {
  27493. return this._root;
  27494. },
  27495. // free all resources specific to a particular clip
  27496. uncacheClip: function (clip) {
  27497. const actions = this._actions,
  27498. clipUuid = clip.uuid,
  27499. actionsByClip = this._actionsByClip,
  27500. actionsForClip = actionsByClip[clipUuid];
  27501. if (actionsForClip !== undefined) {
  27502. // note: just calling _removeInactiveAction would mess up the
  27503. // iteration state and also require updating the state we can
  27504. // just throw away
  27505. const actionsToRemove = actionsForClip.knownActions;
  27506. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27507. const action = actionsToRemove[i];
  27508. this._deactivateAction(action);
  27509. const cacheIndex = action._cacheIndex,
  27510. lastInactiveAction = actions[actions.length - 1];
  27511. action._cacheIndex = null;
  27512. action._byClipCacheIndex = null;
  27513. lastInactiveAction._cacheIndex = cacheIndex;
  27514. actions[cacheIndex] = lastInactiveAction;
  27515. actions.pop();
  27516. this._removeInactiveBindingsForAction(action);
  27517. }
  27518. delete actionsByClip[clipUuid];
  27519. }
  27520. },
  27521. // free all resources specific to a particular root target object
  27522. uncacheRoot: function (root) {
  27523. const rootUuid = root.uuid,
  27524. actionsByClip = this._actionsByClip;
  27525. for (const clipUuid in actionsByClip) {
  27526. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27527. action = actionByRoot[rootUuid];
  27528. if (action !== undefined) {
  27529. this._deactivateAction(action);
  27530. this._removeInactiveAction(action);
  27531. }
  27532. }
  27533. const bindingsByRoot = this._bindingsByRootAndName,
  27534. bindingByName = bindingsByRoot[rootUuid];
  27535. if (bindingByName !== undefined) {
  27536. for (const trackName in bindingByName) {
  27537. const binding = bindingByName[trackName];
  27538. binding.restoreOriginalState();
  27539. this._removeInactiveBinding(binding);
  27540. }
  27541. }
  27542. },
  27543. // remove a targeted clip from the cache
  27544. uncacheAction: function (clip, optionalRoot) {
  27545. const action = this.existingAction(clip, optionalRoot);
  27546. if (action !== null) {
  27547. this._deactivateAction(action);
  27548. this._removeInactiveAction(action);
  27549. }
  27550. }
  27551. });
  27552. class Uniform {
  27553. constructor(value) {
  27554. if (typeof value === 'string') {
  27555. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27556. value = arguments[1];
  27557. }
  27558. this.value = value;
  27559. }
  27560. clone() {
  27561. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27562. }
  27563. }
  27564. exports.Uniform = Uniform;
  27565. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27566. InterleavedBuffer.call(this, array, stride);
  27567. this.meshPerAttribute = meshPerAttribute || 1;
  27568. }
  27569. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27570. constructor: InstancedInterleavedBuffer,
  27571. isInstancedInterleavedBuffer: true,
  27572. copy: function (source) {
  27573. InterleavedBuffer.prototype.copy.call(this, source);
  27574. this.meshPerAttribute = source.meshPerAttribute;
  27575. return this;
  27576. },
  27577. clone: function (data) {
  27578. const ib = InterleavedBuffer.prototype.clone.call(this, data);
  27579. ib.meshPerAttribute = this.meshPerAttribute;
  27580. return ib;
  27581. },
  27582. toJSON: function (data) {
  27583. const json = InterleavedBuffer.prototype.toJSON.call(this, data);
  27584. json.isInstancedInterleavedBuffer = true;
  27585. json.meshPerAttribute = this.meshPerAttribute;
  27586. return json;
  27587. }
  27588. });
  27589. function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
  27590. this.buffer = buffer;
  27591. this.type = type;
  27592. this.itemSize = itemSize;
  27593. this.elementSize = elementSize;
  27594. this.count = count;
  27595. this.version = 0;
  27596. }
  27597. Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
  27598. set: function (value) {
  27599. if (value === true) this.version++;
  27600. }
  27601. });
  27602. Object.assign(GLBufferAttribute.prototype, {
  27603. isGLBufferAttribute: true,
  27604. setBuffer: function (buffer) {
  27605. this.buffer = buffer;
  27606. return this;
  27607. },
  27608. setType: function (type, elementSize) {
  27609. this.type = type;
  27610. this.elementSize = elementSize;
  27611. return this;
  27612. },
  27613. setItemSize: function (itemSize) {
  27614. this.itemSize = itemSize;
  27615. return this;
  27616. },
  27617. setCount: function (count) {
  27618. this.count = count;
  27619. return this;
  27620. }
  27621. });
  27622. function Raycaster(origin, direction, near, far) {
  27623. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27624. this.near = near || 0;
  27625. this.far = far || Infinity;
  27626. this.camera = null;
  27627. this.layers = new Layers();
  27628. this.params = {
  27629. Mesh: {},
  27630. Line: {
  27631. threshold: 1
  27632. },
  27633. LOD: {},
  27634. Points: {
  27635. threshold: 1
  27636. },
  27637. Sprite: {}
  27638. };
  27639. Object.defineProperties(this.params, {
  27640. PointCloud: {
  27641. get: function () {
  27642. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27643. return this.Points;
  27644. }
  27645. }
  27646. });
  27647. }
  27648. function ascSort(a, b) {
  27649. return a.distance - b.distance;
  27650. }
  27651. function intersectObject(object, raycaster, intersects, recursive) {
  27652. if (object.layers.test(raycaster.layers)) {
  27653. object.raycast(raycaster, intersects);
  27654. }
  27655. if (recursive === true) {
  27656. const children = object.children;
  27657. for (let i = 0, l = children.length; i < l; i++) {
  27658. intersectObject(children[i], raycaster, intersects, true);
  27659. }
  27660. }
  27661. }
  27662. Object.assign(Raycaster.prototype, {
  27663. set: function (origin, direction) {
  27664. // direction is assumed to be normalized (for accurate distance calculations)
  27665. this.ray.set(origin, direction);
  27666. },
  27667. setFromCamera: function (coords, camera) {
  27668. if (camera && camera.isPerspectiveCamera) {
  27669. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27670. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27671. this.camera = camera;
  27672. } else if (camera && camera.isOrthographicCamera) {
  27673. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27674. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27675. this.camera = camera;
  27676. } else {
  27677. console.error('THREE.Raycaster: Unsupported camera type.');
  27678. }
  27679. },
  27680. intersectObject: function (object, recursive, optionalTarget) {
  27681. const intersects = optionalTarget || [];
  27682. intersectObject(object, this, intersects, recursive);
  27683. intersects.sort(ascSort);
  27684. return intersects;
  27685. },
  27686. intersectObjects: function (objects, recursive, optionalTarget) {
  27687. const intersects = optionalTarget || [];
  27688. if (Array.isArray(objects) === false) {
  27689. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27690. return intersects;
  27691. }
  27692. for (let i = 0, l = objects.length; i < l; i++) {
  27693. intersectObject(objects[i], this, intersects, recursive);
  27694. }
  27695. intersects.sort(ascSort);
  27696. return intersects;
  27697. }
  27698. });
  27699. /**
  27700. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27701. *
  27702. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27703. * The azimuthal angle (theta) is measured from the positive z-axis.
  27704. */
  27705. class Spherical {
  27706. constructor(radius = 1, phi = 0, theta = 0) {
  27707. this.radius = radius;
  27708. this.phi = phi; // polar angle
  27709. this.theta = theta; // azimuthal angle
  27710. return this;
  27711. }
  27712. set(radius, phi, theta) {
  27713. this.radius = radius;
  27714. this.phi = phi;
  27715. this.theta = theta;
  27716. return this;
  27717. }
  27718. clone() {
  27719. return new this.constructor().copy(this);
  27720. }
  27721. copy(other) {
  27722. this.radius = other.radius;
  27723. this.phi = other.phi;
  27724. this.theta = other.theta;
  27725. return this;
  27726. } // restrict phi to be betwee EPS and PI-EPS
  27727. makeSafe() {
  27728. const EPS = 0.000001;
  27729. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27730. return this;
  27731. }
  27732. setFromVector3(v) {
  27733. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27734. }
  27735. setFromCartesianCoords(x, y, z) {
  27736. this.radius = Math.sqrt(x * x + y * y + z * z);
  27737. if (this.radius === 0) {
  27738. this.theta = 0;
  27739. this.phi = 0;
  27740. } else {
  27741. this.theta = Math.atan2(x, z);
  27742. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  27743. }
  27744. return this;
  27745. }
  27746. }
  27747. /**
  27748. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27749. */
  27750. exports.Spherical = Spherical;
  27751. class Cylindrical {
  27752. constructor(radius, theta, y) {
  27753. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27754. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27755. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27756. return this;
  27757. }
  27758. set(radius, theta, y) {
  27759. this.radius = radius;
  27760. this.theta = theta;
  27761. this.y = y;
  27762. return this;
  27763. }
  27764. clone() {
  27765. return new this.constructor().copy(this);
  27766. }
  27767. copy(other) {
  27768. this.radius = other.radius;
  27769. this.theta = other.theta;
  27770. this.y = other.y;
  27771. return this;
  27772. }
  27773. setFromVector3(v) {
  27774. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27775. }
  27776. setFromCartesianCoords(x, y, z) {
  27777. this.radius = Math.sqrt(x * x + z * z);
  27778. this.theta = Math.atan2(x, z);
  27779. this.y = y;
  27780. return this;
  27781. }
  27782. }
  27783. exports.Cylindrical = Cylindrical;
  27784. const _vector$7 =
  27785. /*@__PURE__*/
  27786. new Vector2();
  27787. class Box2 {
  27788. constructor(min, max) {
  27789. Object.defineProperty(this, 'isBox2', {
  27790. value: true
  27791. });
  27792. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27793. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27794. }
  27795. set(min, max) {
  27796. this.min.copy(min);
  27797. this.max.copy(max);
  27798. return this;
  27799. }
  27800. setFromPoints(points) {
  27801. this.makeEmpty();
  27802. for (let i = 0, il = points.length; i < il; i++) {
  27803. this.expandByPoint(points[i]);
  27804. }
  27805. return this;
  27806. }
  27807. setFromCenterAndSize(center, size) {
  27808. const halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  27809. this.min.copy(center).sub(halfSize);
  27810. this.max.copy(center).add(halfSize);
  27811. return this;
  27812. }
  27813. clone() {
  27814. return new this.constructor().copy(this);
  27815. }
  27816. copy(box) {
  27817. this.min.copy(box.min);
  27818. this.max.copy(box.max);
  27819. return this;
  27820. }
  27821. makeEmpty() {
  27822. this.min.x = this.min.y = +Infinity;
  27823. this.max.x = this.max.y = -Infinity;
  27824. return this;
  27825. }
  27826. isEmpty() {
  27827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27828. return this.max.x < this.min.x || this.max.y < this.min.y;
  27829. }
  27830. getCenter(target) {
  27831. if (target === undefined) {
  27832. console.warn('THREE.Box2: .getCenter() target is now required');
  27833. target = new Vector2();
  27834. }
  27835. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27836. }
  27837. getSize(target) {
  27838. if (target === undefined) {
  27839. console.warn('THREE.Box2: .getSize() target is now required');
  27840. target = new Vector2();
  27841. }
  27842. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27843. }
  27844. expandByPoint(point) {
  27845. this.min.min(point);
  27846. this.max.max(point);
  27847. return this;
  27848. }
  27849. expandByVector(vector) {
  27850. this.min.sub(vector);
  27851. this.max.add(vector);
  27852. return this;
  27853. }
  27854. expandByScalar(scalar) {
  27855. this.min.addScalar(-scalar);
  27856. this.max.addScalar(scalar);
  27857. return this;
  27858. }
  27859. containsPoint(point) {
  27860. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27861. }
  27862. containsBox(box) {
  27863. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  27864. }
  27865. getParameter(point, target) {
  27866. // This can potentially have a divide by zero if the box
  27867. // has a size dimension of 0.
  27868. if (target === undefined) {
  27869. console.warn('THREE.Box2: .getParameter() target is now required');
  27870. target = new Vector2();
  27871. }
  27872. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  27873. }
  27874. intersectsBox(box) {
  27875. // using 4 splitting planes to rule out intersections
  27876. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27877. }
  27878. clampPoint(point, target) {
  27879. if (target === undefined) {
  27880. console.warn('THREE.Box2: .clampPoint() target is now required');
  27881. target = new Vector2();
  27882. }
  27883. return target.copy(point).clamp(this.min, this.max);
  27884. }
  27885. distanceToPoint(point) {
  27886. const clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  27887. return clampedPoint.sub(point).length();
  27888. }
  27889. intersect(box) {
  27890. this.min.max(box.min);
  27891. this.max.min(box.max);
  27892. return this;
  27893. }
  27894. union(box) {
  27895. this.min.min(box.min);
  27896. this.max.max(box.max);
  27897. return this;
  27898. }
  27899. translate(offset) {
  27900. this.min.add(offset);
  27901. this.max.add(offset);
  27902. return this;
  27903. }
  27904. equals(box) {
  27905. return box.min.equals(this.min) && box.max.equals(this.max);
  27906. }
  27907. }
  27908. exports.Box2 = Box2;
  27909. const _startP =
  27910. /*@__PURE__*/
  27911. new Vector3();
  27912. const _startEnd =
  27913. /*@__PURE__*/
  27914. new Vector3();
  27915. class Line3 {
  27916. constructor(start, end) {
  27917. this.start = start !== undefined ? start : new Vector3();
  27918. this.end = end !== undefined ? end : new Vector3();
  27919. }
  27920. set(start, end) {
  27921. this.start.copy(start);
  27922. this.end.copy(end);
  27923. return this;
  27924. }
  27925. clone() {
  27926. return new this.constructor().copy(this);
  27927. }
  27928. copy(line) {
  27929. this.start.copy(line.start);
  27930. this.end.copy(line.end);
  27931. return this;
  27932. }
  27933. getCenter(target) {
  27934. if (target === undefined) {
  27935. console.warn('THREE.Line3: .getCenter() target is now required');
  27936. target = new Vector3();
  27937. }
  27938. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27939. }
  27940. delta(target) {
  27941. if (target === undefined) {
  27942. console.warn('THREE.Line3: .delta() target is now required');
  27943. target = new Vector3();
  27944. }
  27945. return target.subVectors(this.end, this.start);
  27946. }
  27947. distanceSq() {
  27948. return this.start.distanceToSquared(this.end);
  27949. }
  27950. distance() {
  27951. return this.start.distanceTo(this.end);
  27952. }
  27953. at(t, target) {
  27954. if (target === undefined) {
  27955. console.warn('THREE.Line3: .at() target is now required');
  27956. target = new Vector3();
  27957. }
  27958. return this.delta(target).multiplyScalar(t).add(this.start);
  27959. }
  27960. closestPointToPointParameter(point, clampToLine) {
  27961. _startP.subVectors(point, this.start);
  27962. _startEnd.subVectors(this.end, this.start);
  27963. const startEnd2 = _startEnd.dot(_startEnd);
  27964. const startEnd_startP = _startEnd.dot(_startP);
  27965. let t = startEnd_startP / startEnd2;
  27966. if (clampToLine) {
  27967. t = MathUtils.clamp(t, 0, 1);
  27968. }
  27969. return t;
  27970. }
  27971. closestPointToPoint(point, clampToLine, target) {
  27972. const t = this.closestPointToPointParameter(point, clampToLine);
  27973. if (target === undefined) {
  27974. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27975. target = new Vector3();
  27976. }
  27977. return this.delta(target).multiplyScalar(t).add(this.start);
  27978. }
  27979. applyMatrix4(matrix) {
  27980. this.start.applyMatrix4(matrix);
  27981. this.end.applyMatrix4(matrix);
  27982. return this;
  27983. }
  27984. equals(line) {
  27985. return line.start.equals(this.start) && line.end.equals(this.end);
  27986. }
  27987. }
  27988. exports.Line3 = Line3;
  27989. function ImmediateRenderObject(material) {
  27990. Object3D.call(this);
  27991. this.material = material;
  27992. this.render = function ()
  27993. /* renderCallback */
  27994. {};
  27995. this.hasPositions = false;
  27996. this.hasNormals = false;
  27997. this.hasColors = false;
  27998. this.hasUvs = false;
  27999. this.positionArray = null;
  28000. this.normalArray = null;
  28001. this.colorArray = null;
  28002. this.uvArray = null;
  28003. this.count = 0;
  28004. }
  28005. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28006. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28007. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28008. const _vector$8 =
  28009. /*@__PURE__*/
  28010. new Vector3();
  28011. class SpotLightHelper extends Object3D {
  28012. constructor(light, color) {
  28013. super();
  28014. this.light = light;
  28015. this.light.updateMatrixWorld();
  28016. this.matrix = light.matrixWorld;
  28017. this.matrixAutoUpdate = false;
  28018. this.color = color;
  28019. const geometry = new BufferGeometry();
  28020. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  28021. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  28022. const p1 = i / l * Math.PI * 2;
  28023. const p2 = j / l * Math.PI * 2;
  28024. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28025. }
  28026. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28027. const material = new LineBasicMaterial({
  28028. fog: false,
  28029. toneMapped: false
  28030. });
  28031. this.cone = new LineSegments(geometry, material);
  28032. this.add(this.cone);
  28033. this.update();
  28034. }
  28035. dispose() {
  28036. this.cone.geometry.dispose();
  28037. this.cone.material.dispose();
  28038. }
  28039. update() {
  28040. this.light.updateMatrixWorld();
  28041. const coneLength = this.light.distance ? this.light.distance : 1000;
  28042. const coneWidth = coneLength * Math.tan(this.light.angle);
  28043. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28044. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  28045. this.cone.lookAt(_vector$8);
  28046. if (this.color !== undefined) {
  28047. this.cone.material.color.set(this.color);
  28048. } else {
  28049. this.cone.material.color.copy(this.light.color);
  28050. }
  28051. }
  28052. }
  28053. exports.SpotLightHelper = SpotLightHelper;
  28054. const _vector$9 =
  28055. /*@__PURE__*/
  28056. new Vector3();
  28057. const _boneMatrix =
  28058. /*@__PURE__*/
  28059. new Matrix4();
  28060. const _matrixWorldInv =
  28061. /*@__PURE__*/
  28062. new Matrix4();
  28063. class SkeletonHelper extends LineSegments {
  28064. constructor(object) {
  28065. const bones = getBoneList(object);
  28066. const geometry = new BufferGeometry();
  28067. const vertices = [];
  28068. const colors = [];
  28069. const color1 = new Color(0, 0, 1);
  28070. const color2 = new Color(0, 1, 0);
  28071. for (let i = 0; i < bones.length; i++) {
  28072. const bone = bones[i];
  28073. if (bone.parent && bone.parent.isBone) {
  28074. vertices.push(0, 0, 0);
  28075. vertices.push(0, 0, 0);
  28076. colors.push(color1.r, color1.g, color1.b);
  28077. colors.push(color2.r, color2.g, color2.b);
  28078. }
  28079. }
  28080. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28081. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28082. const material = new LineBasicMaterial({
  28083. vertexColors: true,
  28084. depthTest: false,
  28085. depthWrite: false,
  28086. toneMapped: false,
  28087. transparent: true
  28088. });
  28089. super(geometry, material);
  28090. this.type = 'SkeletonHelper';
  28091. this.isSkeletonHelper = true;
  28092. this.root = object;
  28093. this.bones = bones;
  28094. this.matrix = object.matrixWorld;
  28095. this.matrixAutoUpdate = false;
  28096. }
  28097. updateMatrixWorld(force) {
  28098. const bones = this.bones;
  28099. const geometry = this.geometry;
  28100. const position = geometry.getAttribute('position');
  28101. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  28102. for (let i = 0, j = 0; i < bones.length; i++) {
  28103. const bone = bones[i];
  28104. if (bone.parent && bone.parent.isBone) {
  28105. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28106. _vector$9.setFromMatrixPosition(_boneMatrix);
  28107. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  28108. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28109. _vector$9.setFromMatrixPosition(_boneMatrix);
  28110. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  28111. j += 2;
  28112. }
  28113. }
  28114. geometry.getAttribute('position').needsUpdate = true;
  28115. super.updateMatrixWorld(force);
  28116. }
  28117. }
  28118. exports.SkeletonHelper = SkeletonHelper;
  28119. function getBoneList(object) {
  28120. const boneList = [];
  28121. if (object && object.isBone) {
  28122. boneList.push(object);
  28123. }
  28124. for (let i = 0; i < object.children.length; i++) {
  28125. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28126. }
  28127. return boneList;
  28128. }
  28129. class PointLightHelper extends Mesh {
  28130. constructor(light, sphereSize, color) {
  28131. const geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28132. const material = new MeshBasicMaterial({
  28133. wireframe: true,
  28134. fog: false,
  28135. toneMapped: false
  28136. });
  28137. super(geometry, material);
  28138. this.light = light;
  28139. this.light.updateMatrixWorld();
  28140. this.color = color;
  28141. this.type = 'PointLightHelper';
  28142. this.matrix = this.light.matrixWorld;
  28143. this.matrixAutoUpdate = false;
  28144. this.update();
  28145. /*
  28146. // TODO: delete this comment?
  28147. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28148. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28149. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28150. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28151. const d = light.distance;
  28152. if ( d === 0.0 ) {
  28153. this.lightDistance.visible = false;
  28154. } else {
  28155. this.lightDistance.scale.set( d, d, d );
  28156. }
  28157. this.add( this.lightDistance );
  28158. */
  28159. }
  28160. dispose() {
  28161. this.geometry.dispose();
  28162. this.material.dispose();
  28163. }
  28164. update() {
  28165. if (this.color !== undefined) {
  28166. this.material.color.set(this.color);
  28167. } else {
  28168. this.material.color.copy(this.light.color);
  28169. }
  28170. /*
  28171. const d = this.light.distance;
  28172. if ( d === 0.0 ) {
  28173. this.lightDistance.visible = false;
  28174. } else {
  28175. this.lightDistance.visible = true;
  28176. this.lightDistance.scale.set( d, d, d );
  28177. }
  28178. */
  28179. }
  28180. }
  28181. exports.PointLightHelper = PointLightHelper;
  28182. const _vector$a =
  28183. /*@__PURE__*/
  28184. new Vector3();
  28185. const _color1 =
  28186. /*@__PURE__*/
  28187. new Color();
  28188. const _color2 =
  28189. /*@__PURE__*/
  28190. new Color();
  28191. class HemisphereLightHelper extends Object3D {
  28192. constructor(light, size, color) {
  28193. super();
  28194. this.light = light;
  28195. this.light.updateMatrixWorld();
  28196. this.matrix = light.matrixWorld;
  28197. this.matrixAutoUpdate = false;
  28198. this.color = color;
  28199. const geometry = new OctahedronBufferGeometry(size);
  28200. geometry.rotateY(Math.PI * 0.5);
  28201. this.material = new MeshBasicMaterial({
  28202. wireframe: true,
  28203. fog: false,
  28204. toneMapped: false
  28205. });
  28206. if (this.color === undefined) this.material.vertexColors = true;
  28207. const position = geometry.getAttribute('position');
  28208. const colors = new Float32Array(position.count * 3);
  28209. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  28210. this.add(new Mesh(geometry, this.material));
  28211. this.update();
  28212. }
  28213. dispose() {
  28214. this.children[0].geometry.dispose();
  28215. this.children[0].material.dispose();
  28216. }
  28217. update() {
  28218. const mesh = this.children[0];
  28219. if (this.color !== undefined) {
  28220. this.material.color.set(this.color);
  28221. } else {
  28222. const colors = mesh.geometry.getAttribute('color');
  28223. _color1.copy(this.light.color);
  28224. _color2.copy(this.light.groundColor);
  28225. for (let i = 0, l = colors.count; i < l; i++) {
  28226. const color = i < l / 2 ? _color1 : _color2;
  28227. colors.setXYZ(i, color.r, color.g, color.b);
  28228. }
  28229. colors.needsUpdate = true;
  28230. }
  28231. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  28232. }
  28233. }
  28234. exports.HemisphereLightHelper = HemisphereLightHelper;
  28235. class GridHelper extends LineSegments {
  28236. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  28237. color1 = new Color(color1);
  28238. color2 = new Color(color2);
  28239. const center = divisions / 2;
  28240. const step = size / divisions;
  28241. const halfSize = size / 2;
  28242. const vertices = [],
  28243. colors = [];
  28244. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28245. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28246. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28247. const color = i === center ? color1 : color2;
  28248. color.toArray(colors, j);
  28249. j += 3;
  28250. color.toArray(colors, j);
  28251. j += 3;
  28252. color.toArray(colors, j);
  28253. j += 3;
  28254. color.toArray(colors, j);
  28255. j += 3;
  28256. }
  28257. const geometry = new BufferGeometry();
  28258. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28259. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28260. const material = new LineBasicMaterial({
  28261. vertexColors: true,
  28262. toneMapped: false
  28263. });
  28264. super(geometry, material);
  28265. this.type = 'GridHelper';
  28266. }
  28267. }
  28268. exports.GridHelper = GridHelper;
  28269. class PolarGridHelper extends LineSegments {
  28270. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  28271. color1 = new Color(color1);
  28272. color2 = new Color(color2);
  28273. const vertices = [];
  28274. const colors = []; // create the radials
  28275. for (let i = 0; i <= radials; i++) {
  28276. const v = i / radials * (Math.PI * 2);
  28277. const x = Math.sin(v) * radius;
  28278. const z = Math.cos(v) * radius;
  28279. vertices.push(0, 0, 0);
  28280. vertices.push(x, 0, z);
  28281. const color = i & 1 ? color1 : color2;
  28282. colors.push(color.r, color.g, color.b);
  28283. colors.push(color.r, color.g, color.b);
  28284. } // create the circles
  28285. for (let i = 0; i <= circles; i++) {
  28286. const color = i & 1 ? color1 : color2;
  28287. const r = radius - radius / circles * i;
  28288. for (let j = 0; j < divisions; j++) {
  28289. // first vertex
  28290. let v = j / divisions * (Math.PI * 2);
  28291. let x = Math.sin(v) * r;
  28292. let z = Math.cos(v) * r;
  28293. vertices.push(x, 0, z);
  28294. colors.push(color.r, color.g, color.b); // second vertex
  28295. v = (j + 1) / divisions * (Math.PI * 2);
  28296. x = Math.sin(v) * r;
  28297. z = Math.cos(v) * r;
  28298. vertices.push(x, 0, z);
  28299. colors.push(color.r, color.g, color.b);
  28300. }
  28301. }
  28302. const geometry = new BufferGeometry();
  28303. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28304. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28305. const material = new LineBasicMaterial({
  28306. vertexColors: true,
  28307. toneMapped: false
  28308. });
  28309. super(geometry, material);
  28310. this.type = 'PolarGridHelper';
  28311. }
  28312. }
  28313. exports.PolarGridHelper = PolarGridHelper;
  28314. const _v1$6 =
  28315. /*@__PURE__*/
  28316. new Vector3();
  28317. const _v2$3 =
  28318. /*@__PURE__*/
  28319. new Vector3();
  28320. const _v3$1 =
  28321. /*@__PURE__*/
  28322. new Vector3();
  28323. class DirectionalLightHelper extends Object3D {
  28324. constructor(light, size, color) {
  28325. super();
  28326. this.light = light;
  28327. this.light.updateMatrixWorld();
  28328. this.matrix = light.matrixWorld;
  28329. this.matrixAutoUpdate = false;
  28330. this.color = color;
  28331. if (size === undefined) size = 1;
  28332. let geometry = new BufferGeometry();
  28333. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28334. const material = new LineBasicMaterial({
  28335. fog: false,
  28336. toneMapped: false
  28337. });
  28338. this.lightPlane = new Line(geometry, material);
  28339. this.add(this.lightPlane);
  28340. geometry = new BufferGeometry();
  28341. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28342. this.targetLine = new Line(geometry, material);
  28343. this.add(this.targetLine);
  28344. this.update();
  28345. }
  28346. dispose() {
  28347. this.lightPlane.geometry.dispose();
  28348. this.lightPlane.material.dispose();
  28349. this.targetLine.geometry.dispose();
  28350. this.targetLine.material.dispose();
  28351. }
  28352. update() {
  28353. _v1$6.setFromMatrixPosition(this.light.matrixWorld);
  28354. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  28355. _v3$1.subVectors(_v2$3, _v1$6);
  28356. this.lightPlane.lookAt(_v2$3);
  28357. if (this.color !== undefined) {
  28358. this.lightPlane.material.color.set(this.color);
  28359. this.targetLine.material.color.set(this.color);
  28360. } else {
  28361. this.lightPlane.material.color.copy(this.light.color);
  28362. this.targetLine.material.color.copy(this.light.color);
  28363. }
  28364. this.targetLine.lookAt(_v2$3);
  28365. this.targetLine.scale.z = _v3$1.length();
  28366. }
  28367. }
  28368. exports.DirectionalLightHelper = DirectionalLightHelper;
  28369. const _vector$b =
  28370. /*@__PURE__*/
  28371. new Vector3();
  28372. const _camera =
  28373. /*@__PURE__*/
  28374. new Camera();
  28375. /**
  28376. * - shows frustum, line of sight and up of the camera
  28377. * - suitable for fast updates
  28378. * - based on frustum visualization in lightgl.js shadowmap example
  28379. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28380. */
  28381. class CameraHelper extends LineSegments {
  28382. constructor(camera) {
  28383. const geometry = new BufferGeometry();
  28384. const material = new LineBasicMaterial({
  28385. color: 0xffffff,
  28386. vertexColors: true,
  28387. toneMapped: false
  28388. });
  28389. const vertices = [];
  28390. const colors = [];
  28391. const pointMap = {}; // colors
  28392. const colorFrustum = new Color(0xffaa00);
  28393. const colorCone = new Color(0xff0000);
  28394. const colorUp = new Color(0x00aaff);
  28395. const colorTarget = new Color(0xffffff);
  28396. const colorCross = new Color(0x333333); // near
  28397. addLine('n1', 'n2', colorFrustum);
  28398. addLine('n2', 'n4', colorFrustum);
  28399. addLine('n4', 'n3', colorFrustum);
  28400. addLine('n3', 'n1', colorFrustum); // far
  28401. addLine('f1', 'f2', colorFrustum);
  28402. addLine('f2', 'f4', colorFrustum);
  28403. addLine('f4', 'f3', colorFrustum);
  28404. addLine('f3', 'f1', colorFrustum); // sides
  28405. addLine('n1', 'f1', colorFrustum);
  28406. addLine('n2', 'f2', colorFrustum);
  28407. addLine('n3', 'f3', colorFrustum);
  28408. addLine('n4', 'f4', colorFrustum); // cone
  28409. addLine('p', 'n1', colorCone);
  28410. addLine('p', 'n2', colorCone);
  28411. addLine('p', 'n3', colorCone);
  28412. addLine('p', 'n4', colorCone); // up
  28413. addLine('u1', 'u2', colorUp);
  28414. addLine('u2', 'u3', colorUp);
  28415. addLine('u3', 'u1', colorUp); // target
  28416. addLine('c', 't', colorTarget);
  28417. addLine('p', 'c', colorCross); // cross
  28418. addLine('cn1', 'cn2', colorCross);
  28419. addLine('cn3', 'cn4', colorCross);
  28420. addLine('cf1', 'cf2', colorCross);
  28421. addLine('cf3', 'cf4', colorCross);
  28422. function addLine(a, b, color) {
  28423. addPoint(a, color);
  28424. addPoint(b, color);
  28425. }
  28426. function addPoint(id, color) {
  28427. vertices.push(0, 0, 0);
  28428. colors.push(color.r, color.g, color.b);
  28429. if (pointMap[id] === undefined) {
  28430. pointMap[id] = [];
  28431. }
  28432. pointMap[id].push(vertices.length / 3 - 1);
  28433. }
  28434. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28435. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28436. super(geometry, material);
  28437. this.type = 'CameraHelper';
  28438. this.camera = camera;
  28439. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28440. this.matrix = camera.matrixWorld;
  28441. this.matrixAutoUpdate = false;
  28442. this.pointMap = pointMap;
  28443. this.update();
  28444. }
  28445. update() {
  28446. const geometry = this.geometry;
  28447. const pointMap = this.pointMap;
  28448. const w = 1,
  28449. h = 1; // we need just camera projection matrix inverse
  28450. // world matrix must be identity
  28451. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28452. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28453. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28454. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28455. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28456. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28457. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28458. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28459. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28460. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28461. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28462. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28463. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28464. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28465. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28466. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28467. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28468. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28469. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28470. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28471. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28472. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28473. geometry.getAttribute('position').needsUpdate = true;
  28474. }
  28475. }
  28476. exports.CameraHelper = CameraHelper;
  28477. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28478. _vector$b.set(x, y, z).unproject(camera);
  28479. const points = pointMap[point];
  28480. if (points !== undefined) {
  28481. const position = geometry.getAttribute('position');
  28482. for (let i = 0, l = points.length; i < l; i++) {
  28483. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  28484. }
  28485. }
  28486. }
  28487. const _box$3 =
  28488. /*@__PURE__*/
  28489. new Box3();
  28490. class BoxHelper extends LineSegments {
  28491. constructor(object, color = 0xffff00) {
  28492. 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]);
  28493. const positions = new Float32Array(8 * 3);
  28494. const geometry = new BufferGeometry();
  28495. geometry.setIndex(new BufferAttribute(indices, 1));
  28496. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28497. super(geometry, new LineBasicMaterial({
  28498. color: color,
  28499. toneMapped: false
  28500. }));
  28501. this.object = object;
  28502. this.type = 'BoxHelper';
  28503. this.matrixAutoUpdate = false;
  28504. this.update();
  28505. }
  28506. update(object) {
  28507. if (object !== undefined) {
  28508. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28509. }
  28510. if (this.object !== undefined) {
  28511. _box$3.setFromObject(this.object);
  28512. }
  28513. if (_box$3.isEmpty()) return;
  28514. const min = _box$3.min;
  28515. const max = _box$3.max;
  28516. /*
  28517. 5____4
  28518. 1/___0/|
  28519. | 6__|_7
  28520. 2/___3/
  28521. 0: max.x, max.y, max.z
  28522. 1: min.x, max.y, max.z
  28523. 2: min.x, min.y, max.z
  28524. 3: max.x, min.y, max.z
  28525. 4: max.x, max.y, min.z
  28526. 5: min.x, max.y, min.z
  28527. 6: min.x, min.y, min.z
  28528. 7: max.x, min.y, min.z
  28529. */
  28530. const position = this.geometry.attributes.position;
  28531. const array = position.array;
  28532. array[0] = max.x;
  28533. array[1] = max.y;
  28534. array[2] = max.z;
  28535. array[3] = min.x;
  28536. array[4] = max.y;
  28537. array[5] = max.z;
  28538. array[6] = min.x;
  28539. array[7] = min.y;
  28540. array[8] = max.z;
  28541. array[9] = max.x;
  28542. array[10] = min.y;
  28543. array[11] = max.z;
  28544. array[12] = max.x;
  28545. array[13] = max.y;
  28546. array[14] = min.z;
  28547. array[15] = min.x;
  28548. array[16] = max.y;
  28549. array[17] = min.z;
  28550. array[18] = min.x;
  28551. array[19] = min.y;
  28552. array[20] = min.z;
  28553. array[21] = max.x;
  28554. array[22] = min.y;
  28555. array[23] = min.z;
  28556. position.needsUpdate = true;
  28557. this.geometry.computeBoundingSphere();
  28558. }
  28559. setFromObject(object) {
  28560. this.object = object;
  28561. this.update();
  28562. return this;
  28563. }
  28564. copy(source) {
  28565. LineSegments.prototype.copy.call(this, source);
  28566. this.object = source.object;
  28567. return this;
  28568. }
  28569. }
  28570. exports.BoxHelper = BoxHelper;
  28571. class Box3Helper extends LineSegments {
  28572. constructor(box, color = 0xffff00) {
  28573. 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]);
  28574. 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];
  28575. const geometry = new BufferGeometry();
  28576. geometry.setIndex(new BufferAttribute(indices, 1));
  28577. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28578. super(geometry, new LineBasicMaterial({
  28579. color: color,
  28580. toneMapped: false
  28581. }));
  28582. this.box = box;
  28583. this.type = 'Box3Helper';
  28584. this.geometry.computeBoundingSphere();
  28585. }
  28586. updateMatrixWorld(force) {
  28587. const box = this.box;
  28588. if (box.isEmpty()) return;
  28589. box.getCenter(this.position);
  28590. box.getSize(this.scale);
  28591. this.scale.multiplyScalar(0.5);
  28592. super.updateMatrixWorld(force);
  28593. }
  28594. }
  28595. exports.Box3Helper = Box3Helper;
  28596. class PlaneHelper extends Line {
  28597. constructor(plane, size = 1, hex = 0xffff00) {
  28598. const color = hex;
  28599. 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];
  28600. const geometry = new BufferGeometry();
  28601. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28602. geometry.computeBoundingSphere();
  28603. super(geometry, new LineBasicMaterial({
  28604. color: color,
  28605. toneMapped: false
  28606. }));
  28607. this.type = 'PlaneHelper';
  28608. this.plane = plane;
  28609. this.size = size;
  28610. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  28611. const geometry2 = new BufferGeometry();
  28612. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28613. geometry2.computeBoundingSphere();
  28614. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28615. color: color,
  28616. opacity: 0.2,
  28617. transparent: true,
  28618. depthWrite: false,
  28619. toneMapped: false
  28620. })));
  28621. }
  28622. updateMatrixWorld(force) {
  28623. let scale = -this.plane.constant;
  28624. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  28625. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  28626. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28627. this.lookAt(this.plane.normal);
  28628. super.updateMatrixWorld(force);
  28629. }
  28630. }
  28631. exports.PlaneHelper = PlaneHelper;
  28632. const _axis =
  28633. /*@__PURE__*/
  28634. new Vector3();
  28635. let _lineGeometry, _coneGeometry;
  28636. class ArrowHelper extends Object3D {
  28637. constructor(dir, origin, length, color, headLength, headWidth) {
  28638. super(); // dir is assumed to be normalized
  28639. this.type = 'ArrowHelper';
  28640. if (dir === undefined) dir = new Vector3(0, 0, 1);
  28641. if (origin === undefined) origin = new Vector3(0, 0, 0);
  28642. if (length === undefined) length = 1;
  28643. if (color === undefined) color = 0xffff00;
  28644. if (headLength === undefined) headLength = 0.2 * length;
  28645. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28646. if (_lineGeometry === undefined) {
  28647. _lineGeometry = new BufferGeometry();
  28648. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28649. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  28650. _coneGeometry.translate(0, -0.5, 0);
  28651. }
  28652. this.position.copy(origin);
  28653. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28654. color: color,
  28655. toneMapped: false
  28656. }));
  28657. this.line.matrixAutoUpdate = false;
  28658. this.add(this.line);
  28659. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28660. color: color,
  28661. toneMapped: false
  28662. }));
  28663. this.cone.matrixAutoUpdate = false;
  28664. this.add(this.cone);
  28665. this.setDirection(dir);
  28666. this.setLength(length, headLength, headWidth);
  28667. }
  28668. setDirection(dir) {
  28669. // dir is assumed to be normalized
  28670. if (dir.y > 0.99999) {
  28671. this.quaternion.set(0, 0, 0, 1);
  28672. } else if (dir.y < -0.99999) {
  28673. this.quaternion.set(1, 0, 0, 0);
  28674. } else {
  28675. _axis.set(dir.z, 0, -dir.x).normalize();
  28676. const radians = Math.acos(dir.y);
  28677. this.quaternion.setFromAxisAngle(_axis, radians);
  28678. }
  28679. }
  28680. setLength(length, headLength, headWidth) {
  28681. if (headLength === undefined) headLength = 0.2 * length;
  28682. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28683. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28684. this.line.updateMatrix();
  28685. this.cone.scale.set(headWidth, headLength, headWidth);
  28686. this.cone.position.y = length;
  28687. this.cone.updateMatrix();
  28688. }
  28689. setColor(color) {
  28690. this.line.material.color.set(color);
  28691. this.cone.material.color.set(color);
  28692. }
  28693. copy(source) {
  28694. super.copy(source, false);
  28695. this.line.copy(source.line);
  28696. this.cone.copy(source.cone);
  28697. return this;
  28698. }
  28699. }
  28700. exports.ArrowHelper = ArrowHelper;
  28701. class AxesHelper extends LineSegments {
  28702. constructor(size = 1) {
  28703. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28704. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28705. const geometry = new BufferGeometry();
  28706. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28707. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28708. const material = new LineBasicMaterial({
  28709. vertexColors: true,
  28710. toneMapped: false
  28711. });
  28712. super(geometry, material);
  28713. this.type = 'AxesHelper';
  28714. }
  28715. }
  28716. exports.AxesHelper = AxesHelper;
  28717. const _floatView = new Float32Array(1);
  28718. const _int32View = new Int32Array(_floatView.buffer);
  28719. const DataUtils = {
  28720. // Converts float32 to float16 (stored as uint16 value).
  28721. toHalfFloat: function (val) {
  28722. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28723. /* This method is faster than the OpenEXR implementation (very often
  28724. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28725. * by James Tursa?s half-precision code. */
  28726. _floatView[0] = val;
  28727. const x = _int32View[0];
  28728. let bits = x >> 16 & 0x8000;
  28729. /* Get the sign */
  28730. let m = x >> 12 & 0x07ff;
  28731. /* Keep one extra bit for rounding */
  28732. const e = x >> 23 & 0xff;
  28733. /* Using int is faster here */
  28734. /* If zero, or denormal, or exponent underflows too much for a denormal
  28735. * half, return signed zero. */
  28736. if (e < 103) return bits;
  28737. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28738. if (e > 142) {
  28739. bits |= 0x7c00;
  28740. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28741. * not Inf, so make sure we set one mantissa bit too. */
  28742. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  28743. return bits;
  28744. }
  28745. /* If exponent underflows but not too much, return a denormal */
  28746. if (e < 113) {
  28747. m |= 0x0800;
  28748. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28749. * to 1, which is OK. */
  28750. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  28751. return bits;
  28752. }
  28753. bits |= e - 112 << 10 | m >> 1;
  28754. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28755. * the exponent, which is OK. */
  28756. bits += m & 1;
  28757. return bits;
  28758. }
  28759. };
  28760. exports.DataUtils = DataUtils;
  28761. const LOD_MIN = 4;
  28762. const LOD_MAX = 8;
  28763. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  28764. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28765. // geometric shadowing function. These sigma values squared must match the
  28766. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28767. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  28768. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28769. // samples and exit early, but not recompile the shader.
  28770. const MAX_SAMPLES = 20;
  28771. const ENCODINGS = {
  28772. [LinearEncoding]: 0,
  28773. [sRGBEncoding]: 1,
  28774. [RGBEEncoding]: 2,
  28775. [RGBM7Encoding]: 3,
  28776. [RGBM16Encoding]: 4,
  28777. [RGBDEncoding]: 5,
  28778. [GammaEncoding]: 6
  28779. };
  28780. const _flatCamera =
  28781. /*@__PURE__*/
  28782. new OrthographicCamera();
  28783. const {
  28784. _lodPlanes,
  28785. _sizeLods,
  28786. _sigmas
  28787. } =
  28788. /*@__PURE__*/
  28789. _createPlanes();
  28790. let _oldTarget = null; // Golden Ratio
  28791. const PHI = (1 + Math.sqrt(5)) / 2;
  28792. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  28793. // same axis), used as axis directions evenly spread on a sphere.
  28794. const _axisDirections = [
  28795. /*@__PURE__*/
  28796. new Vector3(1, 1, 1),
  28797. /*@__PURE__*/
  28798. new Vector3(-1, 1, 1),
  28799. /*@__PURE__*/
  28800. new Vector3(1, 1, -1),
  28801. /*@__PURE__*/
  28802. new Vector3(-1, 1, -1),
  28803. /*@__PURE__*/
  28804. new Vector3(0, PHI, INV_PHI),
  28805. /*@__PURE__*/
  28806. new Vector3(0, PHI, -INV_PHI),
  28807. /*@__PURE__*/
  28808. new Vector3(INV_PHI, 0, PHI),
  28809. /*@__PURE__*/
  28810. new Vector3(-INV_PHI, 0, PHI),
  28811. /*@__PURE__*/
  28812. new Vector3(PHI, INV_PHI, 0),
  28813. /*@__PURE__*/
  28814. new Vector3(-PHI, INV_PHI, 0)];
  28815. /**
  28816. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28817. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28818. * blur to be quickly accessed based on material roughness. It is packed into a
  28819. * special CubeUV format that allows us to perform custom interpolation so that
  28820. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28821. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28822. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28823. * higher roughness levels. In this way we maintain resolution to smoothly
  28824. * interpolate diffuse lighting while limiting sampling computation.
  28825. */
  28826. class PMREMGenerator {
  28827. constructor(renderer) {
  28828. this._renderer = renderer;
  28829. this._pingPongRenderTarget = null;
  28830. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  28831. this._equirectShader = null;
  28832. this._cubemapShader = null;
  28833. this._compileMaterial(this._blurMaterial);
  28834. }
  28835. /**
  28836. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28837. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28838. * in radians to be applied to the scene before PMREM generation. Optional near
  28839. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28840. * is placed at the origin).
  28841. */
  28842. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  28843. _oldTarget = this._renderer.getRenderTarget();
  28844. const cubeUVRenderTarget = this._allocateTargets();
  28845. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  28846. if (sigma > 0) {
  28847. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  28848. }
  28849. this._applyPMREM(cubeUVRenderTarget);
  28850. this._cleanup(cubeUVRenderTarget);
  28851. return cubeUVRenderTarget;
  28852. }
  28853. /**
  28854. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28855. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28856. * as this matches best with the 256 x 256 cubemap output.
  28857. */
  28858. fromEquirectangular(equirectangular) {
  28859. return this._fromTexture(equirectangular);
  28860. }
  28861. /**
  28862. * Generates a PMREM from an cubemap texture, which can be either LDR
  28863. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28864. * as this matches best with the 256 x 256 cubemap output.
  28865. */
  28866. fromCubemap(cubemap) {
  28867. return this._fromTexture(cubemap);
  28868. }
  28869. /**
  28870. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28871. * your texture's network fetch for increased concurrency.
  28872. */
  28873. compileCubemapShader() {
  28874. if (this._cubemapShader === null) {
  28875. this._cubemapShader = _getCubemapShader();
  28876. this._compileMaterial(this._cubemapShader);
  28877. }
  28878. }
  28879. /**
  28880. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28881. * your texture's network fetch for increased concurrency.
  28882. */
  28883. compileEquirectangularShader() {
  28884. if (this._equirectShader === null) {
  28885. this._equirectShader = _getEquirectShader();
  28886. this._compileMaterial(this._equirectShader);
  28887. }
  28888. }
  28889. /**
  28890. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28891. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28892. * one of them will cause any others to also become unusable.
  28893. */
  28894. dispose() {
  28895. this._blurMaterial.dispose();
  28896. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  28897. if (this._equirectShader !== null) this._equirectShader.dispose();
  28898. for (let i = 0; i < _lodPlanes.length; i++) {
  28899. _lodPlanes[i].dispose();
  28900. }
  28901. } // private interface
  28902. _cleanup(outputTarget) {
  28903. this._pingPongRenderTarget.dispose();
  28904. this._renderer.setRenderTarget(_oldTarget);
  28905. outputTarget.scissorTest = false;
  28906. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  28907. }
  28908. _fromTexture(texture) {
  28909. _oldTarget = this._renderer.getRenderTarget();
  28910. const cubeUVRenderTarget = this._allocateTargets(texture);
  28911. this._textureToCubeUV(texture, cubeUVRenderTarget);
  28912. this._applyPMREM(cubeUVRenderTarget);
  28913. this._cleanup(cubeUVRenderTarget);
  28914. return cubeUVRenderTarget;
  28915. }
  28916. _allocateTargets(texture) {
  28917. // warning: null texture is valid
  28918. const params = {
  28919. magFilter: NearestFilter,
  28920. minFilter: NearestFilter,
  28921. generateMipmaps: false,
  28922. type: UnsignedByteType,
  28923. format: RGBEFormat,
  28924. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  28925. depthBuffer: false
  28926. };
  28927. const cubeUVRenderTarget = _createRenderTarget(params);
  28928. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  28929. this._pingPongRenderTarget = _createRenderTarget(params);
  28930. return cubeUVRenderTarget;
  28931. }
  28932. _compileMaterial(material) {
  28933. const tmpMesh = new Mesh(_lodPlanes[0], material);
  28934. this._renderer.compile(tmpMesh, _flatCamera);
  28935. }
  28936. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  28937. const fov = 90;
  28938. const aspect = 1;
  28939. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  28940. const upSign = [1, -1, 1, 1, 1, 1];
  28941. const forwardSign = [1, 1, 1, -1, -1, -1];
  28942. const renderer = this._renderer;
  28943. const outputEncoding = renderer.outputEncoding;
  28944. const toneMapping = renderer.toneMapping;
  28945. const clearColor = renderer.getClearColor();
  28946. const clearAlpha = renderer.getClearAlpha();
  28947. renderer.toneMapping = NoToneMapping;
  28948. renderer.outputEncoding = LinearEncoding;
  28949. let background = scene.background;
  28950. if (background && background.isColor) {
  28951. background.convertSRGBToLinear(); // Convert linear to RGBE
  28952. const maxComponent = Math.max(background.r, background.g, background.b);
  28953. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  28954. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  28955. const alpha = (fExp + 128.0) / 255.0;
  28956. renderer.setClearColor(background, alpha);
  28957. scene.background = null;
  28958. }
  28959. for (let i = 0; i < 6; i++) {
  28960. const col = i % 3;
  28961. if (col == 0) {
  28962. cubeCamera.up.set(0, upSign[i], 0);
  28963. cubeCamera.lookAt(forwardSign[i], 0, 0);
  28964. } else if (col == 1) {
  28965. cubeCamera.up.set(0, 0, upSign[i]);
  28966. cubeCamera.lookAt(0, forwardSign[i], 0);
  28967. } else {
  28968. cubeCamera.up.set(0, upSign[i], 0);
  28969. cubeCamera.lookAt(0, 0, forwardSign[i]);
  28970. }
  28971. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  28972. renderer.setRenderTarget(cubeUVRenderTarget);
  28973. renderer.render(scene, cubeCamera);
  28974. }
  28975. renderer.toneMapping = toneMapping;
  28976. renderer.outputEncoding = outputEncoding;
  28977. renderer.setClearColor(clearColor, clearAlpha);
  28978. }
  28979. _textureToCubeUV(texture, cubeUVRenderTarget) {
  28980. const renderer = this._renderer;
  28981. if (texture.isCubeTexture) {
  28982. if (this._cubemapShader == null) {
  28983. this._cubemapShader = _getCubemapShader();
  28984. }
  28985. } else {
  28986. if (this._equirectShader == null) {
  28987. this._equirectShader = _getEquirectShader();
  28988. }
  28989. }
  28990. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  28991. const mesh = new Mesh(_lodPlanes[0], material);
  28992. const uniforms = material.uniforms;
  28993. uniforms['envMap'].value = texture;
  28994. if (!texture.isCubeTexture) {
  28995. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  28996. }
  28997. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  28998. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  28999. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  29000. renderer.setRenderTarget(cubeUVRenderTarget);
  29001. renderer.render(mesh, _flatCamera);
  29002. }
  29003. _applyPMREM(cubeUVRenderTarget) {
  29004. const renderer = this._renderer;
  29005. const autoClear = renderer.autoClear;
  29006. renderer.autoClear = false;
  29007. for (let i = 1; i < TOTAL_LODS; i++) {
  29008. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  29009. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  29010. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  29011. }
  29012. renderer.autoClear = autoClear;
  29013. }
  29014. /**
  29015. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29016. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29017. * the blur latitudinally (around the poles), and then longitudinally (towards
  29018. * the poles) to approximate the orthogonally-separable blur. It is least
  29019. * accurate at the poles, but still does a decent job.
  29020. */
  29021. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  29022. const pingPongRenderTarget = this._pingPongRenderTarget;
  29023. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  29024. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  29025. }
  29026. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  29027. const renderer = this._renderer;
  29028. const blurMaterial = this._blurMaterial;
  29029. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  29030. console.error('blur direction must be either latitudinal or longitudinal!');
  29031. } // Number of standard deviations at which to cut off the discrete approximation.
  29032. const STANDARD_DEVIATIONS = 3;
  29033. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  29034. const blurUniforms = blurMaterial.uniforms;
  29035. const pixels = _sizeLods[lodIn] - 1;
  29036. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  29037. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29038. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  29039. if (samples > MAX_SAMPLES) {
  29040. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  29041. }
  29042. const weights = [];
  29043. let sum = 0;
  29044. for (let i = 0; i < MAX_SAMPLES; ++i) {
  29045. const x = i / sigmaPixels;
  29046. const weight = Math.exp(-x * x / 2);
  29047. weights.push(weight);
  29048. if (i == 0) {
  29049. sum += weight;
  29050. } else if (i < samples) {
  29051. sum += 2 * weight;
  29052. }
  29053. }
  29054. for (let i = 0; i < weights.length; i++) {
  29055. weights[i] = weights[i] / sum;
  29056. }
  29057. blurUniforms['envMap'].value = targetIn.texture;
  29058. blurUniforms['samples'].value = samples;
  29059. blurUniforms['weights'].value = weights;
  29060. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  29061. if (poleAxis) {
  29062. blurUniforms['poleAxis'].value = poleAxis;
  29063. }
  29064. blurUniforms['dTheta'].value = radiansPerPixel;
  29065. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  29066. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  29067. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  29068. const outputSize = _sizeLods[lodOut];
  29069. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  29070. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  29071. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  29072. renderer.setRenderTarget(targetOut);
  29073. renderer.render(blurMesh, _flatCamera);
  29074. }
  29075. }
  29076. exports.PMREMGenerator = PMREMGenerator;
  29077. function _isLDR(texture) {
  29078. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  29079. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  29080. }
  29081. function _createPlanes() {
  29082. const _lodPlanes = [];
  29083. const _sizeLods = [];
  29084. const _sigmas = [];
  29085. let lod = LOD_MAX;
  29086. for (let i = 0; i < TOTAL_LODS; i++) {
  29087. const sizeLod = Math.pow(2, lod);
  29088. _sizeLods.push(sizeLod);
  29089. let sigma = 1.0 / sizeLod;
  29090. if (i > LOD_MAX - LOD_MIN) {
  29091. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  29092. } else if (i == 0) {
  29093. sigma = 0;
  29094. }
  29095. _sigmas.push(sigma);
  29096. const texelSize = 1.0 / (sizeLod - 1);
  29097. const min = -texelSize / 2;
  29098. const max = 1 + texelSize / 2;
  29099. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  29100. const cubeFaces = 6;
  29101. const vertices = 6;
  29102. const positionSize = 3;
  29103. const uvSize = 2;
  29104. const faceIndexSize = 1;
  29105. const position = new Float32Array(positionSize * vertices * cubeFaces);
  29106. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  29107. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  29108. for (let face = 0; face < cubeFaces; face++) {
  29109. const x = face % 3 * 2 / 3 - 1;
  29110. const y = face > 2 ? 0 : -1;
  29111. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  29112. position.set(coordinates, positionSize * vertices * face);
  29113. uv.set(uv1, uvSize * vertices * face);
  29114. const fill = [face, face, face, face, face, face];
  29115. faceIndex.set(fill, faceIndexSize * vertices * face);
  29116. }
  29117. const planes = new BufferGeometry();
  29118. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  29119. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  29120. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  29121. _lodPlanes.push(planes);
  29122. if (lod > LOD_MIN) {
  29123. lod--;
  29124. }
  29125. }
  29126. return {
  29127. _lodPlanes,
  29128. _sizeLods,
  29129. _sigmas
  29130. };
  29131. }
  29132. function _createRenderTarget(params) {
  29133. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  29134. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29135. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29136. cubeUVRenderTarget.scissorTest = true;
  29137. return cubeUVRenderTarget;
  29138. }
  29139. function _setViewport(target, x, y, width, height) {
  29140. target.viewport.set(x, y, width, height);
  29141. target.scissor.set(x, y, width, height);
  29142. }
  29143. function _getBlurShader(maxSamples) {
  29144. const weights = new Float32Array(maxSamples);
  29145. const poleAxis = new Vector3(0, 1, 0);
  29146. const shaderMaterial = new RawShaderMaterial({
  29147. name: 'SphericalGaussianBlur',
  29148. defines: {
  29149. 'n': maxSamples
  29150. },
  29151. uniforms: {
  29152. 'envMap': {
  29153. value: null
  29154. },
  29155. 'samples': {
  29156. value: 1
  29157. },
  29158. 'weights': {
  29159. value: weights
  29160. },
  29161. 'latitudinal': {
  29162. value: false
  29163. },
  29164. 'dTheta': {
  29165. value: 0
  29166. },
  29167. 'mipInt': {
  29168. value: 0
  29169. },
  29170. 'poleAxis': {
  29171. value: poleAxis
  29172. },
  29173. 'inputEncoding': {
  29174. value: ENCODINGS[LinearEncoding]
  29175. },
  29176. 'outputEncoding': {
  29177. value: ENCODINGS[LinearEncoding]
  29178. }
  29179. },
  29180. vertexShader: _getCommonVertexShader(),
  29181. fragmentShader:
  29182. /* glsl */
  29183. `
  29184. precision mediump float;
  29185. precision mediump int;
  29186. varying vec3 vOutputDirection;
  29187. uniform sampler2D envMap;
  29188. uniform int samples;
  29189. uniform float weights[ n ];
  29190. uniform bool latitudinal;
  29191. uniform float dTheta;
  29192. uniform float mipInt;
  29193. uniform vec3 poleAxis;
  29194. ${_getEncodings()}
  29195. #define ENVMAP_TYPE_CUBE_UV
  29196. #include <cube_uv_reflection_fragment>
  29197. vec3 getSample( float theta, vec3 axis ) {
  29198. float cosTheta = cos( theta );
  29199. // Rodrigues' axis-angle rotation
  29200. vec3 sampleDirection = vOutputDirection * cosTheta
  29201. + cross( axis, vOutputDirection ) * sin( theta )
  29202. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29203. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29204. }
  29205. void main() {
  29206. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29207. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29208. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29209. }
  29210. axis = normalize( axis );
  29211. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29212. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29213. for ( int i = 1; i < n; i++ ) {
  29214. if ( i >= samples ) {
  29215. break;
  29216. }
  29217. float theta = dTheta * float( i );
  29218. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29219. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29220. }
  29221. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29222. }
  29223. `,
  29224. blending: NoBlending,
  29225. depthTest: false,
  29226. depthWrite: false
  29227. });
  29228. return shaderMaterial;
  29229. }
  29230. function _getEquirectShader() {
  29231. const texelSize = new Vector2(1, 1);
  29232. const shaderMaterial = new RawShaderMaterial({
  29233. name: 'EquirectangularToCubeUV',
  29234. uniforms: {
  29235. 'envMap': {
  29236. value: null
  29237. },
  29238. 'texelSize': {
  29239. value: texelSize
  29240. },
  29241. 'inputEncoding': {
  29242. value: ENCODINGS[LinearEncoding]
  29243. },
  29244. 'outputEncoding': {
  29245. value: ENCODINGS[LinearEncoding]
  29246. }
  29247. },
  29248. vertexShader: _getCommonVertexShader(),
  29249. fragmentShader:
  29250. /* glsl */
  29251. `
  29252. precision mediump float;
  29253. precision mediump int;
  29254. varying vec3 vOutputDirection;
  29255. uniform sampler2D envMap;
  29256. uniform vec2 texelSize;
  29257. ${_getEncodings()}
  29258. #include <common>
  29259. void main() {
  29260. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29261. vec3 outputDirection = normalize( vOutputDirection );
  29262. vec2 uv = equirectUv( outputDirection );
  29263. vec2 f = fract( uv / texelSize - 0.5 );
  29264. uv -= f * texelSize;
  29265. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29266. uv.x += texelSize.x;
  29267. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29268. uv.y += texelSize.y;
  29269. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29270. uv.x -= texelSize.x;
  29271. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29272. vec3 tm = mix( tl, tr, f.x );
  29273. vec3 bm = mix( bl, br, f.x );
  29274. gl_FragColor.rgb = mix( tm, bm, f.y );
  29275. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29276. }
  29277. `,
  29278. blending: NoBlending,
  29279. depthTest: false,
  29280. depthWrite: false
  29281. });
  29282. return shaderMaterial;
  29283. }
  29284. function _getCubemapShader() {
  29285. const shaderMaterial = new RawShaderMaterial({
  29286. name: 'CubemapToCubeUV',
  29287. uniforms: {
  29288. 'envMap': {
  29289. value: null
  29290. },
  29291. 'inputEncoding': {
  29292. value: ENCODINGS[LinearEncoding]
  29293. },
  29294. 'outputEncoding': {
  29295. value: ENCODINGS[LinearEncoding]
  29296. }
  29297. },
  29298. vertexShader: _getCommonVertexShader(),
  29299. fragmentShader:
  29300. /* glsl */
  29301. `
  29302. precision mediump float;
  29303. precision mediump int;
  29304. varying vec3 vOutputDirection;
  29305. uniform samplerCube envMap;
  29306. ${_getEncodings()}
  29307. void main() {
  29308. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29309. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29310. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29311. }
  29312. `,
  29313. blending: NoBlending,
  29314. depthTest: false,
  29315. depthWrite: false
  29316. });
  29317. return shaderMaterial;
  29318. }
  29319. function _getCommonVertexShader() {
  29320. return (
  29321. /* glsl */
  29322. `
  29323. precision mediump float;
  29324. precision mediump int;
  29325. attribute vec3 position;
  29326. attribute vec2 uv;
  29327. attribute float faceIndex;
  29328. varying vec3 vOutputDirection;
  29329. // RH coordinate system; PMREM face-indexing convention
  29330. vec3 getDirection( vec2 uv, float face ) {
  29331. uv = 2.0 * uv - 1.0;
  29332. vec3 direction = vec3( uv, 1.0 );
  29333. if ( face == 0.0 ) {
  29334. direction = direction.zyx; // ( 1, v, u ) pos x
  29335. } else if ( face == 1.0 ) {
  29336. direction = direction.xzy;
  29337. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29338. } else if ( face == 2.0 ) {
  29339. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29340. } else if ( face == 3.0 ) {
  29341. direction = direction.zyx;
  29342. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29343. } else if ( face == 4.0 ) {
  29344. direction = direction.xzy;
  29345. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29346. } else if ( face == 5.0 ) {
  29347. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29348. }
  29349. return direction;
  29350. }
  29351. void main() {
  29352. vOutputDirection = getDirection( uv, faceIndex );
  29353. gl_Position = vec4( position, 1.0 );
  29354. }
  29355. `
  29356. );
  29357. }
  29358. function _getEncodings() {
  29359. return (
  29360. /* glsl */
  29361. `
  29362. uniform int inputEncoding;
  29363. uniform int outputEncoding;
  29364. #include <encodings_pars_fragment>
  29365. vec4 inputTexelToLinear( vec4 value ) {
  29366. if ( inputEncoding == 0 ) {
  29367. return value;
  29368. } else if ( inputEncoding == 1 ) {
  29369. return sRGBToLinear( value );
  29370. } else if ( inputEncoding == 2 ) {
  29371. return RGBEToLinear( value );
  29372. } else if ( inputEncoding == 3 ) {
  29373. return RGBMToLinear( value, 7.0 );
  29374. } else if ( inputEncoding == 4 ) {
  29375. return RGBMToLinear( value, 16.0 );
  29376. } else if ( inputEncoding == 5 ) {
  29377. return RGBDToLinear( value, 256.0 );
  29378. } else {
  29379. return GammaToLinear( value, 2.2 );
  29380. }
  29381. }
  29382. vec4 linearToOutputTexel( vec4 value ) {
  29383. if ( outputEncoding == 0 ) {
  29384. return value;
  29385. } else if ( outputEncoding == 1 ) {
  29386. return LinearTosRGB( value );
  29387. } else if ( outputEncoding == 2 ) {
  29388. return LinearToRGBE( value );
  29389. } else if ( outputEncoding == 3 ) {
  29390. return LinearToRGBM( value, 7.0 );
  29391. } else if ( outputEncoding == 4 ) {
  29392. return LinearToRGBM( value, 16.0 );
  29393. } else if ( outputEncoding == 5 ) {
  29394. return LinearToRGBD( value, 256.0 );
  29395. } else {
  29396. return LinearToGamma( value, 2.2 );
  29397. }
  29398. }
  29399. vec4 envMapTexelToLinear( vec4 color ) {
  29400. return inputTexelToLinear( color );
  29401. }
  29402. `
  29403. );
  29404. }
  29405. function Face4(a, b, c, d, normal, color, materialIndex) {
  29406. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29407. return new Face3(a, b, c, normal, color, materialIndex);
  29408. }
  29409. const LineStrip = 0;
  29410. exports.LineStrip = LineStrip;
  29411. const LinePieces = 1;
  29412. exports.LinePieces = LinePieces;
  29413. const NoColors = 0;
  29414. exports.NoColors = NoColors;
  29415. const FaceColors = 1;
  29416. exports.FaceColors = FaceColors;
  29417. const VertexColors = 2;
  29418. exports.VertexColors = VertexColors;
  29419. function MeshFaceMaterial(materials) {
  29420. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29421. return materials;
  29422. }
  29423. function MultiMaterial(materials = []) {
  29424. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29425. materials.isMultiMaterial = true;
  29426. materials.materials = materials;
  29427. materials.clone = function () {
  29428. return materials.slice();
  29429. };
  29430. return materials;
  29431. }
  29432. function PointCloud(geometry, material) {
  29433. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29434. return new Points(geometry, material);
  29435. }
  29436. function Particle(material) {
  29437. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29438. return new Sprite(material);
  29439. }
  29440. function ParticleSystem(geometry, material) {
  29441. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29442. return new Points(geometry, material);
  29443. }
  29444. function PointCloudMaterial(parameters) {
  29445. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29446. return new PointsMaterial(parameters);
  29447. }
  29448. function ParticleBasicMaterial(parameters) {
  29449. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29450. return new PointsMaterial(parameters);
  29451. }
  29452. function ParticleSystemMaterial(parameters) {
  29453. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29454. return new PointsMaterial(parameters);
  29455. }
  29456. function Vertex(x, y, z) {
  29457. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29458. return new Vector3(x, y, z);
  29459. } //
  29460. function DynamicBufferAttribute(array, itemSize) {
  29461. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  29462. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  29463. }
  29464. function Int8Attribute(array, itemSize) {
  29465. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29466. return new Int8BufferAttribute(array, itemSize);
  29467. }
  29468. function Uint8Attribute(array, itemSize) {
  29469. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29470. return new Uint8BufferAttribute(array, itemSize);
  29471. }
  29472. function Uint8ClampedAttribute(array, itemSize) {
  29473. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29474. return new Uint8ClampedBufferAttribute(array, itemSize);
  29475. }
  29476. function Int16Attribute(array, itemSize) {
  29477. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29478. return new Int16BufferAttribute(array, itemSize);
  29479. }
  29480. function Uint16Attribute(array, itemSize) {
  29481. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29482. return new Uint16BufferAttribute(array, itemSize);
  29483. }
  29484. function Int32Attribute(array, itemSize) {
  29485. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29486. return new Int32BufferAttribute(array, itemSize);
  29487. }
  29488. function Uint32Attribute(array, itemSize) {
  29489. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29490. return new Uint32BufferAttribute(array, itemSize);
  29491. }
  29492. function Float32Attribute(array, itemSize) {
  29493. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29494. return new Float32BufferAttribute(array, itemSize);
  29495. }
  29496. function Float64Attribute(array, itemSize) {
  29497. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29498. return new Float64BufferAttribute(array, itemSize);
  29499. } //
  29500. Curve.create = function (construct, getPoint) {
  29501. console.log('THREE.Curve.create() has been deprecated');
  29502. construct.prototype = Object.create(Curve.prototype);
  29503. construct.prototype.constructor = construct;
  29504. construct.prototype.getPoint = getPoint;
  29505. return construct;
  29506. }; //
  29507. Object.assign(CurvePath.prototype, {
  29508. createPointsGeometry: function (divisions) {
  29509. console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)
  29510. const pts = this.getPoints(divisions);
  29511. return this.createGeometry(pts);
  29512. },
  29513. createSpacedPointsGeometry: function (divisions) {
  29514. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29515. const pts = this.getSpacedPoints(divisions);
  29516. return this.createGeometry(pts);
  29517. },
  29518. createGeometry: function (points) {
  29519. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29520. const geometry = new Geometry();
  29521. for (let i = 0, l = points.length; i < l; i++) {
  29522. const point = points[i];
  29523. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29524. }
  29525. return geometry;
  29526. }
  29527. }); //
  29528. Object.assign(Path.prototype, {
  29529. fromPoints: function (points) {
  29530. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29531. return this.setFromPoints(points);
  29532. }
  29533. }); //
  29534. function ClosedSplineCurve3(points) {
  29535. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29536. CatmullRomCurve3.call(this, points);
  29537. this.type = 'catmullrom';
  29538. this.closed = true;
  29539. }
  29540. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29541. function SplineCurve3(points) {
  29542. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29543. CatmullRomCurve3.call(this, points);
  29544. this.type = 'catmullrom';
  29545. }
  29546. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29547. function Spline(points) {
  29548. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29549. CatmullRomCurve3.call(this, points);
  29550. this.type = 'catmullrom';
  29551. }
  29552. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29553. Object.assign(Spline.prototype, {
  29554. initFromArray: function ()
  29555. /* a */
  29556. {
  29557. console.error('THREE.Spline: .initFromArray() has been removed.');
  29558. },
  29559. getControlPointsArray: function ()
  29560. /* optionalTarget */
  29561. {
  29562. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29563. },
  29564. reparametrizeByArcLength: function ()
  29565. /* samplingCoef */
  29566. {
  29567. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29568. }
  29569. }); //
  29570. function AxisHelper(size) {
  29571. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29572. return new AxesHelper(size);
  29573. }
  29574. function BoundingBoxHelper(object, color) {
  29575. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29576. return new BoxHelper(object, color);
  29577. }
  29578. function EdgesHelper(object, hex) {
  29579. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29580. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29581. color: hex !== undefined ? hex : 0xffffff
  29582. }));
  29583. }
  29584. GridHelper.prototype.setColors = function () {
  29585. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29586. };
  29587. SkeletonHelper.prototype.update = function () {
  29588. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29589. };
  29590. function WireframeHelper(object, hex) {
  29591. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29592. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29593. color: hex !== undefined ? hex : 0xffffff
  29594. }));
  29595. } //
  29596. Object.assign(Loader.prototype, {
  29597. extractUrlBase: function (url) {
  29598. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29599. return LoaderUtils.extractUrlBase(url);
  29600. }
  29601. });
  29602. Loader.Handlers = {
  29603. add: function ()
  29604. /* regex, loader */
  29605. {
  29606. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29607. },
  29608. get: function ()
  29609. /* file */
  29610. {
  29611. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29612. }
  29613. };
  29614. function XHRLoader(manager) {
  29615. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29616. return new FileLoader(manager);
  29617. }
  29618. function BinaryTextureLoader(manager) {
  29619. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29620. return new DataTextureLoader(manager);
  29621. } //
  29622. Object.assign(Box2.prototype, {
  29623. center: function (optionalTarget) {
  29624. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29625. return this.getCenter(optionalTarget);
  29626. },
  29627. empty: function () {
  29628. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29629. return this.isEmpty();
  29630. },
  29631. isIntersectionBox: function (box) {
  29632. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29633. return this.intersectsBox(box);
  29634. },
  29635. size: function (optionalTarget) {
  29636. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29637. return this.getSize(optionalTarget);
  29638. }
  29639. });
  29640. Object.assign(Box3.prototype, {
  29641. center: function (optionalTarget) {
  29642. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29643. return this.getCenter(optionalTarget);
  29644. },
  29645. empty: function () {
  29646. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29647. return this.isEmpty();
  29648. },
  29649. isIntersectionBox: function (box) {
  29650. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29651. return this.intersectsBox(box);
  29652. },
  29653. isIntersectionSphere: function (sphere) {
  29654. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29655. return this.intersectsSphere(sphere);
  29656. },
  29657. size: function (optionalTarget) {
  29658. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29659. return this.getSize(optionalTarget);
  29660. }
  29661. });
  29662. Object.assign(Sphere.prototype, {
  29663. empty: function () {
  29664. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  29665. return this.isEmpty();
  29666. }
  29667. });
  29668. Frustum.prototype.setFromMatrix = function (m) {
  29669. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  29670. return this.setFromProjectionMatrix(m);
  29671. };
  29672. Line3.prototype.center = function (optionalTarget) {
  29673. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29674. return this.getCenter(optionalTarget);
  29675. };
  29676. Object.assign(MathUtils, {
  29677. random16: function () {
  29678. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29679. return Math.random();
  29680. },
  29681. nearestPowerOfTwo: function (value) {
  29682. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29683. return MathUtils.floorPowerOfTwo(value);
  29684. },
  29685. nextPowerOfTwo: function (value) {
  29686. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29687. return MathUtils.ceilPowerOfTwo(value);
  29688. }
  29689. });
  29690. Object.assign(Matrix3.prototype, {
  29691. flattenToArrayOffset: function (array, offset) {
  29692. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29693. return this.toArray(array, offset);
  29694. },
  29695. multiplyVector3: function (vector) {
  29696. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29697. return vector.applyMatrix3(this);
  29698. },
  29699. multiplyVector3Array: function ()
  29700. /* a */
  29701. {
  29702. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29703. },
  29704. applyToBufferAttribute: function (attribute) {
  29705. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  29706. return attribute.applyMatrix3(this);
  29707. },
  29708. applyToVector3Array: function ()
  29709. /* array, offset, length */
  29710. {
  29711. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29712. },
  29713. getInverse: function (matrix) {
  29714. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  29715. return this.copy(matrix).invert();
  29716. }
  29717. });
  29718. Object.assign(Matrix4.prototype, {
  29719. extractPosition: function (m) {
  29720. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29721. return this.copyPosition(m);
  29722. },
  29723. flattenToArrayOffset: function (array, offset) {
  29724. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29725. return this.toArray(array, offset);
  29726. },
  29727. getPosition: function () {
  29728. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29729. return new Vector3().setFromMatrixColumn(this, 3);
  29730. },
  29731. setRotationFromQuaternion: function (q) {
  29732. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29733. return this.makeRotationFromQuaternion(q);
  29734. },
  29735. multiplyToArray: function () {
  29736. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29737. },
  29738. multiplyVector3: function (vector) {
  29739. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29740. return vector.applyMatrix4(this);
  29741. },
  29742. multiplyVector4: function (vector) {
  29743. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29744. return vector.applyMatrix4(this);
  29745. },
  29746. multiplyVector3Array: function ()
  29747. /* a */
  29748. {
  29749. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29750. },
  29751. rotateAxis: function (v) {
  29752. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29753. v.transformDirection(this);
  29754. },
  29755. crossVector: function (vector) {
  29756. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29757. return vector.applyMatrix4(this);
  29758. },
  29759. translate: function () {
  29760. console.error('THREE.Matrix4: .translate() has been removed.');
  29761. },
  29762. rotateX: function () {
  29763. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29764. },
  29765. rotateY: function () {
  29766. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29767. },
  29768. rotateZ: function () {
  29769. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29770. },
  29771. rotateByAxis: function () {
  29772. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29773. },
  29774. applyToBufferAttribute: function (attribute) {
  29775. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  29776. return attribute.applyMatrix4(this);
  29777. },
  29778. applyToVector3Array: function ()
  29779. /* array, offset, length */
  29780. {
  29781. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29782. },
  29783. makeFrustum: function (left, right, bottom, top, near, far) {
  29784. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29785. return this.makePerspective(left, right, top, bottom, near, far);
  29786. },
  29787. getInverse: function (matrix) {
  29788. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  29789. return this.copy(matrix).invert();
  29790. }
  29791. });
  29792. Plane.prototype.isIntersectionLine = function (line) {
  29793. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29794. return this.intersectsLine(line);
  29795. };
  29796. Object.assign(Quaternion.prototype, {
  29797. multiplyVector3: function (vector) {
  29798. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29799. return vector.applyQuaternion(this);
  29800. },
  29801. inverse: function () {
  29802. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  29803. return this.invert();
  29804. }
  29805. });
  29806. Object.assign(Ray.prototype, {
  29807. isIntersectionBox: function (box) {
  29808. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29809. return this.intersectsBox(box);
  29810. },
  29811. isIntersectionPlane: function (plane) {
  29812. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29813. return this.intersectsPlane(plane);
  29814. },
  29815. isIntersectionSphere: function (sphere) {
  29816. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29817. return this.intersectsSphere(sphere);
  29818. }
  29819. });
  29820. Object.assign(Triangle.prototype, {
  29821. area: function () {
  29822. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29823. return this.getArea();
  29824. },
  29825. barycoordFromPoint: function (point, target) {
  29826. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29827. return this.getBarycoord(point, target);
  29828. },
  29829. midpoint: function (target) {
  29830. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29831. return this.getMidpoint(target);
  29832. },
  29833. normal: function (target) {
  29834. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29835. return this.getNormal(target);
  29836. },
  29837. plane: function (target) {
  29838. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29839. return this.getPlane(target);
  29840. }
  29841. });
  29842. Object.assign(Triangle, {
  29843. barycoordFromPoint: function (point, a, b, c, target) {
  29844. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29845. return Triangle.getBarycoord(point, a, b, c, target);
  29846. },
  29847. normal: function (a, b, c, target) {
  29848. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29849. return Triangle.getNormal(a, b, c, target);
  29850. }
  29851. });
  29852. Object.assign(Shape.prototype, {
  29853. extractAllPoints: function (divisions) {
  29854. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29855. return this.extractPoints(divisions);
  29856. },
  29857. extrude: function (options) {
  29858. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29859. return new ExtrudeGeometry(this, options);
  29860. },
  29861. makeGeometry: function (options) {
  29862. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29863. return new ShapeGeometry(this, options);
  29864. }
  29865. });
  29866. Object.assign(Vector2.prototype, {
  29867. fromAttribute: function (attribute, index, offset) {
  29868. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29869. return this.fromBufferAttribute(attribute, index, offset);
  29870. },
  29871. distanceToManhattan: function (v) {
  29872. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29873. return this.manhattanDistanceTo(v);
  29874. },
  29875. lengthManhattan: function () {
  29876. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29877. return this.manhattanLength();
  29878. }
  29879. });
  29880. Object.assign(Vector3.prototype, {
  29881. setEulerFromRotationMatrix: function () {
  29882. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29883. },
  29884. setEulerFromQuaternion: function () {
  29885. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29886. },
  29887. getPositionFromMatrix: function (m) {
  29888. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29889. return this.setFromMatrixPosition(m);
  29890. },
  29891. getScaleFromMatrix: function (m) {
  29892. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29893. return this.setFromMatrixScale(m);
  29894. },
  29895. getColumnFromMatrix: function (index, matrix) {
  29896. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29897. return this.setFromMatrixColumn(matrix, index);
  29898. },
  29899. applyProjection: function (m) {
  29900. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29901. return this.applyMatrix4(m);
  29902. },
  29903. fromAttribute: function (attribute, index, offset) {
  29904. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29905. return this.fromBufferAttribute(attribute, index, offset);
  29906. },
  29907. distanceToManhattan: function (v) {
  29908. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29909. return this.manhattanDistanceTo(v);
  29910. },
  29911. lengthManhattan: function () {
  29912. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29913. return this.manhattanLength();
  29914. }
  29915. });
  29916. Object.assign(Vector4.prototype, {
  29917. fromAttribute: function (attribute, index, offset) {
  29918. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29919. return this.fromBufferAttribute(attribute, index, offset);
  29920. },
  29921. lengthManhattan: function () {
  29922. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29923. return this.manhattanLength();
  29924. }
  29925. }); //
  29926. Object.assign(Geometry.prototype, {
  29927. computeTangents: function () {
  29928. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29929. },
  29930. computeLineDistances: function () {
  29931. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29932. },
  29933. applyMatrix: function (matrix) {
  29934. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29935. return this.applyMatrix4(matrix);
  29936. }
  29937. });
  29938. Object.assign(Object3D.prototype, {
  29939. getChildByName: function (name) {
  29940. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29941. return this.getObjectByName(name);
  29942. },
  29943. renderDepth: function () {
  29944. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29945. },
  29946. translate: function (distance, axis) {
  29947. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29948. return this.translateOnAxis(axis, distance);
  29949. },
  29950. getWorldRotation: function () {
  29951. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29952. },
  29953. applyMatrix: function (matrix) {
  29954. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  29955. return this.applyMatrix4(matrix);
  29956. }
  29957. });
  29958. Object.defineProperties(Object3D.prototype, {
  29959. eulerOrder: {
  29960. get: function () {
  29961. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29962. return this.rotation.order;
  29963. },
  29964. set: function (value) {
  29965. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29966. this.rotation.order = value;
  29967. }
  29968. },
  29969. useQuaternion: {
  29970. get: function () {
  29971. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29972. },
  29973. set: function () {
  29974. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29975. }
  29976. }
  29977. });
  29978. Object.assign(Mesh.prototype, {
  29979. setDrawMode: function () {
  29980. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29981. }
  29982. });
  29983. Object.defineProperties(Mesh.prototype, {
  29984. drawMode: {
  29985. get: function () {
  29986. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  29987. return TrianglesDrawMode;
  29988. },
  29989. set: function () {
  29990. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29991. }
  29992. }
  29993. });
  29994. Object.defineProperties(LOD.prototype, {
  29995. objects: {
  29996. get: function () {
  29997. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29998. return this.levels;
  29999. }
  30000. }
  30001. });
  30002. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  30003. get: function () {
  30004. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  30005. },
  30006. set: function () {
  30007. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  30008. }
  30009. });
  30010. SkinnedMesh.prototype.initBones = function () {
  30011. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  30012. };
  30013. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  30014. get: function () {
  30015. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  30016. return this.arcLengthDivisions;
  30017. },
  30018. set: function (value) {
  30019. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  30020. this.arcLengthDivisions = value;
  30021. }
  30022. }); //
  30023. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  30024. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  30025. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  30026. this.setFocalLength(focalLength);
  30027. }; //
  30028. Object.defineProperties(Light.prototype, {
  30029. onlyShadow: {
  30030. set: function () {
  30031. console.warn('THREE.Light: .onlyShadow has been removed.');
  30032. }
  30033. },
  30034. shadowCameraFov: {
  30035. set: function (value) {
  30036. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  30037. this.shadow.camera.fov = value;
  30038. }
  30039. },
  30040. shadowCameraLeft: {
  30041. set: function (value) {
  30042. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  30043. this.shadow.camera.left = value;
  30044. }
  30045. },
  30046. shadowCameraRight: {
  30047. set: function (value) {
  30048. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  30049. this.shadow.camera.right = value;
  30050. }
  30051. },
  30052. shadowCameraTop: {
  30053. set: function (value) {
  30054. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  30055. this.shadow.camera.top = value;
  30056. }
  30057. },
  30058. shadowCameraBottom: {
  30059. set: function (value) {
  30060. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  30061. this.shadow.camera.bottom = value;
  30062. }
  30063. },
  30064. shadowCameraNear: {
  30065. set: function (value) {
  30066. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  30067. this.shadow.camera.near = value;
  30068. }
  30069. },
  30070. shadowCameraFar: {
  30071. set: function (value) {
  30072. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  30073. this.shadow.camera.far = value;
  30074. }
  30075. },
  30076. shadowCameraVisible: {
  30077. set: function () {
  30078. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  30079. }
  30080. },
  30081. shadowBias: {
  30082. set: function (value) {
  30083. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  30084. this.shadow.bias = value;
  30085. }
  30086. },
  30087. shadowDarkness: {
  30088. set: function () {
  30089. console.warn('THREE.Light: .shadowDarkness has been removed.');
  30090. }
  30091. },
  30092. shadowMapWidth: {
  30093. set: function (value) {
  30094. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  30095. this.shadow.mapSize.width = value;
  30096. }
  30097. },
  30098. shadowMapHeight: {
  30099. set: function (value) {
  30100. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  30101. this.shadow.mapSize.height = value;
  30102. }
  30103. }
  30104. }); //
  30105. Object.defineProperties(BufferAttribute.prototype, {
  30106. length: {
  30107. get: function () {
  30108. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  30109. return this.array.length;
  30110. }
  30111. },
  30112. dynamic: {
  30113. get: function () {
  30114. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  30115. return this.usage === DynamicDrawUsage;
  30116. },
  30117. set: function ()
  30118. /* value */
  30119. {
  30120. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  30121. this.setUsage(DynamicDrawUsage);
  30122. }
  30123. }
  30124. });
  30125. Object.assign(BufferAttribute.prototype, {
  30126. setDynamic: function (value) {
  30127. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  30128. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  30129. return this;
  30130. },
  30131. copyIndicesArray: function ()
  30132. /* indices */
  30133. {
  30134. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  30135. },
  30136. setArray: function ()
  30137. /* array */
  30138. {
  30139. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  30140. }
  30141. });
  30142. Object.assign(BufferGeometry.prototype, {
  30143. addIndex: function (index) {
  30144. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  30145. this.setIndex(index);
  30146. },
  30147. addAttribute: function (name, attribute) {
  30148. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  30149. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  30150. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  30151. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  30152. }
  30153. if (name === 'index') {
  30154. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  30155. this.setIndex(attribute);
  30156. return this;
  30157. }
  30158. return this.setAttribute(name, attribute);
  30159. },
  30160. addDrawCall: function (start, count, indexOffset) {
  30161. if (indexOffset !== undefined) {
  30162. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  30163. }
  30164. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  30165. this.addGroup(start, count);
  30166. },
  30167. clearDrawCalls: function () {
  30168. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  30169. this.clearGroups();
  30170. },
  30171. computeTangents: function () {
  30172. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  30173. },
  30174. computeOffsets: function () {
  30175. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  30176. },
  30177. removeAttribute: function (name) {
  30178. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  30179. return this.deleteAttribute(name);
  30180. },
  30181. applyMatrix: function (matrix) {
  30182. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  30183. return this.applyMatrix4(matrix);
  30184. }
  30185. });
  30186. Object.defineProperties(BufferGeometry.prototype, {
  30187. drawcalls: {
  30188. get: function () {
  30189. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  30190. return this.groups;
  30191. }
  30192. },
  30193. offsets: {
  30194. get: function () {
  30195. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  30196. return this.groups;
  30197. }
  30198. }
  30199. });
  30200. Object.defineProperties(InstancedBufferGeometry.prototype, {
  30201. maxInstancedCount: {
  30202. get: function () {
  30203. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  30204. return this.instanceCount;
  30205. },
  30206. set: function (value) {
  30207. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  30208. this.instanceCount = value;
  30209. }
  30210. }
  30211. });
  30212. Object.defineProperties(Raycaster.prototype, {
  30213. linePrecision: {
  30214. get: function () {
  30215. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  30216. return this.params.Line.threshold;
  30217. },
  30218. set: function (value) {
  30219. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  30220. this.params.Line.threshold = value;
  30221. }
  30222. }
  30223. });
  30224. Object.defineProperties(InterleavedBuffer.prototype, {
  30225. dynamic: {
  30226. get: function () {
  30227. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  30228. return this.usage === DynamicDrawUsage;
  30229. },
  30230. set: function (value) {
  30231. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  30232. this.setUsage(value);
  30233. }
  30234. }
  30235. });
  30236. Object.assign(InterleavedBuffer.prototype, {
  30237. setDynamic: function (value) {
  30238. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  30239. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  30240. return this;
  30241. },
  30242. setArray: function ()
  30243. /* array */
  30244. {
  30245. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  30246. }
  30247. }); //
  30248. Object.assign(ExtrudeBufferGeometry.prototype, {
  30249. getArrays: function () {
  30250. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  30251. },
  30252. addShapeList: function () {
  30253. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  30254. },
  30255. addShape: function () {
  30256. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  30257. }
  30258. }); //
  30259. Object.assign(Scene.prototype, {
  30260. dispose: function () {
  30261. console.error('THREE.Scene: .dispose() has been removed.');
  30262. }
  30263. }); //
  30264. Object.defineProperties(Uniform.prototype, {
  30265. dynamic: {
  30266. set: function () {
  30267. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  30268. }
  30269. },
  30270. onUpdate: {
  30271. value: function () {
  30272. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  30273. return this;
  30274. }
  30275. }
  30276. }); //
  30277. Object.defineProperties(Material.prototype, {
  30278. wrapAround: {
  30279. get: function () {
  30280. console.warn('THREE.Material: .wrapAround has been removed.');
  30281. },
  30282. set: function () {
  30283. console.warn('THREE.Material: .wrapAround has been removed.');
  30284. }
  30285. },
  30286. overdraw: {
  30287. get: function () {
  30288. console.warn('THREE.Material: .overdraw has been removed.');
  30289. },
  30290. set: function () {
  30291. console.warn('THREE.Material: .overdraw has been removed.');
  30292. }
  30293. },
  30294. wrapRGB: {
  30295. get: function () {
  30296. console.warn('THREE.Material: .wrapRGB has been removed.');
  30297. return new Color();
  30298. }
  30299. },
  30300. shading: {
  30301. get: function () {
  30302. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  30303. },
  30304. set: function (value) {
  30305. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  30306. this.flatShading = value === FlatShading;
  30307. }
  30308. },
  30309. stencilMask: {
  30310. get: function () {
  30311. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  30312. return this.stencilFuncMask;
  30313. },
  30314. set: function (value) {
  30315. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  30316. this.stencilFuncMask = value;
  30317. }
  30318. }
  30319. });
  30320. Object.defineProperties(MeshPhongMaterial.prototype, {
  30321. metal: {
  30322. get: function () {
  30323. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  30324. return false;
  30325. },
  30326. set: function () {
  30327. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  30328. }
  30329. }
  30330. });
  30331. Object.defineProperties(MeshPhysicalMaterial.prototype, {
  30332. transparency: {
  30333. get: function () {
  30334. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  30335. return this.transmission;
  30336. },
  30337. set: function (value) {
  30338. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  30339. this.transmission = value;
  30340. }
  30341. }
  30342. });
  30343. Object.defineProperties(ShaderMaterial.prototype, {
  30344. derivatives: {
  30345. get: function () {
  30346. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  30347. return this.extensions.derivatives;
  30348. },
  30349. set: function (value) {
  30350. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  30351. this.extensions.derivatives = value;
  30352. }
  30353. }
  30354. }); //
  30355. Object.assign(WebGLRenderer.prototype, {
  30356. clearTarget: function (renderTarget, color, depth, stencil) {
  30357. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  30358. this.setRenderTarget(renderTarget);
  30359. this.clear(color, depth, stencil);
  30360. },
  30361. animate: function (callback) {
  30362. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  30363. this.setAnimationLoop(callback);
  30364. },
  30365. getCurrentRenderTarget: function () {
  30366. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  30367. return this.getRenderTarget();
  30368. },
  30369. getMaxAnisotropy: function () {
  30370. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  30371. return this.capabilities.getMaxAnisotropy();
  30372. },
  30373. getPrecision: function () {
  30374. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  30375. return this.capabilities.precision;
  30376. },
  30377. resetGLState: function () {
  30378. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  30379. return this.state.reset();
  30380. },
  30381. supportsFloatTextures: function () {
  30382. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30383. return this.extensions.get('OES_texture_float');
  30384. },
  30385. supportsHalfFloatTextures: function () {
  30386. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30387. return this.extensions.get('OES_texture_half_float');
  30388. },
  30389. supportsStandardDerivatives: function () {
  30390. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30391. return this.extensions.get('OES_standard_derivatives');
  30392. },
  30393. supportsCompressedTextureS3TC: function () {
  30394. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30395. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30396. },
  30397. supportsCompressedTexturePVRTC: function () {
  30398. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30399. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30400. },
  30401. supportsBlendMinMax: function () {
  30402. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30403. return this.extensions.get('EXT_blend_minmax');
  30404. },
  30405. supportsVertexTextures: function () {
  30406. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30407. return this.capabilities.vertexTextures;
  30408. },
  30409. supportsInstancedArrays: function () {
  30410. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30411. return this.extensions.get('ANGLE_instanced_arrays');
  30412. },
  30413. enableScissorTest: function (boolean) {
  30414. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30415. this.setScissorTest(boolean);
  30416. },
  30417. initMaterial: function () {
  30418. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30419. },
  30420. addPrePlugin: function () {
  30421. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30422. },
  30423. addPostPlugin: function () {
  30424. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30425. },
  30426. updateShadowMap: function () {
  30427. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30428. },
  30429. setFaceCulling: function () {
  30430. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30431. },
  30432. allocTextureUnit: function () {
  30433. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30434. },
  30435. setTexture: function () {
  30436. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30437. },
  30438. setTexture2D: function () {
  30439. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30440. },
  30441. setTextureCube: function () {
  30442. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30443. },
  30444. getActiveMipMapLevel: function () {
  30445. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30446. return this.getActiveMipmapLevel();
  30447. }
  30448. });
  30449. Object.defineProperties(WebGLRenderer.prototype, {
  30450. shadowMapEnabled: {
  30451. get: function () {
  30452. return this.shadowMap.enabled;
  30453. },
  30454. set: function (value) {
  30455. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30456. this.shadowMap.enabled = value;
  30457. }
  30458. },
  30459. shadowMapType: {
  30460. get: function () {
  30461. return this.shadowMap.type;
  30462. },
  30463. set: function (value) {
  30464. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30465. this.shadowMap.type = value;
  30466. }
  30467. },
  30468. shadowMapCullFace: {
  30469. get: function () {
  30470. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30471. return undefined;
  30472. },
  30473. set: function ()
  30474. /* value */
  30475. {
  30476. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30477. }
  30478. },
  30479. context: {
  30480. get: function () {
  30481. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30482. return this.getContext();
  30483. }
  30484. },
  30485. vr: {
  30486. get: function () {
  30487. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  30488. return this.xr;
  30489. }
  30490. },
  30491. gammaInput: {
  30492. get: function () {
  30493. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  30494. return false;
  30495. },
  30496. set: function () {
  30497. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  30498. }
  30499. },
  30500. gammaOutput: {
  30501. get: function () {
  30502. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  30503. return false;
  30504. },
  30505. set: function (value) {
  30506. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  30507. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  30508. }
  30509. },
  30510. toneMappingWhitePoint: {
  30511. get: function () {
  30512. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  30513. return 1.0;
  30514. },
  30515. set: function () {
  30516. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  30517. }
  30518. }
  30519. });
  30520. Object.defineProperties(WebGLShadowMap.prototype, {
  30521. cullFace: {
  30522. get: function () {
  30523. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30524. return undefined;
  30525. },
  30526. set: function ()
  30527. /* cullFace */
  30528. {
  30529. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30530. }
  30531. },
  30532. renderReverseSided: {
  30533. get: function () {
  30534. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30535. return undefined;
  30536. },
  30537. set: function () {
  30538. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30539. }
  30540. },
  30541. renderSingleSided: {
  30542. get: function () {
  30543. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30544. return undefined;
  30545. },
  30546. set: function () {
  30547. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30548. }
  30549. }
  30550. });
  30551. function WebGLRenderTargetCube(width, height, options) {
  30552. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  30553. return new WebGLCubeRenderTarget(width, options);
  30554. } //
  30555. Object.defineProperties(WebGLRenderTarget.prototype, {
  30556. wrapS: {
  30557. get: function () {
  30558. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30559. return this.texture.wrapS;
  30560. },
  30561. set: function (value) {
  30562. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30563. this.texture.wrapS = value;
  30564. }
  30565. },
  30566. wrapT: {
  30567. get: function () {
  30568. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30569. return this.texture.wrapT;
  30570. },
  30571. set: function (value) {
  30572. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30573. this.texture.wrapT = value;
  30574. }
  30575. },
  30576. magFilter: {
  30577. get: function () {
  30578. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30579. return this.texture.magFilter;
  30580. },
  30581. set: function (value) {
  30582. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30583. this.texture.magFilter = value;
  30584. }
  30585. },
  30586. minFilter: {
  30587. get: function () {
  30588. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30589. return this.texture.minFilter;
  30590. },
  30591. set: function (value) {
  30592. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30593. this.texture.minFilter = value;
  30594. }
  30595. },
  30596. anisotropy: {
  30597. get: function () {
  30598. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30599. return this.texture.anisotropy;
  30600. },
  30601. set: function (value) {
  30602. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30603. this.texture.anisotropy = value;
  30604. }
  30605. },
  30606. offset: {
  30607. get: function () {
  30608. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30609. return this.texture.offset;
  30610. },
  30611. set: function (value) {
  30612. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30613. this.texture.offset = value;
  30614. }
  30615. },
  30616. repeat: {
  30617. get: function () {
  30618. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30619. return this.texture.repeat;
  30620. },
  30621. set: function (value) {
  30622. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30623. this.texture.repeat = value;
  30624. }
  30625. },
  30626. format: {
  30627. get: function () {
  30628. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30629. return this.texture.format;
  30630. },
  30631. set: function (value) {
  30632. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30633. this.texture.format = value;
  30634. }
  30635. },
  30636. type: {
  30637. get: function () {
  30638. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30639. return this.texture.type;
  30640. },
  30641. set: function (value) {
  30642. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30643. this.texture.type = value;
  30644. }
  30645. },
  30646. generateMipmaps: {
  30647. get: function () {
  30648. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30649. return this.texture.generateMipmaps;
  30650. },
  30651. set: function (value) {
  30652. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30653. this.texture.generateMipmaps = value;
  30654. }
  30655. }
  30656. }); //
  30657. Object.defineProperties(Audio.prototype, {
  30658. load: {
  30659. value: function (file) {
  30660. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30661. const scope = this;
  30662. const audioLoader = new AudioLoader();
  30663. audioLoader.load(file, function (buffer) {
  30664. scope.setBuffer(buffer);
  30665. });
  30666. return this;
  30667. }
  30668. },
  30669. startTime: {
  30670. set: function () {
  30671. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  30672. }
  30673. }
  30674. });
  30675. AudioAnalyser.prototype.getData = function () {
  30676. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30677. return this.getFrequencyData();
  30678. }; //
  30679. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30680. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30681. return this.update(renderer, scene);
  30682. };
  30683. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  30684. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  30685. return this.renderTarget.clear(renderer, color, depth, stencil);
  30686. }; //
  30687. const GeometryUtils = {
  30688. merge: function (geometry1, geometry2, materialIndexOffset) {
  30689. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30690. let matrix;
  30691. if (geometry2.isMesh) {
  30692. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30693. matrix = geometry2.matrix;
  30694. geometry2 = geometry2.geometry;
  30695. }
  30696. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30697. },
  30698. center: function (geometry) {
  30699. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30700. return geometry.center();
  30701. }
  30702. };
  30703. exports.GeometryUtils = GeometryUtils;
  30704. ImageUtils.crossOrigin = undefined;
  30705. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30706. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30707. const loader = new TextureLoader();
  30708. loader.setCrossOrigin(this.crossOrigin);
  30709. const texture = loader.load(url, onLoad, undefined, onError);
  30710. if (mapping) texture.mapping = mapping;
  30711. return texture;
  30712. };
  30713. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30714. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30715. const loader = new CubeTextureLoader();
  30716. loader.setCrossOrigin(this.crossOrigin);
  30717. const texture = loader.load(urls, onLoad, undefined, onError);
  30718. if (mapping) texture.mapping = mapping;
  30719. return texture;
  30720. };
  30721. ImageUtils.loadCompressedTexture = function () {
  30722. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30723. };
  30724. ImageUtils.loadCompressedTextureCube = function () {
  30725. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30726. }; //
  30727. function CanvasRenderer() {
  30728. console.error('THREE.CanvasRenderer has been removed');
  30729. } //
  30730. function JSONLoader() {
  30731. console.error('THREE.JSONLoader has been removed.');
  30732. } //
  30733. const SceneUtils = {
  30734. createMultiMaterialObject: function ()
  30735. /* geometry, materials */
  30736. {
  30737. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30738. },
  30739. detach: function ()
  30740. /* child, parent, scene */
  30741. {
  30742. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30743. },
  30744. attach: function ()
  30745. /* child, scene, parent */
  30746. {
  30747. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30748. }
  30749. }; //
  30750. exports.SceneUtils = SceneUtils;
  30751. function LensFlare() {
  30752. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  30753. }
  30754. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30755. /* eslint-disable no-undef */
  30756. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30757. detail: {
  30758. revision: REVISION
  30759. }
  30760. }));
  30761. /* eslint-enable no-undef */
  30762. }
  30763. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  30764. // shim for using process in browser
  30765. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  30766. // don't break things. But we need to wrap it in a try catch in case it is
  30767. // wrapped in strict mode code which doesn't define any globals. It's inside a
  30768. // function because try/catches deoptimize in certain engines.
  30769. var cachedSetTimeout;
  30770. var cachedClearTimeout;
  30771. function defaultSetTimout() {
  30772. throw new Error('setTimeout has not been defined');
  30773. }
  30774. function defaultClearTimeout() {
  30775. throw new Error('clearTimeout has not been defined');
  30776. }
  30777. (function () {
  30778. try {
  30779. if (typeof setTimeout === 'function') {
  30780. cachedSetTimeout = setTimeout;
  30781. } else {
  30782. cachedSetTimeout = defaultSetTimout;
  30783. }
  30784. } catch (e) {
  30785. cachedSetTimeout = defaultSetTimout;
  30786. }
  30787. try {
  30788. if (typeof clearTimeout === 'function') {
  30789. cachedClearTimeout = clearTimeout;
  30790. } else {
  30791. cachedClearTimeout = defaultClearTimeout;
  30792. }
  30793. } catch (e) {
  30794. cachedClearTimeout = defaultClearTimeout;
  30795. }
  30796. })();
  30797. function runTimeout(fun) {
  30798. if (cachedSetTimeout === setTimeout) {
  30799. //normal enviroments in sane situations
  30800. return setTimeout(fun, 0);
  30801. } // if setTimeout wasn't available but was latter defined
  30802. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  30803. cachedSetTimeout = setTimeout;
  30804. return setTimeout(fun, 0);
  30805. }
  30806. try {
  30807. // when when somebody has screwed with setTimeout but no I.E. maddness
  30808. return cachedSetTimeout(fun, 0);
  30809. } catch (e) {
  30810. try {
  30811. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30812. return cachedSetTimeout.call(null, fun, 0);
  30813. } catch (e) {
  30814. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  30815. return cachedSetTimeout.call(this, fun, 0);
  30816. }
  30817. }
  30818. }
  30819. function runClearTimeout(marker) {
  30820. if (cachedClearTimeout === clearTimeout) {
  30821. //normal enviroments in sane situations
  30822. return clearTimeout(marker);
  30823. } // if clearTimeout wasn't available but was latter defined
  30824. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  30825. cachedClearTimeout = clearTimeout;
  30826. return clearTimeout(marker);
  30827. }
  30828. try {
  30829. // when when somebody has screwed with setTimeout but no I.E. maddness
  30830. return cachedClearTimeout(marker);
  30831. } catch (e) {
  30832. try {
  30833. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30834. return cachedClearTimeout.call(null, marker);
  30835. } catch (e) {
  30836. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  30837. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  30838. return cachedClearTimeout.call(this, marker);
  30839. }
  30840. }
  30841. }
  30842. var queue = [];
  30843. var draining = false;
  30844. var currentQueue;
  30845. var queueIndex = -1;
  30846. function cleanUpNextTick() {
  30847. if (!draining || !currentQueue) {
  30848. return;
  30849. }
  30850. draining = false;
  30851. if (currentQueue.length) {
  30852. queue = currentQueue.concat(queue);
  30853. } else {
  30854. queueIndex = -1;
  30855. }
  30856. if (queue.length) {
  30857. drainQueue();
  30858. }
  30859. }
  30860. function drainQueue() {
  30861. if (draining) {
  30862. return;
  30863. }
  30864. var timeout = runTimeout(cleanUpNextTick);
  30865. draining = true;
  30866. var len = queue.length;
  30867. while (len) {
  30868. currentQueue = queue;
  30869. queue = [];
  30870. while (++queueIndex < len) {
  30871. if (currentQueue) {
  30872. currentQueue[queueIndex].run();
  30873. }
  30874. }
  30875. queueIndex = -1;
  30876. len = queue.length;
  30877. }
  30878. currentQueue = null;
  30879. draining = false;
  30880. runClearTimeout(timeout);
  30881. }
  30882. process.nextTick = function (fun) {
  30883. var args = new Array(arguments.length - 1);
  30884. if (arguments.length > 1) {
  30885. for (var i = 1; i < arguments.length; i++) {
  30886. args[i - 1] = arguments[i];
  30887. }
  30888. }
  30889. queue.push(new Item(fun, args));
  30890. if (queue.length === 1 && !draining) {
  30891. runTimeout(drainQueue);
  30892. }
  30893. }; // v8 likes predictible objects
  30894. function Item(fun, array) {
  30895. this.fun = fun;
  30896. this.array = array;
  30897. }
  30898. Item.prototype.run = function () {
  30899. this.fun.apply(null, this.array);
  30900. };
  30901. process.title = 'browser';
  30902. process.env = {};
  30903. process.argv = [];
  30904. process.version = ''; // empty string to avoid regexp issues
  30905. process.versions = {};
  30906. function noop() {}
  30907. process.on = noop;
  30908. process.addListener = noop;
  30909. process.once = noop;
  30910. process.off = noop;
  30911. process.removeListener = noop;
  30912. process.removeAllListeners = noop;
  30913. process.emit = noop;
  30914. process.prependListener = noop;
  30915. process.prependOnceListener = noop;
  30916. process.listeners = function (name) {
  30917. return [];
  30918. };
  30919. process.binding = function (name) {
  30920. throw new Error('process.binding is not supported');
  30921. };
  30922. process.cwd = function () {
  30923. return '/';
  30924. };
  30925. process.chdir = function (dir) {
  30926. throw new Error('process.chdir is not supported');
  30927. };
  30928. process.umask = function () {
  30929. return 0;
  30930. };
  30931. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  30932. var process = require("process");
  30933. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  30934. // backported and transplited with Babel, with backwards-compat fixes
  30935. // Copyright Joyent, Inc. and other Node contributors.
  30936. //
  30937. // Permission is hereby granted, free of charge, to any person obtaining a
  30938. // copy of this software and associated documentation files (the
  30939. // "Software"), to deal in the Software without restriction, including
  30940. // without limitation the rights to use, copy, modify, merge, publish,
  30941. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30942. // persons to whom the Software is furnished to do so, subject to the
  30943. // following conditions:
  30944. //
  30945. // The above copyright notice and this permission notice shall be included
  30946. // in all copies or substantial portions of the Software.
  30947. //
  30948. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30949. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30950. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30951. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30952. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30953. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30954. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30955. // resolves . and .. elements in a path array with directory names there
  30956. // must be no slashes, empty elements, or device names (c:\) in the array
  30957. // (so also no leading and trailing slashes - it does not distinguish
  30958. // relative and absolute paths)
  30959. function normalizeArray(parts, allowAboveRoot) {
  30960. // if the path tries to go above the root, `up` ends up > 0
  30961. var up = 0;
  30962. for (var i = parts.length - 1; i >= 0; i--) {
  30963. var last = parts[i];
  30964. if (last === '.') {
  30965. parts.splice(i, 1);
  30966. } else if (last === '..') {
  30967. parts.splice(i, 1);
  30968. up++;
  30969. } else if (up) {
  30970. parts.splice(i, 1);
  30971. up--;
  30972. }
  30973. }
  30974. // if the path is allowed to go above the root, restore leading ..s
  30975. if (allowAboveRoot) {
  30976. for (; up--; up) {
  30977. parts.unshift('..');
  30978. }
  30979. }
  30980. return parts;
  30981. }
  30982. // path.resolve([from ...], to)
  30983. // posix version
  30984. exports.resolve = function() {
  30985. var resolvedPath = '',
  30986. resolvedAbsolute = false;
  30987. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  30988. var path = (i >= 0) ? arguments[i] : process.cwd();
  30989. // Skip empty and invalid entries
  30990. if (typeof path !== 'string') {
  30991. throw new TypeError('Arguments to path.resolve must be strings');
  30992. } else if (!path) {
  30993. continue;
  30994. }
  30995. resolvedPath = path + '/' + resolvedPath;
  30996. resolvedAbsolute = path.charAt(0) === '/';
  30997. }
  30998. // At this point the path should be resolved to a full absolute path, but
  30999. // handle relative paths to be safe (might happen when process.cwd() fails)
  31000. // Normalize the path
  31001. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  31002. return !!p;
  31003. }), !resolvedAbsolute).join('/');
  31004. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  31005. };
  31006. // path.normalize(path)
  31007. // posix version
  31008. exports.normalize = function(path) {
  31009. var isAbsolute = exports.isAbsolute(path),
  31010. trailingSlash = substr(path, -1) === '/';
  31011. // Normalize the path
  31012. path = normalizeArray(filter(path.split('/'), function(p) {
  31013. return !!p;
  31014. }), !isAbsolute).join('/');
  31015. if (!path && !isAbsolute) {
  31016. path = '.';
  31017. }
  31018. if (path && trailingSlash) {
  31019. path += '/';
  31020. }
  31021. return (isAbsolute ? '/' : '') + path;
  31022. };
  31023. // posix version
  31024. exports.isAbsolute = function(path) {
  31025. return path.charAt(0) === '/';
  31026. };
  31027. // posix version
  31028. exports.join = function() {
  31029. var paths = Array.prototype.slice.call(arguments, 0);
  31030. return exports.normalize(filter(paths, function(p, index) {
  31031. if (typeof p !== 'string') {
  31032. throw new TypeError('Arguments to path.join must be strings');
  31033. }
  31034. return p;
  31035. }).join('/'));
  31036. };
  31037. // path.relative(from, to)
  31038. // posix version
  31039. exports.relative = function(from, to) {
  31040. from = exports.resolve(from).substr(1);
  31041. to = exports.resolve(to).substr(1);
  31042. function trim(arr) {
  31043. var start = 0;
  31044. for (; start < arr.length; start++) {
  31045. if (arr[start] !== '') break;
  31046. }
  31047. var end = arr.length - 1;
  31048. for (; end >= 0; end--) {
  31049. if (arr[end] !== '') break;
  31050. }
  31051. if (start > end) return [];
  31052. return arr.slice(start, end - start + 1);
  31053. }
  31054. var fromParts = trim(from.split('/'));
  31055. var toParts = trim(to.split('/'));
  31056. var length = Math.min(fromParts.length, toParts.length);
  31057. var samePartsLength = length;
  31058. for (var i = 0; i < length; i++) {
  31059. if (fromParts[i] !== toParts[i]) {
  31060. samePartsLength = i;
  31061. break;
  31062. }
  31063. }
  31064. var outputParts = [];
  31065. for (var i = samePartsLength; i < fromParts.length; i++) {
  31066. outputParts.push('..');
  31067. }
  31068. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  31069. return outputParts.join('/');
  31070. };
  31071. exports.sep = '/';
  31072. exports.delimiter = ':';
  31073. exports.dirname = function (path) {
  31074. if (typeof path !== 'string') path = path + '';
  31075. if (path.length === 0) return '.';
  31076. var code = path.charCodeAt(0);
  31077. var hasRoot = code === 47 /*/*/;
  31078. var end = -1;
  31079. var matchedSlash = true;
  31080. for (var i = path.length - 1; i >= 1; --i) {
  31081. code = path.charCodeAt(i);
  31082. if (code === 47 /*/*/) {
  31083. if (!matchedSlash) {
  31084. end = i;
  31085. break;
  31086. }
  31087. } else {
  31088. // We saw the first non-path separator
  31089. matchedSlash = false;
  31090. }
  31091. }
  31092. if (end === -1) return hasRoot ? '/' : '.';
  31093. if (hasRoot && end === 1) {
  31094. // return '//';
  31095. // Backwards-compat fix:
  31096. return '/';
  31097. }
  31098. return path.slice(0, end);
  31099. };
  31100. function basename(path) {
  31101. if (typeof path !== 'string') path = path + '';
  31102. var start = 0;
  31103. var end = -1;
  31104. var matchedSlash = true;
  31105. var i;
  31106. for (i = path.length - 1; i >= 0; --i) {
  31107. if (path.charCodeAt(i) === 47 /*/*/) {
  31108. // If we reached a path separator that was not part of a set of path
  31109. // separators at the end of the string, stop now
  31110. if (!matchedSlash) {
  31111. start = i + 1;
  31112. break;
  31113. }
  31114. } else if (end === -1) {
  31115. // We saw the first non-path separator, mark this as the end of our
  31116. // path component
  31117. matchedSlash = false;
  31118. end = i + 1;
  31119. }
  31120. }
  31121. if (end === -1) return '';
  31122. return path.slice(start, end);
  31123. }
  31124. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  31125. // in new Node.js versions, so only basename() above is backported here
  31126. exports.basename = function (path, ext) {
  31127. var f = basename(path);
  31128. if (ext && f.substr(-1 * ext.length) === ext) {
  31129. f = f.substr(0, f.length - ext.length);
  31130. }
  31131. return f;
  31132. };
  31133. exports.extname = function (path) {
  31134. if (typeof path !== 'string') path = path + '';
  31135. var startDot = -1;
  31136. var startPart = 0;
  31137. var end = -1;
  31138. var matchedSlash = true;
  31139. // Track the state of characters (if any) we see before our first dot and
  31140. // after any path separator we find
  31141. var preDotState = 0;
  31142. for (var i = path.length - 1; i >= 0; --i) {
  31143. var code = path.charCodeAt(i);
  31144. if (code === 47 /*/*/) {
  31145. // If we reached a path separator that was not part of a set of path
  31146. // separators at the end of the string, stop now
  31147. if (!matchedSlash) {
  31148. startPart = i + 1;
  31149. break;
  31150. }
  31151. continue;
  31152. }
  31153. if (end === -1) {
  31154. // We saw the first non-path separator, mark this as the end of our
  31155. // extension
  31156. matchedSlash = false;
  31157. end = i + 1;
  31158. }
  31159. if (code === 46 /*.*/) {
  31160. // If this is our first dot, mark it as the start of our extension
  31161. if (startDot === -1)
  31162. startDot = i;
  31163. else if (preDotState !== 1)
  31164. preDotState = 1;
  31165. } else if (startDot !== -1) {
  31166. // We saw a non-dot and non-path separator before our dot, so we should
  31167. // have a good chance at having a non-empty extension
  31168. preDotState = -1;
  31169. }
  31170. }
  31171. if (startDot === -1 || end === -1 ||
  31172. // We saw a non-dot character immediately before the dot
  31173. preDotState === 0 ||
  31174. // The (right-most) trimmed path component is exactly '..'
  31175. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  31176. return '';
  31177. }
  31178. return path.slice(startDot, end);
  31179. };
  31180. function filter (xs, f) {
  31181. if (xs.filter) return xs.filter(f);
  31182. var res = [];
  31183. for (var i = 0; i < xs.length; i++) {
  31184. if (f(xs[i], i, xs)) res.push(xs[i]);
  31185. }
  31186. return res;
  31187. }
  31188. // String.prototype.substr - negative index don't work in IE8
  31189. var substr = 'ab'.substr(-1) === 'b'
  31190. ? function (str, start, len) { return str.substr(start, len) }
  31191. : function (str, start, len) {
  31192. if (start < 0) start = str.length + start;
  31193. return str.substr(start, len);
  31194. }
  31195. ;
  31196. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/urlJoin.js":[function(require,module,exports) {
  31197. "use strict";
  31198. Object.defineProperty(exports, "__esModule", {
  31199. value: true
  31200. });
  31201. exports.urlJoin = urlJoin;
  31202. var _path = _interopRequireDefault(require("path"));
  31203. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31204. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
  31205. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
  31206. function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
  31207. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
  31208. // Function that properly handles path resolution for parts that have
  31209. // a protocol component like "http://".
  31210. function urlJoin() {
  31211. var protocolRegex = /^[a-zA-Z]+:\/\//;
  31212. var lastRoot = -1;
  31213. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  31214. args[_key] = arguments[_key];
  31215. }
  31216. for (var i = 0, l = args.length; i < l; i++) {
  31217. if (protocolRegex.test(args[i])) {
  31218. lastRoot = i;
  31219. }
  31220. }
  31221. if (lastRoot === -1) {
  31222. return _path.default.join.apply(_path.default, args).replace(/\\/g, '/');
  31223. } else {
  31224. var parts = lastRoot <= 0 ? args : args.slice(lastRoot);
  31225. var protocol = parts[0].match(protocolRegex)[0];
  31226. parts[0] = parts[0].substring(protocol.length);
  31227. return (protocol + _path.default.join.apply(_path.default, _toConsumableArray(parts))).replace(/\\/g, '/');
  31228. }
  31229. }
  31230. },{"path":"../node_modules/path-browserify/index.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  31231. "use strict";
  31232. Object.defineProperty(exports, "__esModule", {
  31233. value: true
  31234. });
  31235. exports.LRUCache = void 0;
  31236. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31237. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31238. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31239. // Fires at the end of the frame and before the next one
  31240. function enqueueMicrotask(callback) {
  31241. Promise.resolve().then(callback);
  31242. }
  31243. var LRUCache =
  31244. /*#__PURE__*/
  31245. function () {
  31246. function LRUCache() {
  31247. _classCallCheck(this, LRUCache);
  31248. // options
  31249. this.maxSize = 800;
  31250. this.minSize = 600;
  31251. this.unloadPercent = 0.05; // "itemSet" doubles as both the list of the full set of items currently
  31252. // stored in the cache (keys) as well as a map to the time the item was last
  31253. // used so it can be sorted appropriately.
  31254. this.itemSet = new Map();
  31255. this.itemList = [];
  31256. this.usedSet = new Set();
  31257. this.callbacks = new Map();
  31258. this.unloadPriorityCallback = null;
  31259. var itemSet = this.itemSet;
  31260. this.defaultPriorityCallback = function (item) {
  31261. return itemSet.get(item);
  31262. };
  31263. } // Returns whether or not the cache has reached the maximum size
  31264. _createClass(LRUCache, [{
  31265. key: "isFull",
  31266. value: function isFull() {
  31267. return this.itemSet.size >= this.maxSize;
  31268. }
  31269. }, {
  31270. key: "add",
  31271. value: function add(item, removeCb) {
  31272. var itemSet = this.itemSet;
  31273. if (itemSet.has(item)) {
  31274. return false;
  31275. }
  31276. if (this.isFull()) {
  31277. return false;
  31278. }
  31279. var usedSet = this.usedSet;
  31280. var itemList = this.itemList;
  31281. var callbacks = this.callbacks;
  31282. itemList.push(item);
  31283. usedSet.add(item);
  31284. itemSet.set(item, Date.now());
  31285. callbacks.set(item, removeCb);
  31286. return true;
  31287. }
  31288. }, {
  31289. key: "remove",
  31290. value: function remove(item) {
  31291. var usedSet = this.usedSet;
  31292. var itemSet = this.itemSet;
  31293. var itemList = this.itemList;
  31294. var callbacks = this.callbacks;
  31295. if (itemSet.has(item)) {
  31296. callbacks.get(item)(item);
  31297. var index = itemList.indexOf(item);
  31298. itemList.splice(index, 1);
  31299. usedSet.delete(item);
  31300. itemSet.delete(item);
  31301. callbacks.delete(item);
  31302. return true;
  31303. }
  31304. return false;
  31305. }
  31306. }, {
  31307. key: "markUsed",
  31308. value: function markUsed(item) {
  31309. var itemSet = this.itemSet;
  31310. var usedSet = this.usedSet;
  31311. if (itemSet.has(item) && !usedSet.has(item)) {
  31312. itemSet.set(item, Date.now());
  31313. usedSet.add(item);
  31314. }
  31315. }
  31316. }, {
  31317. key: "markAllUnused",
  31318. value: function markAllUnused() {
  31319. this.usedSet.clear();
  31320. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  31321. // Maybe call it "cleanup" or "unloadToMinSize"
  31322. }, {
  31323. key: "unloadUnusedContent",
  31324. value: function unloadUnusedContent() {
  31325. var unloadPercent = this.unloadPercent;
  31326. var targetSize = this.minSize;
  31327. var itemList = this.itemList;
  31328. var itemSet = this.itemSet;
  31329. var usedSet = this.usedSet;
  31330. var callbacks = this.callbacks;
  31331. var unused = itemList.length - usedSet.size;
  31332. var excess = itemList.length - targetSize;
  31333. var unloadPriorityCallback = this.unloadPriorityCallback || this.defaultPriorityCallback;
  31334. if (excess > 0 && unused > 0) {
  31335. // used items should be at the end of the array
  31336. itemList.sort(function (a, b) {
  31337. var usedA = usedSet.has(a);
  31338. var usedB = usedSet.has(b);
  31339. if (usedA && usedB) {
  31340. // If they're both used then don't bother moving them
  31341. return 0;
  31342. } else if (!usedA && !usedB) {
  31343. // Use the sort function otherwise
  31344. // higher priority should be further to the left
  31345. return unloadPriorityCallback(b) - unloadPriorityCallback(a);
  31346. } else {
  31347. // If one is used and the other is not move the used one towards the end of the array
  31348. return usedA ? 1 : -1;
  31349. }
  31350. }); // address corner cases where the minSize might be zero or smaller than maxSize - minSize,
  31351. // which would result in a very small or no items being unloaded.
  31352. var unusedExcess = Math.min(excess, unused);
  31353. var maxUnload = Math.max(targetSize * unloadPercent, unusedExcess * unloadPercent);
  31354. var nodesToUnload = Math.min(maxUnload, unused);
  31355. nodesToUnload = Math.ceil(nodesToUnload);
  31356. var removedItems = itemList.splice(0, nodesToUnload);
  31357. for (var i = 0, l = removedItems.length; i < l; i++) {
  31358. var item = removedItems[i];
  31359. callbacks.get(item)(item);
  31360. itemSet.delete(item);
  31361. callbacks.delete(item);
  31362. }
  31363. }
  31364. }
  31365. }, {
  31366. key: "scheduleUnload",
  31367. value: function scheduleUnload() {
  31368. var _this = this;
  31369. var markAllUnused = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  31370. if (!this.scheduled) {
  31371. this.scheduled = true;
  31372. enqueueMicrotask(function () {
  31373. _this.scheduled = false;
  31374. _this.unloadUnusedContent();
  31375. if (markAllUnused) {
  31376. _this.markAllUnused();
  31377. }
  31378. });
  31379. }
  31380. }
  31381. }]);
  31382. return LRUCache;
  31383. }();
  31384. exports.LRUCache = LRUCache;
  31385. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  31386. "use strict";
  31387. Object.defineProperty(exports, "__esModule", {
  31388. value: true
  31389. });
  31390. exports.PriorityQueue = void 0;
  31391. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31392. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31393. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31394. var PriorityQueue =
  31395. /*#__PURE__*/
  31396. function () {
  31397. function PriorityQueue() {
  31398. _classCallCheck(this, PriorityQueue);
  31399. // options
  31400. this.maxJobs = 6;
  31401. this.items = [];
  31402. this.callbacks = new Map();
  31403. this.currJobs = 0;
  31404. this.scheduled = false;
  31405. this.autoUpdate = true;
  31406. this.priorityCallback = function () {
  31407. throw new Error('PriorityQueue: PriorityCallback function not defined.');
  31408. };
  31409. }
  31410. _createClass(PriorityQueue, [{
  31411. key: "sort",
  31412. value: function sort() {
  31413. var priorityCallback = this.priorityCallback;
  31414. var items = this.items;
  31415. items.sort(function (a, b) {
  31416. return priorityCallback(a) - priorityCallback(b);
  31417. });
  31418. }
  31419. }, {
  31420. key: "add",
  31421. value: function add(item, callback) {
  31422. var _this = this;
  31423. return new Promise(function (resolve, reject) {
  31424. var prCallback = function prCallback() {
  31425. return callback.apply(void 0, arguments).then(resolve).catch(reject);
  31426. };
  31427. var items = _this.items;
  31428. var callbacks = _this.callbacks;
  31429. items.push(item);
  31430. callbacks.set(item, prCallback);
  31431. if (_this.autoUpdate) {
  31432. _this.scheduleJobRun();
  31433. }
  31434. });
  31435. }
  31436. }, {
  31437. key: "remove",
  31438. value: function remove(item) {
  31439. var items = this.items;
  31440. var callbacks = this.callbacks;
  31441. var index = items.indexOf(item);
  31442. if (index !== -1) {
  31443. items.splice(index, 1);
  31444. callbacks.delete(item);
  31445. }
  31446. }
  31447. }, {
  31448. key: "tryRunJobs",
  31449. value: function tryRunJobs() {
  31450. var _this2 = this;
  31451. this.sort();
  31452. var items = this.items;
  31453. var callbacks = this.callbacks;
  31454. var maxJobs = this.maxJobs;
  31455. var currJobs = this.currJobs;
  31456. while (maxJobs > currJobs && items.length > 0) {
  31457. currJobs++;
  31458. var item = items.pop();
  31459. var callback = callbacks.get(item);
  31460. callbacks.delete(item);
  31461. callback(item).then(function () {
  31462. _this2.currJobs--;
  31463. if (_this2.autoUpdate) {
  31464. _this2.scheduleJobRun();
  31465. }
  31466. }).catch(function () {
  31467. _this2.currJobs--;
  31468. if (_this2.autoUpdate) {
  31469. _this2.scheduleJobRun();
  31470. }
  31471. });
  31472. }
  31473. this.currJobs = currJobs;
  31474. }
  31475. }, {
  31476. key: "scheduleJobRun",
  31477. value: function scheduleJobRun() {
  31478. var _this3 = this;
  31479. if (!this.scheduled) {
  31480. requestAnimationFrame(function () {
  31481. _this3.tryRunJobs();
  31482. _this3.scheduled = false;
  31483. });
  31484. this.scheduled = true;
  31485. }
  31486. }
  31487. }]);
  31488. return PriorityQueue;
  31489. }();
  31490. exports.PriorityQueue = PriorityQueue;
  31491. },{}],"../src/base/constants.js":[function(require,module,exports) {
  31492. "use strict";
  31493. Object.defineProperty(exports, "__esModule", {
  31494. value: true
  31495. });
  31496. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  31497. var UNLOADED = 0;
  31498. exports.UNLOADED = UNLOADED;
  31499. var LOADING = 1;
  31500. exports.LOADING = LOADING;
  31501. var PARSING = 2;
  31502. exports.PARSING = PARSING;
  31503. var LOADED = 3;
  31504. exports.LOADED = LOADED;
  31505. var FAILED = 4;
  31506. exports.FAILED = FAILED;
  31507. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  31508. "use strict";
  31509. Object.defineProperty(exports, "__esModule", {
  31510. value: true
  31511. });
  31512. exports.traverseSet = traverseSet;
  31513. exports.determineFrustumSet = determineFrustumSet;
  31514. exports.markUsedSetLeaves = markUsedSetLeaves;
  31515. exports.skipTraversal = skipTraversal;
  31516. exports.toggleTiles = toggleTiles;
  31517. var _constants = require("./constants.js");
  31518. function isDownloadFinished(value) {
  31519. return value === _constants.LOADED || value === _constants.FAILED;
  31520. } // Checks whether this tile was last used on the given frame.
  31521. function isUsedThisFrame(tile, frameCount) {
  31522. return tile.__lastFrameVisited === frameCount && tile.__used;
  31523. } // Resets the frame frame information for the given tile
  31524. function resetFrameState(tile, frameCount) {
  31525. if (tile.__lastFrameVisited !== frameCount) {
  31526. tile.__lastFrameVisited = frameCount;
  31527. tile.__used = false;
  31528. tile.__inFrustum = false;
  31529. tile.__isLeaf = false;
  31530. tile.__visible = false;
  31531. tile.__active = false;
  31532. tile.__error = 0;
  31533. tile.__childrenWereVisible = false;
  31534. tile.__allChildrenLoaded = false;
  31535. }
  31536. } // Recursively mark tiles used down to the next tile with content
  31537. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  31538. resetFrameState(tile, frameCount);
  31539. tile.__used = true;
  31540. lruCache.markUsed(tile);
  31541. if (tile.__contentEmpty) {
  31542. var children = tile.children;
  31543. for (var i = 0, l = children.length; i < l; i++) {
  31544. recursivelyMarkUsed(children[i], frameCount, lruCache);
  31545. }
  31546. }
  31547. }
  31548. function recursivelyLoadTiles(tile, depthFromRenderedParent, renderer) {
  31549. // Try to load any external tile set children if the external tile set has loaded.
  31550. var doTraverse = tile.__contentEmpty && (!tile.__externalTileSet || isDownloadFinished(tile.__loadingState));
  31551. if (doTraverse) {
  31552. var children = tile.children;
  31553. for (var i = 0, l = children.length; i < l; i++) {
  31554. // don't increment depth to rendered parent here because we should treat
  31555. // the next layer of rendered children as just a single depth away for the
  31556. // sake of sorting.
  31557. var child = children[i];
  31558. child.__depthFromRenderedParent = depthFromRenderedParent;
  31559. recursivelyLoadTiles(child, depthFromRenderedParent, renderer);
  31560. }
  31561. } else {
  31562. renderer.requestTileContents(tile);
  31563. }
  31564. } // Helper function for recursively traversing a tile set. If `beforeCb` returns `true` then the
  31565. // traversal will end early.
  31566. function traverseSet(tile) {
  31567. var beforeCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  31568. var afterCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  31569. var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  31570. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  31571. if (beforeCb && beforeCb(tile, parent, depth)) {
  31572. if (afterCb) {
  31573. afterCb(tile, parent, depth);
  31574. }
  31575. return;
  31576. }
  31577. var children = tile.children;
  31578. for (var i = 0, l = children.length; i < l; i++) {
  31579. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  31580. }
  31581. if (afterCb) {
  31582. afterCb(tile, parent, depth);
  31583. }
  31584. } // Determine which tiles are within the camera frustum.
  31585. // TODO: this is marking items as used in the lrucache, which means some data is
  31586. // being kept around that isn't being used -- is that okay?
  31587. function determineFrustumSet(tile, renderer) {
  31588. var stats = renderer.stats;
  31589. var frameCount = renderer.frameCount;
  31590. var errorTarget = renderer.errorTarget;
  31591. var maxDepth = renderer.maxDepth;
  31592. var loadSiblings = renderer.loadSiblings;
  31593. var lruCache = renderer.lruCache;
  31594. var stopAtEmptyTiles = renderer.stopAtEmptyTiles;
  31595. resetFrameState(tile, frameCount); // Early out if this tile is not within view.
  31596. var inFrustum = renderer.tileInView(tile);
  31597. if (inFrustum === false) {
  31598. return false;
  31599. }
  31600. tile.__used = true;
  31601. lruCache.markUsed(tile);
  31602. tile.__inFrustum = true;
  31603. stats.inFrustum++; // Early out if this tile has less error than we're targeting but don't stop
  31604. // at an external tile set.
  31605. if ((stopAtEmptyTiles || !tile.__contentEmpty) && !tile.__externalTileSet) {
  31606. var error = renderer.calculateError(tile);
  31607. tile.__error = error;
  31608. if (error <= errorTarget) {
  31609. return true;
  31610. } // Early out if we've reached the maximum allowed depth.
  31611. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  31612. return true;
  31613. }
  31614. } // Traverse children and see if any children are in view.
  31615. var anyChildrenUsed = false;
  31616. var children = tile.children;
  31617. for (var i = 0, l = children.length; i < l; i++) {
  31618. var c = children[i];
  31619. var r = determineFrustumSet(c, renderer);
  31620. anyChildrenUsed = anyChildrenUsed || r;
  31621. } // If there are children within view and we are loading siblings then mark
  31622. // all sibling tiles as used, as well.
  31623. if (anyChildrenUsed && loadSiblings) {
  31624. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  31625. var _c = children[_i];
  31626. recursivelyMarkUsed(_c, frameCount, lruCache);
  31627. }
  31628. }
  31629. return true;
  31630. } // Traverse and mark the tiles that are at the leaf nodes of the "used" tree.
  31631. function markUsedSetLeaves(tile, renderer) {
  31632. var stats = renderer.stats;
  31633. var frameCount = renderer.frameCount;
  31634. if (!isUsedThisFrame(tile, frameCount)) {
  31635. return;
  31636. }
  31637. stats.used++; // This tile is a leaf if none of the children had been used.
  31638. var children = tile.children;
  31639. var anyChildrenUsed = false;
  31640. for (var i = 0, l = children.length; i < l; i++) {
  31641. var c = children[i];
  31642. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  31643. }
  31644. if (!anyChildrenUsed) {
  31645. // TODO: This isn't necessarily right because it's possible that a parent tile is considered in the
  31646. // frustum while the child tiles are not, making them unused. If all children have loaded and were properly
  31647. // considered to be in the used set then we shouldn't set ourselves to a leaf here.
  31648. tile.__isLeaf = true;
  31649. } else {
  31650. var childrenWereVisible = false;
  31651. var allChildrenLoaded = true;
  31652. for (var _i2 = 0, _l2 = children.length; _i2 < _l2; _i2++) {
  31653. var _c2 = children[_i2];
  31654. markUsedSetLeaves(_c2, renderer);
  31655. childrenWereVisible = childrenWereVisible || _c2.__wasSetVisible || _c2.__childrenWereVisible;
  31656. if (isUsedThisFrame(_c2, frameCount)) {
  31657. var childLoaded = _c2.__allChildrenLoaded || !_c2.__contentEmpty && isDownloadFinished(_c2.__loadingState) || _c2.__externalTileSet && _c2.__loadingState === _constants.FAILED;
  31658. allChildrenLoaded = allChildrenLoaded && childLoaded;
  31659. }
  31660. }
  31661. tile.__childrenWereVisible = childrenWereVisible;
  31662. tile.__allChildrenLoaded = allChildrenLoaded;
  31663. }
  31664. } // Skip past tiles we consider unrenderable because they are outside the error threshold.
  31665. function skipTraversal(tile, renderer) {
  31666. var stats = renderer.stats;
  31667. var frameCount = renderer.frameCount;
  31668. if (!isUsedThisFrame(tile, frameCount)) {
  31669. return;
  31670. }
  31671. var parent = tile.parent;
  31672. var parentDepthToParent = parent ? parent.__depthFromRenderedParent : -1;
  31673. tile.__depthFromRenderedParent = parentDepthToParent; // Request the tile contents or mark it as visible if we've found a leaf.
  31674. var lruCache = renderer.lruCache;
  31675. if (tile.__isLeaf) {
  31676. tile.__depthFromRenderedParent++;
  31677. if (tile.__loadingState === _constants.LOADED) {
  31678. if (tile.__inFrustum) {
  31679. tile.__visible = true;
  31680. stats.visible++;
  31681. }
  31682. tile.__active = true;
  31683. stats.active++;
  31684. } else if (!lruCache.isFull() && (!tile.__contentEmpty || tile.__externalTileSet)) {
  31685. renderer.requestTileContents(tile);
  31686. }
  31687. return;
  31688. }
  31689. var errorRequirement = (renderer.errorTarget + 1) * renderer.errorThreshold;
  31690. var meetsSSE = tile.__error <= errorRequirement;
  31691. var includeTile = meetsSSE || tile.refine === 'ADD';
  31692. var hasModel = !tile.__contentEmpty;
  31693. var hasContent = hasModel || tile.__externalTileSet;
  31694. var loadedContent = isDownloadFinished(tile.__loadingState) && hasContent;
  31695. var childrenWereVisible = tile.__childrenWereVisible;
  31696. var children = tile.children;
  31697. var allChildrenHaveContent = tile.__allChildrenLoaded; // Increment the relative depth of the node to the nearest rendered parent if it has content
  31698. // and is being rendered.
  31699. if (includeTile && hasModel) {
  31700. tile.__depthFromRenderedParent++;
  31701. } // If we've met the SSE requirements and we can load content then fire a fetch.
  31702. if (includeTile && !loadedContent && !lruCache.isFull() && hasContent) {
  31703. renderer.requestTileContents(tile);
  31704. } // Only mark this tile as visible if it meets the screen space error requirements, has loaded content, not
  31705. // all children have loaded yet, and if no children were visible last frame. We want to keep children visible
  31706. // that _were_ visible to avoid a pop in level of detail as the camera moves around and parent / sibling tiles
  31707. // load in.
  31708. // Skip the tile entirely if there's no content to load
  31709. if (meetsSSE && !allChildrenHaveContent && !childrenWereVisible && loadedContent || tile.refine === 'ADD' && loadedContent) {
  31710. if (tile.__inFrustum) {
  31711. tile.__visible = true;
  31712. stats.visible++;
  31713. }
  31714. tile.__active = true;
  31715. stats.active++;
  31716. } // If we're additive then don't stop the traversal here because it doesn't matter whether the children load in
  31717. // at the same rate.
  31718. if (tile.refine !== 'ADD' && meetsSSE && !allChildrenHaveContent && loadedContent) {
  31719. // load the child content if we've found that we've been loaded so we can move down to the next tile
  31720. // layer when the data has loaded.
  31721. for (var i = 0, l = children.length; i < l; i++) {
  31722. var c = children[i];
  31723. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  31724. c.__depthFromRenderedParent = tile.__depthFromRenderedParent + 1;
  31725. recursivelyLoadTiles(c, c.__depthFromRenderedParent, renderer);
  31726. }
  31727. }
  31728. } else {
  31729. for (var _i3 = 0, _l3 = children.length; _i3 < _l3; _i3++) {
  31730. var _c3 = children[_i3];
  31731. if (isUsedThisFrame(_c3, frameCount)) {
  31732. skipTraversal(_c3, renderer);
  31733. }
  31734. }
  31735. }
  31736. } // Final traverse to toggle tile visibility.
  31737. function toggleTiles(tile, renderer) {
  31738. var frameCount = renderer.frameCount;
  31739. var isUsed = isUsedThisFrame(tile, frameCount);
  31740. if (isUsed || tile.__usedLastFrame) {
  31741. var setActive = false;
  31742. var setVisible = false;
  31743. if (isUsed) {
  31744. // enable visibility if active due to shadows
  31745. setActive = tile.__active;
  31746. if (renderer.displayActiveTiles) {
  31747. setVisible = tile.__active || tile.__visible;
  31748. } else {
  31749. setVisible = tile.__visible;
  31750. }
  31751. } // If the active or visible state changed then call the functions.
  31752. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  31753. if (tile.__wasSetActive !== setActive) {
  31754. renderer.setTileActive(tile, setActive);
  31755. }
  31756. if (tile.__wasSetVisible !== setVisible) {
  31757. renderer.setTileVisible(tile, setVisible);
  31758. }
  31759. }
  31760. tile.__wasSetActive = setActive;
  31761. tile.__wasSetVisible = setVisible;
  31762. tile.__usedLastFrame = isUsed;
  31763. var children = tile.children;
  31764. for (var i = 0, l = children.length; i < l; i++) {
  31765. var c = children[i];
  31766. toggleTiles(c, renderer);
  31767. }
  31768. }
  31769. }
  31770. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  31771. "use strict";
  31772. Object.defineProperty(exports, "__esModule", {
  31773. value: true
  31774. });
  31775. exports.TilesRendererBase = void 0;
  31776. var _path = _interopRequireDefault(require("path"));
  31777. var _urlJoin = require("../utilities/urlJoin.js");
  31778. var _LRUCache = require("../utilities/LRUCache.js");
  31779. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  31780. var _traverseFunctions = require("./traverseFunctions.js");
  31781. var _constants = require("./constants.js");
  31782. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31783. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31784. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31785. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31786. // Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  31787. var priorityCallback = function priorityCallback(tile) {
  31788. return 1 / (tile.__depthFromRenderedParent + 1);
  31789. };
  31790. var TilesRendererBase =
  31791. /*#__PURE__*/
  31792. function () {
  31793. _createClass(TilesRendererBase, [{
  31794. key: "rootTileSet",
  31795. get: function get() {
  31796. var tileSet = this.tileSets[this.rootURL];
  31797. if (!tileSet || tileSet instanceof Promise) {
  31798. return null;
  31799. } else {
  31800. return tileSet;
  31801. }
  31802. }
  31803. }, {
  31804. key: "root",
  31805. get: function get() {
  31806. var tileSet = this.rootTileSet;
  31807. return tileSet ? tileSet.root : null;
  31808. }
  31809. }]);
  31810. function TilesRendererBase(url) {
  31811. _classCallCheck(this, TilesRendererBase);
  31812. // state
  31813. this.tileSets = {};
  31814. this.rootURL = url;
  31815. this.fetchOptions = {};
  31816. var lruCache = new _LRUCache.LRUCache();
  31817. lruCache.unloadPriorityCallback = priorityCallback;
  31818. var downloadQueue = new _PriorityQueue.PriorityQueue();
  31819. downloadQueue.maxJobs = 4;
  31820. downloadQueue.priorityCallback = priorityCallback;
  31821. var parseQueue = new _PriorityQueue.PriorityQueue();
  31822. parseQueue.maxJobs = 1;
  31823. parseQueue.priorityCallback = priorityCallback;
  31824. this.lruCache = lruCache;
  31825. this.downloadQueue = downloadQueue;
  31826. this.parseQueue = parseQueue;
  31827. this.stats = {
  31828. parsing: 0,
  31829. downloading: 0,
  31830. failed: 0,
  31831. inFrustum: 0,
  31832. used: 0,
  31833. active: 0,
  31834. visible: 0
  31835. };
  31836. this.frameCount = 0; // options
  31837. this.errorTarget = 6.0;
  31838. this.errorThreshold = Infinity;
  31839. this.loadSiblings = true;
  31840. this.displayActiveTiles = false;
  31841. this.maxDepth = Infinity;
  31842. this.stopAtEmptyTiles = true;
  31843. }
  31844. _createClass(TilesRendererBase, [{
  31845. key: "traverse",
  31846. value: function traverse(beforecb, aftercb) {
  31847. var tileSets = this.tileSets;
  31848. var rootTileSet = tileSets[this.rootURL];
  31849. if (!rootTileSet || !rootTileSet.root) return;
  31850. (0, _traverseFunctions.traverseSet)(rootTileSet.root, beforecb, aftercb);
  31851. } // Public API
  31852. }, {
  31853. key: "update",
  31854. value: function update() {
  31855. var stats = this.stats;
  31856. var lruCache = this.lruCache;
  31857. var tileSets = this.tileSets;
  31858. var rootTileSet = tileSets[this.rootURL];
  31859. if (!(this.rootURL in tileSets)) {
  31860. this.loadRootTileSet(this.rootURL);
  31861. return;
  31862. } else if (!rootTileSet || !rootTileSet.root) {
  31863. return;
  31864. }
  31865. var root = rootTileSet.root;
  31866. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  31867. (0, _traverseFunctions.determineFrustumSet)(root, this);
  31868. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  31869. (0, _traverseFunctions.skipTraversal)(root, this);
  31870. (0, _traverseFunctions.toggleTiles)(root, this);
  31871. lruCache.scheduleUnload();
  31872. } // Overrideable
  31873. }, {
  31874. key: "parseTile",
  31875. value: function parseTile(buffer, tile, extension) {
  31876. return null;
  31877. }
  31878. }, {
  31879. key: "disposeTile",
  31880. value: function disposeTile(tile) {}
  31881. }, {
  31882. key: "preprocessNode",
  31883. value: function preprocessNode(tile, parentTile, tileSetDir) {
  31884. if (tile.content) {
  31885. // Fix old file formats
  31886. if (!('uri' in tile.content) && 'url' in tile.content) {
  31887. tile.content.uri = tile.content.url;
  31888. delete tile.content.url;
  31889. }
  31890. if (tile.content.uri) {
  31891. tile.content.uri = (0, _urlJoin.urlJoin)(tileSetDir, tile.content.uri);
  31892. } // NOTE: fix for some cases where tilesets provide the bounding volume
  31893. // but volumes are not present.
  31894. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  31895. delete tile.content.boundingVolume;
  31896. }
  31897. }
  31898. tile.parent = parentTile;
  31899. tile.children = tile.children || [];
  31900. var uri = tile.content && tile.content.uri;
  31901. if (uri) {
  31902. // "content" should only indicate loadable meshes, not external tile sets
  31903. var isExternalTileSet = /\.json$/i.test(tile.content.uri);
  31904. tile.__externalTileSet = isExternalTileSet;
  31905. tile.__contentEmpty = isExternalTileSet;
  31906. } else {
  31907. tile.__externalTileSet = false;
  31908. tile.__contentEmpty = true;
  31909. }
  31910. tile.__error = 0.0;
  31911. tile.__inFrustum = false;
  31912. tile.__isLeaf = false;
  31913. tile.__usedLastFrame = false;
  31914. tile.__used = false;
  31915. tile.__wasSetVisible = false;
  31916. tile.__visible = false;
  31917. tile.__childrenWereVisible = false;
  31918. tile.__allChildrenLoaded = false;
  31919. tile.__wasSetActive = false;
  31920. tile.__active = false;
  31921. tile.__loadingState = _constants.UNLOADED;
  31922. tile.__loadIndex = 0;
  31923. tile.__loadAbort = null;
  31924. tile.__depthFromRenderedParent = -1;
  31925. if (parentTile === null) {
  31926. tile.__depth = 0;
  31927. tile.refine = tile.refine || 'REPLACE';
  31928. } else {
  31929. tile.__depth = parentTile.__depth + 1;
  31930. tile.refine = tile.refine || parentTile.refine;
  31931. }
  31932. }
  31933. }, {
  31934. key: "setTileActive",
  31935. value: function setTileActive(tile, state) {}
  31936. }, {
  31937. key: "setTileVisible",
  31938. value: function setTileVisible(tile, state) {}
  31939. }, {
  31940. key: "calculateError",
  31941. value: function calculateError(tile) {
  31942. return 0;
  31943. }
  31944. }, {
  31945. key: "tileInView",
  31946. value: function tileInView(tile) {
  31947. return true;
  31948. } // Private Functions
  31949. }, {
  31950. key: "fetchTileSet",
  31951. value: function fetchTileSet(url, fetchOptions) {
  31952. var _this = this;
  31953. var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  31954. return fetch(url, fetchOptions).then(function (res) {
  31955. if (res.ok) {
  31956. return res.json();
  31957. } else {
  31958. throw new Error("TilesRenderer: Failed to load tileset \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  31959. }
  31960. }).then(function (json) {
  31961. var version = json.asset.version;
  31962. console.assert(version === '1.0' || version === '0.0', 'asset.version is expected to be a string of "1.0" or "0.0"');
  31963. var basePath = _path.default.dirname(url);
  31964. (0, _traverseFunctions.traverseSet)(json.root, function (node, parent) {
  31965. return _this.preprocessNode(node, parent, basePath);
  31966. }, null, parent, parent ? parent.__depth : 0);
  31967. return json;
  31968. });
  31969. }
  31970. }, {
  31971. key: "loadRootTileSet",
  31972. value: function loadRootTileSet(url) {
  31973. var tileSets = this.tileSets;
  31974. if (!(url in tileSets)) {
  31975. var pr = this.fetchTileSet(url, this.fetchOptions).then(function (json) {
  31976. tileSets[url] = json;
  31977. });
  31978. pr.catch(function (err) {
  31979. console.error(err);
  31980. tileSets[url] = err;
  31981. });
  31982. tileSets[url] = pr;
  31983. return pr;
  31984. } else if (tileSets[url] instanceof Error) {
  31985. return Promise.reject(tileSets[url]);
  31986. } else {
  31987. return Promise.resolve(tileSets[url]);
  31988. }
  31989. }
  31990. }, {
  31991. key: "requestTileContents",
  31992. value: function requestTileContents(tile) {
  31993. var _this2 = this;
  31994. // If the tile is already being loaded then don't
  31995. // start it again.
  31996. if (tile.__loadingState !== _constants.UNLOADED) {
  31997. return;
  31998. }
  31999. var stats = this.stats;
  32000. var lruCache = this.lruCache;
  32001. var downloadQueue = this.downloadQueue;
  32002. var parseQueue = this.parseQueue;
  32003. var isExternalTileSet = tile.__externalTileSet;
  32004. lruCache.add(tile, function (t) {
  32005. // Stop the load if it's started
  32006. if (t.__loadingState === _constants.LOADING) {
  32007. t.__loadAbort.abort();
  32008. t.__loadAbort = null;
  32009. } else if (isExternalTileSet) {
  32010. t.children.length = 0;
  32011. } else {
  32012. _this2.disposeTile(t);
  32013. } // Decrement stats
  32014. if (t.__loadingState === _constants.LOADING) {
  32015. stats.downloading--;
  32016. } else if (t.__loadingState === _constants.PARSING) {
  32017. stats.parsing--;
  32018. }
  32019. t.__loadingState = _constants.UNLOADED;
  32020. t.__loadIndex++;
  32021. parseQueue.remove(t);
  32022. downloadQueue.remove(t);
  32023. }); // Track a new load index so we avoid the condition where this load is stopped and
  32024. // another begins soon after so we don't parse twice.
  32025. tile.__loadIndex++;
  32026. var loadIndex = tile.__loadIndex;
  32027. var controller = new AbortController();
  32028. var signal = controller.signal;
  32029. stats.downloading++;
  32030. tile.__loadAbort = controller;
  32031. tile.__loadingState = _constants.LOADING;
  32032. var errorCallback = function errorCallback(e) {
  32033. // if it has been unloaded then the tile has been disposed
  32034. if (tile.__loadIndex !== loadIndex) {
  32035. return;
  32036. }
  32037. if (e.name !== 'AbortError') {
  32038. parseQueue.remove(tile);
  32039. downloadQueue.remove(tile);
  32040. if (tile.__loadingState === _constants.PARSING) {
  32041. stats.parsing--;
  32042. } else if (tile.__loadingState === _constants.LOADING) {
  32043. stats.downloading--;
  32044. }
  32045. stats.failed++;
  32046. console.error('TilesRenderer : Failed to load tile.');
  32047. console.error(e);
  32048. tile.__loadingState = _constants.FAILED;
  32049. } else {
  32050. lruCache.remove(tile);
  32051. }
  32052. };
  32053. if (isExternalTileSet) {
  32054. downloadQueue.add(tile, function (tile) {
  32055. // if it has been unloaded then the tile has been disposed
  32056. if (tile.__loadIndex !== loadIndex) {
  32057. return Promise.resolve();
  32058. }
  32059. return _this2.fetchTileSet(tile.content.uri, Object.assign({
  32060. signal: signal
  32061. }, _this2.fetchOptions), tile);
  32062. }).then(function (json) {
  32063. // if it has been unloaded then the tile has been disposed
  32064. if (tile.__loadIndex !== loadIndex) {
  32065. return;
  32066. }
  32067. stats.downloading--;
  32068. tile.__loadAbort = null;
  32069. tile.__loadingState = _constants.LOADED;
  32070. tile.children.push(json.root);
  32071. }).catch(errorCallback);
  32072. } else {
  32073. downloadQueue.add(tile, function (tile) {
  32074. if (tile.__loadIndex !== loadIndex) {
  32075. return Promise.resolve();
  32076. }
  32077. return fetch(tile.content.uri, Object.assign({
  32078. signal: signal
  32079. }, _this2.fetchOptions));
  32080. }).then(function (res) {
  32081. if (tile.__loadIndex !== loadIndex) {
  32082. return;
  32083. }
  32084. if (res.ok) {
  32085. return res.arrayBuffer();
  32086. } else {
  32087. throw new Error("Failed to load model with error code ".concat(res.status));
  32088. }
  32089. }).then(function (buffer) {
  32090. // if it has been unloaded then the tile has been disposed
  32091. if (tile.__loadIndex !== loadIndex) {
  32092. return;
  32093. }
  32094. stats.downloading--;
  32095. stats.parsing++;
  32096. tile.__loadAbort = null;
  32097. tile.__loadingState = _constants.PARSING;
  32098. return parseQueue.add(tile, function (tile) {
  32099. // if it has been unloaded then the tile has been disposed
  32100. if (tile.__loadIndex !== loadIndex) {
  32101. return Promise.resolve();
  32102. }
  32103. var uri = tile.content.uri;
  32104. var extension = uri.split(/\./g).pop();
  32105. return _this2.parseTile(buffer, tile, extension);
  32106. });
  32107. }).then(function () {
  32108. // if it has been unloaded then the tile has been disposed
  32109. if (tile.__loadIndex !== loadIndex) {
  32110. return;
  32111. }
  32112. stats.parsing--;
  32113. tile.__loadingState = _constants.LOADED;
  32114. if (tile.__wasSetVisible) {
  32115. _this2.setTileVisible(tile, true);
  32116. }
  32117. if (tile.__wasSetActive) {
  32118. _this2.setTileActive(tile, true);
  32119. }
  32120. }).catch(errorCallback);
  32121. }
  32122. }
  32123. }, {
  32124. key: "dispose",
  32125. value: function dispose() {
  32126. var lruCache = this.lruCache;
  32127. this.traverse(function (tile) {
  32128. lruCache.remove(tile);
  32129. });
  32130. }
  32131. }]);
  32132. return TilesRendererBase;
  32133. }();
  32134. exports.TilesRendererBase = TilesRendererBase;
  32135. },{"path":"../node_modules/path-browserify/index.js","../utilities/urlJoin.js":"../src/utilities/urlJoin.js","../utilities/LRUCache.js":"../src/utilities/LRUCache.js","../utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js","./traverseFunctions.js":"../src/base/traverseFunctions.js","./constants.js":"../src/base/constants.js"}],"../src/utilities/arrayToString.js":[function(require,module,exports) {
  32136. "use strict";
  32137. Object.defineProperty(exports, "__esModule", {
  32138. value: true
  32139. });
  32140. exports.arrayToString = arrayToString;
  32141. function arrayToString(array) {
  32142. var str = '';
  32143. for (var i = 0, l = array.length; i < l; i++) {
  32144. str += String.fromCharCode(array[i]);
  32145. }
  32146. return str;
  32147. }
  32148. },{}],"../src/utilities/FeatureTable.js":[function(require,module,exports) {
  32149. "use strict";
  32150. Object.defineProperty(exports, "__esModule", {
  32151. value: true
  32152. });
  32153. exports.BatchTable = exports.FeatureTable = void 0;
  32154. var _arrayToString = require("./arrayToString.js");
  32155. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  32156. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  32157. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  32158. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  32159. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  32160. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  32161. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  32162. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  32163. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32164. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  32165. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  32166. var FeatureTable =
  32167. /*#__PURE__*/
  32168. function () {
  32169. function FeatureTable(buffer, start, headerLength, binLength) {
  32170. _classCallCheck(this, FeatureTable);
  32171. this.buffer = buffer;
  32172. this.binOffset = start + headerLength;
  32173. this.binLength = binLength;
  32174. var header = null;
  32175. if (headerLength !== 0) {
  32176. var headerData = new Uint8Array(buffer, start, headerLength);
  32177. header = JSON.parse((0, _arrayToString.arrayToString)(headerData));
  32178. } else {
  32179. header = {};
  32180. }
  32181. this.header = header;
  32182. }
  32183. _createClass(FeatureTable, [{
  32184. key: "getKeys",
  32185. value: function getKeys() {
  32186. return Object.keys(this.header);
  32187. }
  32188. }, {
  32189. key: "getData",
  32190. value: function getData(key, count) {
  32191. var defaultComponentType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32192. var defaultType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  32193. var header = this.header;
  32194. if (!(key in header)) {
  32195. return null;
  32196. }
  32197. var feature = header[key];
  32198. if (!(feature instanceof Object)) {
  32199. return feature;
  32200. } else if (Array.isArray(feature)) {
  32201. return feature;
  32202. } else {
  32203. var buffer = this.buffer,
  32204. binOffset = this.binOffset,
  32205. binLength = this.binLength;
  32206. var byteOffset = feature.byteOffset || 0;
  32207. var featureType = feature.type || defaultType;
  32208. var featureComponentType = feature.componentType || defaultComponentType;
  32209. if ('type' in feature && defaultType && feature.type !== defaultType) {
  32210. throw new Error('FeatureTable: Specified type does not match expected type.');
  32211. }
  32212. var stride;
  32213. switch (featureType) {
  32214. case 'SCALAR':
  32215. stride = 1;
  32216. break;
  32217. case 'VEC2':
  32218. stride = 2;
  32219. break;
  32220. case 'VEC3':
  32221. stride = 3;
  32222. break;
  32223. case 'VEC4':
  32224. stride = 4;
  32225. break;
  32226. default:
  32227. throw new Error("FeatureTable : Feature type not provided for \"".concat(key, "\"."));
  32228. }
  32229. var data;
  32230. var arrayStart = binOffset + byteOffset;
  32231. var arrayLength = count * stride;
  32232. switch (featureComponentType) {
  32233. case 'BYTE':
  32234. data = new Int8Array(buffer, arrayStart, arrayLength);
  32235. break;
  32236. case 'UNSIGNED_BYTE':
  32237. data = new Uint8Array(buffer, arrayStart, arrayLength);
  32238. break;
  32239. case 'SHORT':
  32240. data = new Int16Array(buffer, arrayStart, arrayLength);
  32241. break;
  32242. case 'UNSIGNED_SHORT':
  32243. data = new Uint16Array(buffer, arrayStart, arrayLength);
  32244. break;
  32245. case 'INT':
  32246. data = new Int32Array(buffer, arrayStart, arrayLength);
  32247. break;
  32248. case 'UNSIGNED_INT':
  32249. data = new Uint32Array(buffer, arrayStart, arrayLength);
  32250. break;
  32251. case 'FLOAT':
  32252. data = new Float32Array(buffer, arrayStart, arrayLength);
  32253. break;
  32254. case 'DOUBLE':
  32255. data = new Float64Array(buffer, arrayStart, arrayLength);
  32256. break;
  32257. default:
  32258. throw new Error("FeatureTable : Feature component type not provided for \"".concat(key, "\"."));
  32259. }
  32260. var dataEnd = arrayStart + arrayLength * data.BYTES_PER_ELEMENT;
  32261. if (dataEnd > binOffset + binLength) {
  32262. throw new Error('FeatureTable: Feature data read outside binary body length.');
  32263. }
  32264. return data;
  32265. }
  32266. }
  32267. }]);
  32268. return FeatureTable;
  32269. }();
  32270. exports.FeatureTable = FeatureTable;
  32271. var BatchTable =
  32272. /*#__PURE__*/
  32273. function (_FeatureTable) {
  32274. _inherits(BatchTable, _FeatureTable);
  32275. function BatchTable(buffer, batchSize, start, headerLength, binLength) {
  32276. var _this;
  32277. _classCallCheck(this, BatchTable);
  32278. _this = _possibleConstructorReturn(this, _getPrototypeOf(BatchTable).call(this, buffer, start, headerLength, binLength));
  32279. _this.batchSize = batchSize;
  32280. return _this;
  32281. }
  32282. _createClass(BatchTable, [{
  32283. key: "getData",
  32284. value: function getData(key) {
  32285. var componentType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  32286. var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32287. return _get(_getPrototypeOf(BatchTable.prototype), "getData", this).call(this, key, this.batchSize, type, componentType);
  32288. }
  32289. }]);
  32290. return BatchTable;
  32291. }(FeatureTable);
  32292. exports.BatchTable = BatchTable;
  32293. },{"./arrayToString.js":"../src/utilities/arrayToString.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  32294. "use strict";
  32295. Object.defineProperty(exports, "__esModule", {
  32296. value: true
  32297. });
  32298. exports.B3DMLoaderBase = void 0;
  32299. var _FeatureTable = require("../utilities/FeatureTable.js");
  32300. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32301. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  32302. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  32303. var B3DMLoaderBase =
  32304. /*#__PURE__*/
  32305. function () {
  32306. function B3DMLoaderBase() {
  32307. _classCallCheck(this, B3DMLoaderBase);
  32308. this.fetchOptions = {};
  32309. }
  32310. _createClass(B3DMLoaderBase, [{
  32311. key: "load",
  32312. value: function load(url) {
  32313. var _this = this;
  32314. return fetch(url, this.fetchOptions).then(function (res) {
  32315. if (!res.ok) {
  32316. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  32317. }
  32318. return res.arrayBuffer();
  32319. }).then(function (buffer) {
  32320. return _this.parse(buffer);
  32321. });
  32322. }
  32323. }, {
  32324. key: "parse",
  32325. value: function parse(buffer) {
  32326. // TODO: this should be able to take a uint8array with an offset and length
  32327. var dataView = new DataView(buffer); // 28-byte header
  32328. // 4 bytes
  32329. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  32330. console.assert(magic === 'b3dm'); // 4 bytes
  32331. var version = dataView.getUint32(4, true);
  32332. console.assert(version === 1); // 4 bytes
  32333. var byteLength = dataView.getUint32(8, true);
  32334. console.assert(byteLength === buffer.byteLength); // 4 bytes
  32335. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  32336. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  32337. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  32338. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  32339. var featureTableStart = 28;
  32340. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  32341. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  32342. var batchTable = new _FeatureTable.BatchTable(buffer, featureTable.getData('BATCH_LENGTH'), batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  32343. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  32344. var glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart);
  32345. return {
  32346. version: version,
  32347. featureTable: featureTable,
  32348. batchTable: batchTable,
  32349. glbBytes: glbBytes
  32350. };
  32351. }
  32352. }]);
  32353. return B3DMLoaderBase;
  32354. }();
  32355. exports.B3DMLoaderBase = B3DMLoaderBase;
  32356. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js"}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  32357. "use strict";
  32358. Object.defineProperty(exports, "__esModule", {
  32359. value: true
  32360. });
  32361. exports.GLTFLoader = void 0;
  32362. var _threeModule = require("../../../build/three.module.js");
  32363. var GLTFLoader = function () {
  32364. function GLTFLoader(manager) {
  32365. _threeModule.Loader.call(this, manager);
  32366. this.dracoLoader = null;
  32367. this.ddsLoader = null;
  32368. this.ktx2Loader = null;
  32369. this.meshoptDecoder = null;
  32370. this.pluginCallbacks = [];
  32371. this.register(function (parser) {
  32372. return new GLTFMaterialsClearcoatExtension(parser);
  32373. });
  32374. this.register(function (parser) {
  32375. return new GLTFTextureBasisUExtension(parser);
  32376. });
  32377. this.register(function (parser) {
  32378. return new GLTFTextureWebPExtension(parser);
  32379. });
  32380. this.register(function (parser) {
  32381. return new GLTFMaterialsTransmissionExtension(parser);
  32382. });
  32383. this.register(function (parser) {
  32384. return new GLTFLightsExtension(parser);
  32385. });
  32386. this.register(function (parser) {
  32387. return new GLTFMeshoptCompression(parser);
  32388. });
  32389. }
  32390. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  32391. constructor: GLTFLoader,
  32392. load: function (url, onLoad, onProgress, onError) {
  32393. var scope = this;
  32394. var resourcePath;
  32395. if (this.resourcePath !== '') {
  32396. resourcePath = this.resourcePath;
  32397. } else if (this.path !== '') {
  32398. resourcePath = this.path;
  32399. } else {
  32400. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  32401. } // Tells the LoadingManager to track an extra item, which resolves after
  32402. // the model is fully loaded. This means the count of items loaded will
  32403. // be incorrect, but ensures manager.onLoad() does not fire early.
  32404. this.manager.itemStart(url);
  32405. var _onError = function (e) {
  32406. if (onError) {
  32407. onError(e);
  32408. } else {
  32409. console.error(e);
  32410. }
  32411. scope.manager.itemError(url);
  32412. scope.manager.itemEnd(url);
  32413. };
  32414. var loader = new _threeModule.FileLoader(this.manager);
  32415. loader.setPath(this.path);
  32416. loader.setResponseType('arraybuffer');
  32417. loader.setRequestHeader(this.requestHeader);
  32418. loader.setWithCredentials(this.withCredentials);
  32419. loader.load(url, function (data) {
  32420. try {
  32421. scope.parse(data, resourcePath, function (gltf) {
  32422. onLoad(gltf);
  32423. scope.manager.itemEnd(url);
  32424. }, _onError);
  32425. } catch (e) {
  32426. _onError(e);
  32427. }
  32428. }, onProgress, _onError);
  32429. },
  32430. setDRACOLoader: function (dracoLoader) {
  32431. this.dracoLoader = dracoLoader;
  32432. return this;
  32433. },
  32434. setDDSLoader: function (ddsLoader) {
  32435. this.ddsLoader = ddsLoader;
  32436. return this;
  32437. },
  32438. setKTX2Loader: function (ktx2Loader) {
  32439. this.ktx2Loader = ktx2Loader;
  32440. return this;
  32441. },
  32442. setMeshoptDecoder: function (meshoptDecoder) {
  32443. this.meshoptDecoder = meshoptDecoder;
  32444. return this;
  32445. },
  32446. register: function (callback) {
  32447. if (this.pluginCallbacks.indexOf(callback) === -1) {
  32448. this.pluginCallbacks.push(callback);
  32449. }
  32450. return this;
  32451. },
  32452. unregister: function (callback) {
  32453. if (this.pluginCallbacks.indexOf(callback) !== -1) {
  32454. this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
  32455. }
  32456. return this;
  32457. },
  32458. parse: function (data, path, onLoad, onError) {
  32459. var content;
  32460. var extensions = {};
  32461. var plugins = {};
  32462. if (typeof data === 'string') {
  32463. content = data;
  32464. } else {
  32465. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  32466. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  32467. try {
  32468. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  32469. } catch (error) {
  32470. if (onError) onError(error);
  32471. return;
  32472. }
  32473. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  32474. } else {
  32475. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  32476. }
  32477. }
  32478. var json = JSON.parse(content);
  32479. if (json.asset === undefined || json.asset.version[0] < 2) {
  32480. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  32481. return;
  32482. }
  32483. var parser = new GLTFParser(json, {
  32484. path: path || this.resourcePath || '',
  32485. crossOrigin: this.crossOrigin,
  32486. manager: this.manager,
  32487. ktx2Loader: this.ktx2Loader,
  32488. meshoptDecoder: this.meshoptDecoder
  32489. });
  32490. parser.fileLoader.setRequestHeader(this.requestHeader);
  32491. for (var i = 0; i < this.pluginCallbacks.length; i++) {
  32492. var plugin = this.pluginCallbacks[i](parser);
  32493. plugins[plugin.name] = plugin; // Workaround to avoid determining as unknown extension
  32494. // in addUnknownExtensionsToUserData().
  32495. // Remove this workaround if we move all the existing
  32496. // extension handlers to plugin system
  32497. extensions[plugin.name] = true;
  32498. }
  32499. if (json.extensionsUsed) {
  32500. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  32501. var extensionName = json.extensionsUsed[i];
  32502. var extensionsRequired = json.extensionsRequired || [];
  32503. switch (extensionName) {
  32504. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  32505. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  32506. break;
  32507. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  32508. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  32509. break;
  32510. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  32511. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  32512. break;
  32513. case EXTENSIONS.MSFT_TEXTURE_DDS:
  32514. extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader);
  32515. break;
  32516. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  32517. extensions[extensionName] = new GLTFTextureTransformExtension();
  32518. break;
  32519. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  32520. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  32521. break;
  32522. default:
  32523. if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) {
  32524. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  32525. }
  32526. }
  32527. }
  32528. }
  32529. parser.setExtensions(extensions);
  32530. parser.setPlugins(plugins);
  32531. parser.parse(onLoad, onError);
  32532. }
  32533. });
  32534. /* GLTFREGISTRY */
  32535. function GLTFRegistry() {
  32536. var objects = {};
  32537. return {
  32538. get: function (key) {
  32539. return objects[key];
  32540. },
  32541. add: function (key, object) {
  32542. objects[key] = object;
  32543. },
  32544. remove: function (key) {
  32545. delete objects[key];
  32546. },
  32547. removeAll: function () {
  32548. objects = {};
  32549. }
  32550. };
  32551. }
  32552. /*********************************/
  32553. /********** EXTENSIONS ***********/
  32554. /*********************************/
  32555. var EXTENSIONS = {
  32556. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  32557. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  32558. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  32559. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  32560. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  32561. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  32562. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  32563. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  32564. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  32565. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  32566. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  32567. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  32568. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  32569. };
  32570. /**
  32571. * DDS Texture Extension
  32572. *
  32573. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  32574. *
  32575. */
  32576. function GLTFTextureDDSExtension(ddsLoader) {
  32577. if (!ddsLoader) {
  32578. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  32579. }
  32580. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  32581. this.ddsLoader = ddsLoader;
  32582. }
  32583. /**
  32584. * Punctual Lights Extension
  32585. *
  32586. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  32587. */
  32588. function GLTFLightsExtension(parser) {
  32589. this.parser = parser;
  32590. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // Object3D instance caches
  32591. this.cache = {
  32592. refs: {},
  32593. uses: {}
  32594. };
  32595. }
  32596. GLTFLightsExtension.prototype._markDefs = function () {
  32597. var parser = this.parser;
  32598. var nodeDefs = this.parser.json.nodes || [];
  32599. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  32600. var nodeDef = nodeDefs[nodeIndex];
  32601. if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) {
  32602. parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light);
  32603. }
  32604. }
  32605. };
  32606. GLTFLightsExtension.prototype._loadLight = function (lightIndex) {
  32607. var parser = this.parser;
  32608. var cacheKey = 'light:' + lightIndex;
  32609. var dependency = parser.cache.get(cacheKey);
  32610. if (dependency) return dependency;
  32611. var json = parser.json;
  32612. var extensions = json.extensions && json.extensions[this.name] || {};
  32613. var lightDefs = extensions.lights || [];
  32614. var lightDef = lightDefs[lightIndex];
  32615. var lightNode;
  32616. var color = new _threeModule.Color(0xffffff);
  32617. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  32618. var range = lightDef.range !== undefined ? lightDef.range : 0;
  32619. switch (lightDef.type) {
  32620. case 'directional':
  32621. lightNode = new _threeModule.DirectionalLight(color);
  32622. lightNode.target.position.set(0, 0, -1);
  32623. lightNode.add(lightNode.target);
  32624. break;
  32625. case 'point':
  32626. lightNode = new _threeModule.PointLight(color);
  32627. lightNode.distance = range;
  32628. break;
  32629. case 'spot':
  32630. lightNode = new _threeModule.SpotLight(color);
  32631. lightNode.distance = range; // Handle spotlight properties.
  32632. lightDef.spot = lightDef.spot || {};
  32633. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  32634. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  32635. lightNode.angle = lightDef.spot.outerConeAngle;
  32636. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  32637. lightNode.target.position.set(0, 0, -1);
  32638. lightNode.add(lightNode.target);
  32639. break;
  32640. default:
  32641. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  32642. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  32643. // here, because node-level parsing will only override position if explicitly specified.
  32644. lightNode.position.set(0, 0, 0);
  32645. lightNode.decay = 2;
  32646. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  32647. lightNode.name = parser.createUniqueName(lightDef.name || 'light_' + lightIndex);
  32648. dependency = Promise.resolve(lightNode);
  32649. parser.cache.add(cacheKey, dependency);
  32650. return dependency;
  32651. };
  32652. GLTFLightsExtension.prototype.createNodeAttachment = function (nodeIndex) {
  32653. var self = this;
  32654. var parser = this.parser;
  32655. var json = parser.json;
  32656. var nodeDef = json.nodes[nodeIndex];
  32657. var lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {};
  32658. var lightIndex = lightDef.light;
  32659. if (lightIndex === undefined) return null;
  32660. return this._loadLight(lightIndex).then(function (light) {
  32661. return parser._getNodeRef(self.cache, lightIndex, light);
  32662. });
  32663. };
  32664. /**
  32665. * Unlit Materials Extension
  32666. *
  32667. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  32668. */
  32669. function GLTFMaterialsUnlitExtension() {
  32670. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  32671. }
  32672. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  32673. return _threeModule.MeshBasicMaterial;
  32674. };
  32675. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  32676. var pending = [];
  32677. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32678. materialParams.opacity = 1.0;
  32679. var metallicRoughness = materialDef.pbrMetallicRoughness;
  32680. if (metallicRoughness) {
  32681. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  32682. var array = metallicRoughness.baseColorFactor;
  32683. materialParams.color.fromArray(array);
  32684. materialParams.opacity = array[3];
  32685. }
  32686. if (metallicRoughness.baseColorTexture !== undefined) {
  32687. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  32688. }
  32689. }
  32690. return Promise.all(pending);
  32691. };
  32692. /**
  32693. * Clearcoat Materials Extension
  32694. *
  32695. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  32696. */
  32697. function GLTFMaterialsClearcoatExtension(parser) {
  32698. this.parser = parser;
  32699. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  32700. }
  32701. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function (materialIndex) {
  32702. var parser = this.parser;
  32703. var materialDef = parser.json.materials[materialIndex];
  32704. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  32705. return _threeModule.MeshPhysicalMaterial;
  32706. };
  32707. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function (materialIndex, materialParams) {
  32708. var parser = this.parser;
  32709. var materialDef = parser.json.materials[materialIndex];
  32710. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  32711. return Promise.resolve();
  32712. }
  32713. var pending = [];
  32714. var extension = materialDef.extensions[this.name];
  32715. if (extension.clearcoatFactor !== undefined) {
  32716. materialParams.clearcoat = extension.clearcoatFactor;
  32717. }
  32718. if (extension.clearcoatTexture !== undefined) {
  32719. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  32720. }
  32721. if (extension.clearcoatRoughnessFactor !== undefined) {
  32722. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  32723. }
  32724. if (extension.clearcoatRoughnessTexture !== undefined) {
  32725. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  32726. }
  32727. if (extension.clearcoatNormalTexture !== undefined) {
  32728. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  32729. if (extension.clearcoatNormalTexture.scale !== undefined) {
  32730. var scale = extension.clearcoatNormalTexture.scale;
  32731. materialParams.clearcoatNormalScale = new _threeModule.Vector2(scale, scale);
  32732. }
  32733. }
  32734. return Promise.all(pending);
  32735. };
  32736. /**
  32737. * Transmission Materials Extension
  32738. *
  32739. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  32740. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  32741. */
  32742. function GLTFMaterialsTransmissionExtension(parser) {
  32743. this.parser = parser;
  32744. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  32745. }
  32746. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function (materialIndex) {
  32747. var parser = this.parser;
  32748. var materialDef = parser.json.materials[materialIndex];
  32749. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  32750. return _threeModule.MeshPhysicalMaterial;
  32751. };
  32752. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function (materialIndex, materialParams) {
  32753. var parser = this.parser;
  32754. var materialDef = parser.json.materials[materialIndex];
  32755. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  32756. return Promise.resolve();
  32757. }
  32758. var pending = [];
  32759. var extension = materialDef.extensions[this.name];
  32760. if (extension.transmissionFactor !== undefined) {
  32761. materialParams.transmission = extension.transmissionFactor;
  32762. }
  32763. if (extension.transmissionTexture !== undefined) {
  32764. pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture));
  32765. }
  32766. return Promise.all(pending);
  32767. };
  32768. /**
  32769. * BasisU Texture Extension
  32770. *
  32771. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  32772. */
  32773. function GLTFTextureBasisUExtension(parser) {
  32774. this.parser = parser;
  32775. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  32776. }
  32777. GLTFTextureBasisUExtension.prototype.loadTexture = function (textureIndex) {
  32778. var parser = this.parser;
  32779. var json = parser.json;
  32780. var textureDef = json.textures[textureIndex];
  32781. if (!textureDef.extensions || !textureDef.extensions[this.name]) {
  32782. return null;
  32783. }
  32784. var extension = textureDef.extensions[this.name];
  32785. var source = json.images[extension.source];
  32786. var loader = parser.options.ktx2Loader;
  32787. if (!loader) {
  32788. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  32789. throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures');
  32790. } else {
  32791. // Assumes that the extension is optional and that a fallback texture is present
  32792. return null;
  32793. }
  32794. }
  32795. return parser.loadTextureImage(textureIndex, source, loader);
  32796. };
  32797. /**
  32798. * WebP Texture Extension
  32799. *
  32800. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  32801. */
  32802. function GLTFTextureWebPExtension(parser) {
  32803. this.parser = parser;
  32804. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  32805. this.isSupported = null;
  32806. }
  32807. GLTFTextureWebPExtension.prototype.loadTexture = function (textureIndex) {
  32808. var name = this.name;
  32809. var parser = this.parser;
  32810. var json = parser.json;
  32811. var textureDef = json.textures[textureIndex];
  32812. if (!textureDef.extensions || !textureDef.extensions[name]) {
  32813. return null;
  32814. }
  32815. var extension = textureDef.extensions[name];
  32816. var source = json.images[extension.source];
  32817. var loader = source.uri ? parser.options.manager.getHandler(source.uri) : parser.textureLoader;
  32818. return this.detectSupport().then(function (isSupported) {
  32819. if (isSupported) return parser.loadTextureImage(textureIndex, source, loader);
  32820. if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
  32821. throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.');
  32822. } // Fall back to PNG or JPEG.
  32823. return parser.loadTexture(textureIndex);
  32824. });
  32825. };
  32826. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  32827. if (!this.isSupported) {
  32828. this.isSupported = new Promise(function (resolve) {
  32829. var image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all
  32830. // WebP images, unfortunately.
  32831. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  32832. image.onload = image.onerror = function () {
  32833. resolve(image.height === 1);
  32834. };
  32835. });
  32836. }
  32837. return this.isSupported;
  32838. };
  32839. /**
  32840. * meshopt BufferView Compression Extension
  32841. *
  32842. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  32843. */
  32844. function GLTFMeshoptCompression(parser) {
  32845. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  32846. this.parser = parser;
  32847. }
  32848. GLTFMeshoptCompression.prototype.loadBufferView = function (index) {
  32849. var json = this.parser.json;
  32850. var bufferView = json.bufferViews[index];
  32851. if (bufferView.extensions && bufferView.extensions[this.name]) {
  32852. var extensionDef = bufferView.extensions[this.name];
  32853. var buffer = this.parser.getDependency('buffer', extensionDef.buffer);
  32854. var decoder = this.parser.options.meshoptDecoder;
  32855. if (!decoder || !decoder.supported) {
  32856. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  32857. throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files');
  32858. } else {
  32859. // Assumes that the extension is optional and that fallback buffer data is present
  32860. return null;
  32861. }
  32862. }
  32863. return Promise.all([buffer, decoder.ready]).then(function (res) {
  32864. var byteOffset = extensionDef.byteOffset || 0;
  32865. var byteLength = extensionDef.byteLength || 0;
  32866. var count = extensionDef.count;
  32867. var stride = extensionDef.byteStride;
  32868. var result = new ArrayBuffer(count * stride);
  32869. var source = new Uint8Array(res[0], byteOffset, byteLength);
  32870. decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter);
  32871. return result;
  32872. });
  32873. } else {
  32874. return null;
  32875. }
  32876. };
  32877. /* BINARY EXTENSION */
  32878. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  32879. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  32880. var BINARY_EXTENSION_CHUNK_TYPES = {
  32881. JSON: 0x4E4F534A,
  32882. BIN: 0x004E4942
  32883. };
  32884. function GLTFBinaryExtension(data) {
  32885. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  32886. this.content = null;
  32887. this.body = null;
  32888. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  32889. this.header = {
  32890. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  32891. version: headerView.getUint32(4, true),
  32892. length: headerView.getUint32(8, true)
  32893. };
  32894. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  32895. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  32896. } else if (this.header.version < 2.0) {
  32897. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  32898. }
  32899. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  32900. var chunkIndex = 0;
  32901. while (chunkIndex < chunkView.byteLength) {
  32902. var chunkLength = chunkView.getUint32(chunkIndex, true);
  32903. chunkIndex += 4;
  32904. var chunkType = chunkView.getUint32(chunkIndex, true);
  32905. chunkIndex += 4;
  32906. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  32907. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  32908. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  32909. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  32910. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  32911. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  32912. } // Clients must ignore chunks with unknown types.
  32913. chunkIndex += chunkLength;
  32914. }
  32915. if (this.content === null) {
  32916. throw new Error('THREE.GLTFLoader: JSON content not found.');
  32917. }
  32918. }
  32919. /**
  32920. * DRACO Mesh Compression Extension
  32921. *
  32922. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  32923. */
  32924. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  32925. if (!dracoLoader) {
  32926. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  32927. }
  32928. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  32929. this.json = json;
  32930. this.dracoLoader = dracoLoader;
  32931. this.dracoLoader.preload();
  32932. }
  32933. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  32934. var json = this.json;
  32935. var dracoLoader = this.dracoLoader;
  32936. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  32937. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  32938. var threeAttributeMap = {};
  32939. var attributeNormalizedMap = {};
  32940. var attributeTypeMap = {};
  32941. for (var attributeName in gltfAttributeMap) {
  32942. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  32943. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  32944. }
  32945. for (attributeName in primitive.attributes) {
  32946. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  32947. if (gltfAttributeMap[attributeName] !== undefined) {
  32948. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  32949. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  32950. attributeTypeMap[threeAttributeName] = componentType;
  32951. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  32952. }
  32953. }
  32954. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  32955. return new Promise(function (resolve) {
  32956. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  32957. for (var attributeName in geometry.attributes) {
  32958. var attribute = geometry.attributes[attributeName];
  32959. var normalized = attributeNormalizedMap[attributeName];
  32960. if (normalized !== undefined) attribute.normalized = normalized;
  32961. }
  32962. resolve(geometry);
  32963. }, threeAttributeMap, attributeTypeMap);
  32964. });
  32965. });
  32966. };
  32967. /**
  32968. * Texture Transform Extension
  32969. *
  32970. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  32971. */
  32972. function GLTFTextureTransformExtension() {
  32973. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  32974. }
  32975. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  32976. texture = texture.clone();
  32977. if (transform.offset !== undefined) {
  32978. texture.offset.fromArray(transform.offset);
  32979. }
  32980. if (transform.rotation !== undefined) {
  32981. texture.rotation = transform.rotation;
  32982. }
  32983. if (transform.scale !== undefined) {
  32984. texture.repeat.fromArray(transform.scale);
  32985. }
  32986. if (transform.texCoord !== undefined) {
  32987. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  32988. }
  32989. texture.needsUpdate = true;
  32990. return texture;
  32991. };
  32992. /**
  32993. * Specular-Glossiness Extension
  32994. *
  32995. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  32996. */
  32997. /**
  32998. * A sub class of StandardMaterial with some of the functionality
  32999. * changed via the `onBeforeCompile` callback
  33000. * @pailhead
  33001. */
  33002. function GLTFMeshStandardSGMaterial(params) {
  33003. _threeModule.MeshStandardMaterial.call(this);
  33004. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  33005. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  33006. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  33007. var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n');
  33008. var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n');
  33009. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.specularRoughness += geometryRoughness;', 'material.specularRoughness = min( material.specularRoughness, 1.0 );', 'material.specularColor = specularFactor;'].join('\n');
  33010. var uniforms = {
  33011. specular: {
  33012. value: new _threeModule.Color().setHex(0xffffff)
  33013. },
  33014. glossiness: {
  33015. value: 1
  33016. },
  33017. specularMap: {
  33018. value: null
  33019. },
  33020. glossinessMap: {
  33021. value: null
  33022. }
  33023. };
  33024. this._extraUniforms = uniforms;
  33025. this.onBeforeCompile = function (shader) {
  33026. for (var uniformName in uniforms) {
  33027. shader.uniforms[uniformName] = uniforms[uniformName];
  33028. }
  33029. shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  33030. };
  33031. Object.defineProperties(this, {
  33032. specular: {
  33033. get: function () {
  33034. return uniforms.specular.value;
  33035. },
  33036. set: function (v) {
  33037. uniforms.specular.value = v;
  33038. }
  33039. },
  33040. specularMap: {
  33041. get: function () {
  33042. return uniforms.specularMap.value;
  33043. },
  33044. set: function (v) {
  33045. uniforms.specularMap.value = v;
  33046. if (v) {
  33047. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  33048. } else {
  33049. delete this.defines.USE_SPECULARMAP;
  33050. }
  33051. }
  33052. },
  33053. glossiness: {
  33054. get: function () {
  33055. return uniforms.glossiness.value;
  33056. },
  33057. set: function (v) {
  33058. uniforms.glossiness.value = v;
  33059. }
  33060. },
  33061. glossinessMap: {
  33062. get: function () {
  33063. return uniforms.glossinessMap.value;
  33064. },
  33065. set: function (v) {
  33066. uniforms.glossinessMap.value = v;
  33067. if (v) {
  33068. this.defines.USE_GLOSSINESSMAP = '';
  33069. this.defines.USE_UV = '';
  33070. } else {
  33071. delete this.defines.USE_GLOSSINESSMAP;
  33072. delete this.defines.USE_UV;
  33073. }
  33074. }
  33075. }
  33076. });
  33077. delete this.metalness;
  33078. delete this.roughness;
  33079. delete this.metalnessMap;
  33080. delete this.roughnessMap;
  33081. this.setValues(params);
  33082. }
  33083. GLTFMeshStandardSGMaterial.prototype = Object.create(_threeModule.MeshStandardMaterial.prototype);
  33084. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  33085. GLTFMeshStandardSGMaterial.prototype.copy = function (source) {
  33086. _threeModule.MeshStandardMaterial.prototype.copy.call(this, source);
  33087. this.specularMap = source.specularMap;
  33088. this.specular.copy(source.specular);
  33089. this.glossinessMap = source.glossinessMap;
  33090. this.glossiness = source.glossiness;
  33091. delete this.metalness;
  33092. delete this.roughness;
  33093. delete this.metalnessMap;
  33094. delete this.roughnessMap;
  33095. return this;
  33096. };
  33097. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  33098. return {
  33099. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  33100. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  33101. getMaterialType: function () {
  33102. return GLTFMeshStandardSGMaterial;
  33103. },
  33104. extendParams: function (materialParams, materialDef, parser) {
  33105. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  33106. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  33107. materialParams.opacity = 1.0;
  33108. var pending = [];
  33109. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  33110. var array = pbrSpecularGlossiness.diffuseFactor;
  33111. materialParams.color.fromArray(array);
  33112. materialParams.opacity = array[3];
  33113. }
  33114. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  33115. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  33116. }
  33117. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  33118. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  33119. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  33120. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  33121. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  33122. }
  33123. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  33124. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  33125. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  33126. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  33127. }
  33128. return Promise.all(pending);
  33129. },
  33130. createMaterial: function (materialParams) {
  33131. var material = new GLTFMeshStandardSGMaterial(materialParams);
  33132. material.fog = true;
  33133. material.color = materialParams.color;
  33134. material.map = materialParams.map === undefined ? null : materialParams.map;
  33135. material.lightMap = null;
  33136. material.lightMapIntensity = 1.0;
  33137. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  33138. material.aoMapIntensity = 1.0;
  33139. material.emissive = materialParams.emissive;
  33140. material.emissiveIntensity = 1.0;
  33141. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  33142. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  33143. material.bumpScale = 1;
  33144. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  33145. material.normalMapType = _threeModule.TangentSpaceNormalMap;
  33146. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  33147. material.displacementMap = null;
  33148. material.displacementScale = 1;
  33149. material.displacementBias = 0;
  33150. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  33151. material.specular = materialParams.specular;
  33152. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  33153. material.glossiness = materialParams.glossiness;
  33154. material.alphaMap = null;
  33155. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  33156. material.envMapIntensity = 1.0;
  33157. material.refractionRatio = 0.98;
  33158. return material;
  33159. }
  33160. };
  33161. }
  33162. /**
  33163. * Mesh Quantization Extension
  33164. *
  33165. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  33166. */
  33167. function GLTFMeshQuantizationExtension() {
  33168. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  33169. }
  33170. /*********************************/
  33171. /********** INTERPOLATION ********/
  33172. /*********************************/
  33173. // Spline Interpolation
  33174. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  33175. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  33176. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  33177. }
  33178. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  33179. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  33180. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  33181. // Copies a sample value to the result buffer. See description of glTF
  33182. // CUBICSPLINE values layout in interpolate_() function below.
  33183. var result = this.resultBuffer,
  33184. values = this.sampleValues,
  33185. valueSize = this.valueSize,
  33186. offset = index * valueSize * 3 + valueSize;
  33187. for (var i = 0; i !== valueSize; i++) {
  33188. result[i] = values[offset + i];
  33189. }
  33190. return result;
  33191. };
  33192. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  33193. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  33194. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  33195. var result = this.resultBuffer;
  33196. var values = this.sampleValues;
  33197. var stride = this.valueSize;
  33198. var stride2 = stride * 2;
  33199. var stride3 = stride * 3;
  33200. var td = t1 - t0;
  33201. var p = (t - t0) / td;
  33202. var pp = p * p;
  33203. var ppp = pp * p;
  33204. var offset1 = i1 * stride3;
  33205. var offset0 = offset1 - stride3;
  33206. var s2 = -2 * ppp + 3 * pp;
  33207. var s3 = ppp - pp;
  33208. var s0 = 1 - s2;
  33209. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  33210. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  33211. for (var i = 0; i !== stride; i++) {
  33212. var p0 = values[offset0 + i + stride]; // splineVertex_k
  33213. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  33214. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  33215. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  33216. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  33217. }
  33218. return result;
  33219. };
  33220. /*********************************/
  33221. /********** INTERNALS ************/
  33222. /*********************************/
  33223. /* CONSTANTS */
  33224. var WEBGL_CONSTANTS = {
  33225. FLOAT: 5126,
  33226. //FLOAT_MAT2: 35674,
  33227. FLOAT_MAT3: 35675,
  33228. FLOAT_MAT4: 35676,
  33229. FLOAT_VEC2: 35664,
  33230. FLOAT_VEC3: 35665,
  33231. FLOAT_VEC4: 35666,
  33232. LINEAR: 9729,
  33233. REPEAT: 10497,
  33234. SAMPLER_2D: 35678,
  33235. POINTS: 0,
  33236. LINES: 1,
  33237. LINE_LOOP: 2,
  33238. LINE_STRIP: 3,
  33239. TRIANGLES: 4,
  33240. TRIANGLE_STRIP: 5,
  33241. TRIANGLE_FAN: 6,
  33242. UNSIGNED_BYTE: 5121,
  33243. UNSIGNED_SHORT: 5123
  33244. };
  33245. var WEBGL_COMPONENT_TYPES = {
  33246. 5120: Int8Array,
  33247. 5121: Uint8Array,
  33248. 5122: Int16Array,
  33249. 5123: Uint16Array,
  33250. 5125: Uint32Array,
  33251. 5126: Float32Array
  33252. };
  33253. var WEBGL_FILTERS = {
  33254. 9728: _threeModule.NearestFilter,
  33255. 9729: _threeModule.LinearFilter,
  33256. 9984: _threeModule.NearestMipmapNearestFilter,
  33257. 9985: _threeModule.LinearMipmapNearestFilter,
  33258. 9986: _threeModule.NearestMipmapLinearFilter,
  33259. 9987: _threeModule.LinearMipmapLinearFilter
  33260. };
  33261. var WEBGL_WRAPPINGS = {
  33262. 33071: _threeModule.ClampToEdgeWrapping,
  33263. 33648: _threeModule.MirroredRepeatWrapping,
  33264. 10497: _threeModule.RepeatWrapping
  33265. };
  33266. var WEBGL_TYPE_SIZES = {
  33267. 'SCALAR': 1,
  33268. 'VEC2': 2,
  33269. 'VEC3': 3,
  33270. 'VEC4': 4,
  33271. 'MAT2': 4,
  33272. 'MAT3': 9,
  33273. 'MAT4': 16
  33274. };
  33275. var ATTRIBUTES = {
  33276. POSITION: 'position',
  33277. NORMAL: 'normal',
  33278. TANGENT: 'tangent',
  33279. TEXCOORD_0: 'uv',
  33280. TEXCOORD_1: 'uv2',
  33281. COLOR_0: 'color',
  33282. WEIGHTS_0: 'skinWeight',
  33283. JOINTS_0: 'skinIndex'
  33284. };
  33285. var PATH_PROPERTIES = {
  33286. scale: 'scale',
  33287. translation: 'position',
  33288. rotation: 'quaternion',
  33289. weights: 'morphTargetInfluences'
  33290. };
  33291. var INTERPOLATION = {
  33292. CUBICSPLINE: undefined,
  33293. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  33294. // keyframe track will be initialized with a default interpolation type, then modified.
  33295. LINEAR: _threeModule.InterpolateLinear,
  33296. STEP: _threeModule.InterpolateDiscrete
  33297. };
  33298. var ALPHA_MODES = {
  33299. OPAQUE: 'OPAQUE',
  33300. MASK: 'MASK',
  33301. BLEND: 'BLEND'
  33302. };
  33303. /* UTILITY FUNCTIONS */
  33304. function resolveURL(url, path) {
  33305. // Invalid URL
  33306. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  33307. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  33308. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  33309. } // Absolute URL http://,https://,//
  33310. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  33311. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  33312. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  33313. return path + url;
  33314. }
  33315. /**
  33316. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  33317. */
  33318. function createDefaultMaterial(cache) {
  33319. if (cache['DefaultMaterial'] === undefined) {
  33320. cache['DefaultMaterial'] = new _threeModule.MeshStandardMaterial({
  33321. color: 0xFFFFFF,
  33322. emissive: 0x000000,
  33323. metalness: 1,
  33324. roughness: 1,
  33325. transparent: false,
  33326. depthTest: true,
  33327. side: _threeModule.FrontSide
  33328. });
  33329. }
  33330. return cache['DefaultMaterial'];
  33331. }
  33332. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  33333. // Add unknown glTF extensions to an object's userData.
  33334. for (var name in objectDef.extensions) {
  33335. if (knownExtensions[name] === undefined) {
  33336. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  33337. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  33338. }
  33339. }
  33340. }
  33341. /**
  33342. * @param {Object3D|Material|BufferGeometry} object
  33343. * @param {GLTF.definition} gltfDef
  33344. */
  33345. function assignExtrasToUserData(object, gltfDef) {
  33346. if (gltfDef.extras !== undefined) {
  33347. if (typeof gltfDef.extras === 'object') {
  33348. Object.assign(object.userData, gltfDef.extras);
  33349. } else {
  33350. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  33351. }
  33352. }
  33353. }
  33354. /**
  33355. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  33356. *
  33357. * @param {BufferGeometry} geometry
  33358. * @param {Array<GLTF.Target>} targets
  33359. * @param {GLTFParser} parser
  33360. * @return {Promise<BufferGeometry>}
  33361. */
  33362. function addMorphTargets(geometry, targets, parser) {
  33363. var hasMorphPosition = false;
  33364. var hasMorphNormal = false;
  33365. for (var i = 0, il = targets.length; i < il; i++) {
  33366. var target = targets[i];
  33367. if (target.POSITION !== undefined) hasMorphPosition = true;
  33368. if (target.NORMAL !== undefined) hasMorphNormal = true;
  33369. if (hasMorphPosition && hasMorphNormal) break;
  33370. }
  33371. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  33372. var pendingPositionAccessors = [];
  33373. var pendingNormalAccessors = [];
  33374. for (var i = 0, il = targets.length; i < il; i++) {
  33375. var target = targets[i];
  33376. if (hasMorphPosition) {
  33377. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  33378. pendingPositionAccessors.push(pendingAccessor);
  33379. }
  33380. if (hasMorphNormal) {
  33381. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  33382. pendingNormalAccessors.push(pendingAccessor);
  33383. }
  33384. }
  33385. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  33386. var morphPositions = accessors[0];
  33387. var morphNormals = accessors[1];
  33388. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  33389. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  33390. geometry.morphTargetsRelative = true;
  33391. return geometry;
  33392. });
  33393. }
  33394. /**
  33395. * @param {Mesh} mesh
  33396. * @param {GLTF.Mesh} meshDef
  33397. */
  33398. function updateMorphTargets(mesh, meshDef) {
  33399. mesh.updateMorphTargets();
  33400. if (meshDef.weights !== undefined) {
  33401. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  33402. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  33403. }
  33404. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  33405. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  33406. var targetNames = meshDef.extras.targetNames;
  33407. if (mesh.morphTargetInfluences.length === targetNames.length) {
  33408. mesh.morphTargetDictionary = {};
  33409. for (var i = 0, il = targetNames.length; i < il; i++) {
  33410. mesh.morphTargetDictionary[targetNames[i]] = i;
  33411. }
  33412. } else {
  33413. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  33414. }
  33415. }
  33416. }
  33417. function createPrimitiveKey(primitiveDef) {
  33418. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  33419. var geometryKey;
  33420. if (dracoExtension) {
  33421. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  33422. } else {
  33423. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  33424. }
  33425. return geometryKey;
  33426. }
  33427. function createAttributesKey(attributes) {
  33428. var attributesKey = '';
  33429. var keys = Object.keys(attributes).sort();
  33430. for (var i = 0, il = keys.length; i < il; i++) {
  33431. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  33432. }
  33433. return attributesKey;
  33434. }
  33435. /* GLTF PARSER */
  33436. function GLTFParser(json, options) {
  33437. this.json = json || {};
  33438. this.extensions = {};
  33439. this.plugins = {};
  33440. this.options = options || {}; // loader object cache
  33441. this.cache = new GLTFRegistry(); // associations between Three.js objects and glTF elements
  33442. this.associations = new Map(); // BufferGeometry caching
  33443. this.primitiveCache = {}; // Object3D instance caches
  33444. this.meshCache = {
  33445. refs: {},
  33446. uses: {}
  33447. };
  33448. this.cameraCache = {
  33449. refs: {},
  33450. uses: {}
  33451. };
  33452. this.lightCache = {
  33453. refs: {},
  33454. uses: {}
  33455. }; // Track node names, to ensure no duplicates
  33456. this.nodeNamesUsed = {}; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  33457. // expensive work of uploading a texture to the GPU off the main thread.
  33458. if (typeof createImageBitmap !== 'undefined' && /Firefox/.test(navigator.userAgent) === false) {
  33459. this.textureLoader = new _threeModule.ImageBitmapLoader(this.options.manager);
  33460. } else {
  33461. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  33462. }
  33463. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  33464. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  33465. this.fileLoader.setResponseType('arraybuffer');
  33466. if (this.options.crossOrigin === 'use-credentials') {
  33467. this.fileLoader.setWithCredentials(true);
  33468. }
  33469. }
  33470. GLTFParser.prototype.setExtensions = function (extensions) {
  33471. this.extensions = extensions;
  33472. };
  33473. GLTFParser.prototype.setPlugins = function (plugins) {
  33474. this.plugins = plugins;
  33475. };
  33476. GLTFParser.prototype.parse = function (onLoad, onError) {
  33477. var parser = this;
  33478. var json = this.json;
  33479. var extensions = this.extensions; // Clear the loader cache
  33480. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  33481. this._invokeAll(function (ext) {
  33482. return ext._markDefs && ext._markDefs();
  33483. });
  33484. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  33485. var result = {
  33486. scene: dependencies[0][json.scene || 0],
  33487. scenes: dependencies[0],
  33488. animations: dependencies[1],
  33489. cameras: dependencies[2],
  33490. asset: json.asset,
  33491. parser: parser,
  33492. userData: {}
  33493. };
  33494. addUnknownExtensionsToUserData(extensions, result, json);
  33495. assignExtrasToUserData(result, json);
  33496. onLoad(result);
  33497. }).catch(onError);
  33498. };
  33499. /**
  33500. * Marks the special nodes/meshes in json for efficient parse.
  33501. */
  33502. GLTFParser.prototype._markDefs = function () {
  33503. var nodeDefs = this.json.nodes || [];
  33504. var skinDefs = this.json.skins || [];
  33505. var meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an
  33506. // Object3D. Use the skins' joint references to mark bones.
  33507. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  33508. var joints = skinDefs[skinIndex].joints;
  33509. for (var i = 0, il = joints.length; i < il; i++) {
  33510. nodeDefs[joints[i]].isBone = true;
  33511. }
  33512. } // Iterate over all nodes, marking references to shared resources,
  33513. // as well as skeleton joints.
  33514. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  33515. var nodeDef = nodeDefs[nodeIndex];
  33516. if (nodeDef.mesh !== undefined) {
  33517. this._addNodeRef(this.meshCache, nodeDef.mesh); // Nothing in the mesh definition indicates whether it is
  33518. // a SkinnedMesh or Mesh. Use the node's mesh reference
  33519. // to mark SkinnedMesh if node has skin.
  33520. if (nodeDef.skin !== undefined) {
  33521. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  33522. }
  33523. }
  33524. if (nodeDef.camera !== undefined) {
  33525. this._addNodeRef(this.cameraCache, nodeDef.camera);
  33526. }
  33527. }
  33528. };
  33529. /**
  33530. * Counts references to shared node / Object3D resources. These resources
  33531. * can be reused, or "instantiated", at multiple nodes in the scene
  33532. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  33533. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  33534. * Textures) can be reused directly and are not marked here.
  33535. *
  33536. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  33537. */
  33538. GLTFParser.prototype._addNodeRef = function (cache, index) {
  33539. if (index === undefined) return;
  33540. if (cache.refs[index] === undefined) {
  33541. cache.refs[index] = cache.uses[index] = 0;
  33542. }
  33543. cache.refs[index]++;
  33544. };
  33545. /** Returns a reference to a shared resource, cloning it if necessary. */
  33546. GLTFParser.prototype._getNodeRef = function (cache, index, object) {
  33547. if (cache.refs[index] <= 1) return object;
  33548. var ref = object.clone();
  33549. ref.name += '_instance_' + cache.uses[index]++;
  33550. return ref;
  33551. };
  33552. GLTFParser.prototype._invokeOne = function (func) {
  33553. var extensions = Object.values(this.plugins);
  33554. extensions.push(this);
  33555. for (var i = 0; i < extensions.length; i++) {
  33556. var result = func(extensions[i]);
  33557. if (result) return result;
  33558. }
  33559. };
  33560. GLTFParser.prototype._invokeAll = function (func) {
  33561. var extensions = Object.values(this.plugins);
  33562. extensions.unshift(this);
  33563. var pending = [];
  33564. for (var i = 0; i < extensions.length; i++) {
  33565. var result = func(extensions[i]);
  33566. if (result) pending.push(result);
  33567. }
  33568. return pending;
  33569. };
  33570. /**
  33571. * Requests the specified dependency asynchronously, with caching.
  33572. * @param {string} type
  33573. * @param {number} index
  33574. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  33575. */
  33576. GLTFParser.prototype.getDependency = function (type, index) {
  33577. var cacheKey = type + ':' + index;
  33578. var dependency = this.cache.get(cacheKey);
  33579. if (!dependency) {
  33580. switch (type) {
  33581. case 'scene':
  33582. dependency = this.loadScene(index);
  33583. break;
  33584. case 'node':
  33585. dependency = this.loadNode(index);
  33586. break;
  33587. case 'mesh':
  33588. dependency = this._invokeOne(function (ext) {
  33589. return ext.loadMesh && ext.loadMesh(index);
  33590. });
  33591. break;
  33592. case 'accessor':
  33593. dependency = this.loadAccessor(index);
  33594. break;
  33595. case 'bufferView':
  33596. dependency = this._invokeOne(function (ext) {
  33597. return ext.loadBufferView && ext.loadBufferView(index);
  33598. });
  33599. break;
  33600. case 'buffer':
  33601. dependency = this.loadBuffer(index);
  33602. break;
  33603. case 'material':
  33604. dependency = this._invokeOne(function (ext) {
  33605. return ext.loadMaterial && ext.loadMaterial(index);
  33606. });
  33607. break;
  33608. case 'texture':
  33609. dependency = this._invokeOne(function (ext) {
  33610. return ext.loadTexture && ext.loadTexture(index);
  33611. });
  33612. break;
  33613. case 'skin':
  33614. dependency = this.loadSkin(index);
  33615. break;
  33616. case 'animation':
  33617. dependency = this.loadAnimation(index);
  33618. break;
  33619. case 'camera':
  33620. dependency = this.loadCamera(index);
  33621. break;
  33622. default:
  33623. throw new Error('Unknown type: ' + type);
  33624. }
  33625. this.cache.add(cacheKey, dependency);
  33626. }
  33627. return dependency;
  33628. };
  33629. /**
  33630. * Requests all dependencies of the specified type asynchronously, with caching.
  33631. * @param {string} type
  33632. * @return {Promise<Array<Object>>}
  33633. */
  33634. GLTFParser.prototype.getDependencies = function (type) {
  33635. var dependencies = this.cache.get(type);
  33636. if (!dependencies) {
  33637. var parser = this;
  33638. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  33639. dependencies = Promise.all(defs.map(function (def, index) {
  33640. return parser.getDependency(type, index);
  33641. }));
  33642. this.cache.add(type, dependencies);
  33643. }
  33644. return dependencies;
  33645. };
  33646. /**
  33647. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  33648. * @param {number} bufferIndex
  33649. * @return {Promise<ArrayBuffer>}
  33650. */
  33651. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  33652. var bufferDef = this.json.buffers[bufferIndex];
  33653. var loader = this.fileLoader;
  33654. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  33655. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  33656. } // If present, GLB container is required to be the first buffer.
  33657. if (bufferDef.uri === undefined && bufferIndex === 0) {
  33658. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  33659. }
  33660. var options = this.options;
  33661. return new Promise(function (resolve, reject) {
  33662. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  33663. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  33664. });
  33665. });
  33666. };
  33667. /**
  33668. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  33669. * @param {number} bufferViewIndex
  33670. * @return {Promise<ArrayBuffer>}
  33671. */
  33672. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  33673. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  33674. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  33675. var byteLength = bufferViewDef.byteLength || 0;
  33676. var byteOffset = bufferViewDef.byteOffset || 0;
  33677. return buffer.slice(byteOffset, byteOffset + byteLength);
  33678. });
  33679. };
  33680. /**
  33681. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  33682. * @param {number} accessorIndex
  33683. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  33684. */
  33685. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  33686. var parser = this;
  33687. var json = this.json;
  33688. var accessorDef = this.json.accessors[accessorIndex];
  33689. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  33690. // Ignore empty accessors, which may be used to declare runtime
  33691. // information about attributes coming from another source (e.g. Draco
  33692. // compression extension).
  33693. return Promise.resolve(null);
  33694. }
  33695. var pendingBufferViews = [];
  33696. if (accessorDef.bufferView !== undefined) {
  33697. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  33698. } else {
  33699. pendingBufferViews.push(null);
  33700. }
  33701. if (accessorDef.sparse !== undefined) {
  33702. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  33703. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  33704. }
  33705. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  33706. var bufferView = bufferViews[0];
  33707. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  33708. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  33709. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  33710. var itemBytes = elementBytes * itemSize;
  33711. var byteOffset = accessorDef.byteOffset || 0;
  33712. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  33713. var normalized = accessorDef.normalized === true;
  33714. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  33715. if (byteStride && byteStride !== itemBytes) {
  33716. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  33717. // This makes sure that IBA.count reflects accessor.count properly
  33718. var ibSlice = Math.floor(byteOffset / byteStride);
  33719. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  33720. var ib = parser.cache.get(ibCacheKey);
  33721. if (!ib) {
  33722. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  33723. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  33724. parser.cache.add(ibCacheKey, ib);
  33725. }
  33726. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  33727. } else {
  33728. if (bufferView === null) {
  33729. array = new TypedArray(accessorDef.count * itemSize);
  33730. } else {
  33731. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  33732. }
  33733. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  33734. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  33735. if (accessorDef.sparse !== undefined) {
  33736. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  33737. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  33738. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  33739. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  33740. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  33741. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  33742. if (bufferView !== null) {
  33743. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  33744. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  33745. }
  33746. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  33747. var index = sparseIndices[i];
  33748. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  33749. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  33750. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  33751. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  33752. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  33753. }
  33754. }
  33755. return bufferAttribute;
  33756. });
  33757. };
  33758. /**
  33759. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  33760. * @param {number} textureIndex
  33761. * @return {Promise<THREE.Texture>}
  33762. */
  33763. GLTFParser.prototype.loadTexture = function (textureIndex) {
  33764. var parser = this;
  33765. var json = this.json;
  33766. var options = this.options;
  33767. var textureDef = json.textures[textureIndex];
  33768. var textureExtensions = textureDef.extensions || {};
  33769. var source;
  33770. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  33771. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  33772. } else {
  33773. source = json.images[textureDef.source];
  33774. }
  33775. var loader;
  33776. if (source.uri) {
  33777. loader = options.manager.getHandler(source.uri);
  33778. }
  33779. if (!loader) {
  33780. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : this.textureLoader;
  33781. }
  33782. return this.loadTextureImage(textureIndex, source, loader);
  33783. };
  33784. GLTFParser.prototype.loadTextureImage = function (textureIndex, source, loader) {
  33785. var parser = this;
  33786. var json = this.json;
  33787. var options = this.options;
  33788. var textureDef = json.textures[textureIndex];
  33789. var URL = self.URL || self.webkitURL;
  33790. var sourceURI = source.uri;
  33791. var isObjectURL = false;
  33792. var hasAlpha = true;
  33793. if (source.mimeType === 'image/jpeg') hasAlpha = false;
  33794. if (source.bufferView !== undefined) {
  33795. // Load binary image data from bufferView, if provided.
  33796. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  33797. if (source.mimeType === 'image/png') {
  33798. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  33799. // alpha channel. This check is conservative — the image could have an alpha
  33800. // channel with all values == 1, and the indexed type (colorType == 3) only
  33801. // sometimes contains alpha.
  33802. //
  33803. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  33804. var colorType = new DataView(bufferView, 25, 1).getUint8(0, false);
  33805. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  33806. }
  33807. isObjectURL = true;
  33808. var blob = new Blob([bufferView], {
  33809. type: source.mimeType
  33810. });
  33811. sourceURI = URL.createObjectURL(blob);
  33812. return sourceURI;
  33813. });
  33814. }
  33815. return Promise.resolve(sourceURI).then(function (sourceURI) {
  33816. return new Promise(function (resolve, reject) {
  33817. var onLoad = resolve;
  33818. if (loader.isImageBitmapLoader === true) {
  33819. onLoad = function (imageBitmap) {
  33820. resolve(new _threeModule.CanvasTexture(imageBitmap));
  33821. };
  33822. }
  33823. loader.load(resolveURL(sourceURI, options.path), onLoad, undefined, reject);
  33824. });
  33825. }).then(function (texture) {
  33826. // Clean up resources and configure Texture.
  33827. if (isObjectURL === true) {
  33828. URL.revokeObjectURL(sourceURI);
  33829. }
  33830. texture.flipY = false;
  33831. if (textureDef.name) texture.name = textureDef.name; // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  33832. if (!hasAlpha) texture.format = _threeModule.RGBFormat;
  33833. var samplers = json.samplers || {};
  33834. var sampler = samplers[textureDef.sampler] || {};
  33835. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  33836. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  33837. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  33838. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  33839. parser.associations.set(texture, {
  33840. type: 'textures',
  33841. index: textureIndex
  33842. });
  33843. return texture;
  33844. });
  33845. };
  33846. /**
  33847. * Asynchronously assigns a texture to the given material parameters.
  33848. * @param {Object} materialParams
  33849. * @param {string} mapName
  33850. * @param {Object} mapDef
  33851. * @return {Promise}
  33852. */
  33853. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  33854. var parser = this;
  33855. return this.getDependency('texture', mapDef.index).then(function (texture) {
  33856. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  33857. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  33858. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  33859. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  33860. }
  33861. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  33862. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  33863. if (transform) {
  33864. var gltfReference = parser.associations.get(texture);
  33865. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  33866. parser.associations.set(texture, gltfReference);
  33867. }
  33868. }
  33869. materialParams[mapName] = texture;
  33870. });
  33871. };
  33872. /**
  33873. * Assigns final material to a Mesh, Line, or Points instance. The instance
  33874. * already has a material (generated from the glTF material options alone)
  33875. * but reuse of the same glTF material may require multiple threejs materials
  33876. * to accomodate different primitive types, defines, etc. New materials will
  33877. * be created if necessary, and reused from a cache.
  33878. * @param {Object3D} mesh Mesh, Line, or Points instance.
  33879. */
  33880. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  33881. var geometry = mesh.geometry;
  33882. var material = mesh.material;
  33883. var useVertexTangents = geometry.attributes.tangent !== undefined;
  33884. var useVertexColors = geometry.attributes.color !== undefined;
  33885. var useFlatShading = geometry.attributes.normal === undefined;
  33886. var useSkinning = mesh.isSkinnedMesh === true;
  33887. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  33888. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  33889. if (mesh.isPoints) {
  33890. var cacheKey = 'PointsMaterial:' + material.uuid;
  33891. var pointsMaterial = this.cache.get(cacheKey);
  33892. if (!pointsMaterial) {
  33893. pointsMaterial = new _threeModule.PointsMaterial();
  33894. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  33895. pointsMaterial.color.copy(material.color);
  33896. pointsMaterial.map = material.map;
  33897. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  33898. this.cache.add(cacheKey, pointsMaterial);
  33899. }
  33900. material = pointsMaterial;
  33901. } else if (mesh.isLine) {
  33902. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  33903. var lineMaterial = this.cache.get(cacheKey);
  33904. if (!lineMaterial) {
  33905. lineMaterial = new _threeModule.LineBasicMaterial();
  33906. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  33907. lineMaterial.color.copy(material.color);
  33908. this.cache.add(cacheKey, lineMaterial);
  33909. }
  33910. material = lineMaterial;
  33911. } // Clone the material if it will be modified
  33912. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  33913. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  33914. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  33915. if (useSkinning) cacheKey += 'skinning:';
  33916. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  33917. if (useVertexColors) cacheKey += 'vertex-colors:';
  33918. if (useFlatShading) cacheKey += 'flat-shading:';
  33919. if (useMorphTargets) cacheKey += 'morph-targets:';
  33920. if (useMorphNormals) cacheKey += 'morph-normals:';
  33921. var cachedMaterial = this.cache.get(cacheKey);
  33922. if (!cachedMaterial) {
  33923. cachedMaterial = material.clone();
  33924. if (useSkinning) cachedMaterial.skinning = true;
  33925. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  33926. if (useVertexColors) cachedMaterial.vertexColors = true;
  33927. if (useFlatShading) cachedMaterial.flatShading = true;
  33928. if (useMorphTargets) cachedMaterial.morphTargets = true;
  33929. if (useMorphNormals) cachedMaterial.morphNormals = true;
  33930. this.cache.add(cacheKey, cachedMaterial);
  33931. this.associations.set(cachedMaterial, this.associations.get(material));
  33932. }
  33933. material = cachedMaterial;
  33934. } // workarounds for mesh and geometry
  33935. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  33936. geometry.setAttribute('uv2', geometry.attributes.uv);
  33937. } // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  33938. if (material.normalScale && !useVertexTangents) {
  33939. material.normalScale.y = -material.normalScale.y;
  33940. }
  33941. if (material.clearcoatNormalScale && !useVertexTangents) {
  33942. material.clearcoatNormalScale.y = -material.clearcoatNormalScale.y;
  33943. }
  33944. mesh.material = material;
  33945. };
  33946. GLTFParser.prototype.getMaterialType = function ()
  33947. /* materialIndex */
  33948. {
  33949. return _threeModule.MeshStandardMaterial;
  33950. };
  33951. /**
  33952. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  33953. * @param {number} materialIndex
  33954. * @return {Promise<Material>}
  33955. */
  33956. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  33957. var parser = this;
  33958. var json = this.json;
  33959. var extensions = this.extensions;
  33960. var materialDef = json.materials[materialIndex];
  33961. var materialType;
  33962. var materialParams = {};
  33963. var materialExtensions = materialDef.extensions || {};
  33964. var pending = [];
  33965. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  33966. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  33967. materialType = sgExtension.getMaterialType();
  33968. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  33969. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  33970. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  33971. materialType = kmuExtension.getMaterialType();
  33972. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  33973. } else {
  33974. // Specification:
  33975. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  33976. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  33977. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  33978. materialParams.opacity = 1.0;
  33979. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  33980. var array = metallicRoughness.baseColorFactor;
  33981. materialParams.color.fromArray(array);
  33982. materialParams.opacity = array[3];
  33983. }
  33984. if (metallicRoughness.baseColorTexture !== undefined) {
  33985. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  33986. }
  33987. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  33988. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  33989. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  33990. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  33991. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  33992. }
  33993. materialType = this._invokeOne(function (ext) {
  33994. return ext.getMaterialType && ext.getMaterialType(materialIndex);
  33995. });
  33996. pending.push(Promise.all(this._invokeAll(function (ext) {
  33997. return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams);
  33998. })));
  33999. }
  34000. if (materialDef.doubleSided === true) {
  34001. materialParams.side = _threeModule.DoubleSide;
  34002. }
  34003. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  34004. if (alphaMode === ALPHA_MODES.BLEND) {
  34005. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  34006. materialParams.depthWrite = false;
  34007. } else {
  34008. materialParams.transparent = false;
  34009. if (alphaMode === ALPHA_MODES.MASK) {
  34010. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  34011. }
  34012. }
  34013. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34014. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  34015. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  34016. if (materialDef.normalTexture.scale !== undefined) {
  34017. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  34018. }
  34019. }
  34020. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34021. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  34022. if (materialDef.occlusionTexture.strength !== undefined) {
  34023. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  34024. }
  34025. }
  34026. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34027. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  34028. }
  34029. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34030. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  34031. }
  34032. return Promise.all(pending).then(function () {
  34033. var material;
  34034. if (materialType === GLTFMeshStandardSGMaterial) {
  34035. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  34036. } else {
  34037. material = new materialType(materialParams);
  34038. }
  34039. if (materialDef.name) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  34040. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  34041. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  34042. assignExtrasToUserData(material, materialDef);
  34043. parser.associations.set(material, {
  34044. type: 'materials',
  34045. index: materialIndex
  34046. });
  34047. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  34048. return material;
  34049. });
  34050. };
  34051. /** When Object3D instances are targeted by animation, they need unique names. */
  34052. GLTFParser.prototype.createUniqueName = function (originalName) {
  34053. var name = _threeModule.PropertyBinding.sanitizeNodeName(originalName || '');
  34054. for (var i = 1; this.nodeNamesUsed[name]; ++i) {
  34055. name = originalName + '_' + i;
  34056. }
  34057. this.nodeNamesUsed[name] = true;
  34058. return name;
  34059. };
  34060. /**
  34061. * @param {BufferGeometry} geometry
  34062. * @param {GLTF.Primitive} primitiveDef
  34063. * @param {GLTFParser} parser
  34064. */
  34065. function computeBounds(geometry, primitiveDef, parser) {
  34066. var attributes = primitiveDef.attributes;
  34067. var box = new _threeModule.Box3();
  34068. if (attributes.POSITION !== undefined) {
  34069. var accessor = parser.json.accessors[attributes.POSITION];
  34070. var min = accessor.min;
  34071. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  34072. if (min !== undefined && max !== undefined) {
  34073. box.set(new _threeModule.Vector3(min[0], min[1], min[2]), new _threeModule.Vector3(max[0], max[1], max[2]));
  34074. } else {
  34075. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  34076. return;
  34077. }
  34078. } else {
  34079. return;
  34080. }
  34081. var targets = primitiveDef.targets;
  34082. if (targets !== undefined) {
  34083. var maxDisplacement = new _threeModule.Vector3();
  34084. var vector = new _threeModule.Vector3();
  34085. for (var i = 0, il = targets.length; i < il; i++) {
  34086. var target = targets[i];
  34087. if (target.POSITION !== undefined) {
  34088. var accessor = parser.json.accessors[target.POSITION];
  34089. var min = accessor.min;
  34090. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  34091. if (min !== undefined && max !== undefined) {
  34092. // we need to get max of absolute components because target weight is [-1,1]
  34093. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
  34094. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
  34095. vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  34096. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  34097. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  34098. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  34099. maxDisplacement.max(vector);
  34100. } else {
  34101. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  34102. }
  34103. }
  34104. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  34105. box.expandByVector(maxDisplacement);
  34106. }
  34107. geometry.boundingBox = box;
  34108. var sphere = new _threeModule.Sphere();
  34109. box.getCenter(sphere.center);
  34110. sphere.radius = box.min.distanceTo(box.max) / 2;
  34111. geometry.boundingSphere = sphere;
  34112. }
  34113. /**
  34114. * @param {BufferGeometry} geometry
  34115. * @param {GLTF.Primitive} primitiveDef
  34116. * @param {GLTFParser} parser
  34117. * @return {Promise<BufferGeometry>}
  34118. */
  34119. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  34120. var attributes = primitiveDef.attributes;
  34121. var pending = [];
  34122. function assignAttributeAccessor(accessorIndex, attributeName) {
  34123. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  34124. geometry.setAttribute(attributeName, accessor);
  34125. });
  34126. }
  34127. for (var gltfAttributeName in attributes) {
  34128. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  34129. if (threeAttributeName in geometry.attributes) continue;
  34130. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  34131. }
  34132. if (primitiveDef.indices !== undefined && !geometry.index) {
  34133. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  34134. geometry.setIndex(accessor);
  34135. });
  34136. pending.push(accessor);
  34137. }
  34138. assignExtrasToUserData(geometry, primitiveDef);
  34139. computeBounds(geometry, primitiveDef, parser);
  34140. return Promise.all(pending).then(function () {
  34141. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  34142. });
  34143. }
  34144. /**
  34145. * @param {BufferGeometry} geometry
  34146. * @param {Number} drawMode
  34147. * @return {BufferGeometry}
  34148. */
  34149. function toTrianglesDrawMode(geometry, drawMode) {
  34150. var index = geometry.getIndex(); // generate index if not present
  34151. if (index === null) {
  34152. var indices = [];
  34153. var position = geometry.getAttribute('position');
  34154. if (position !== undefined) {
  34155. for (var i = 0; i < position.count; i++) {
  34156. indices.push(i);
  34157. }
  34158. geometry.setIndex(indices);
  34159. index = geometry.getIndex();
  34160. } else {
  34161. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  34162. return geometry;
  34163. }
  34164. } //
  34165. var numberOfTriangles = index.count - 2;
  34166. var newIndices = [];
  34167. if (drawMode === _threeModule.TriangleFanDrawMode) {
  34168. // gl.TRIANGLE_FAN
  34169. for (var i = 1; i <= numberOfTriangles; i++) {
  34170. newIndices.push(index.getX(0));
  34171. newIndices.push(index.getX(i));
  34172. newIndices.push(index.getX(i + 1));
  34173. }
  34174. } else {
  34175. // gl.TRIANGLE_STRIP
  34176. for (var i = 0; i < numberOfTriangles; i++) {
  34177. if (i % 2 === 0) {
  34178. newIndices.push(index.getX(i));
  34179. newIndices.push(index.getX(i + 1));
  34180. newIndices.push(index.getX(i + 2));
  34181. } else {
  34182. newIndices.push(index.getX(i + 2));
  34183. newIndices.push(index.getX(i + 1));
  34184. newIndices.push(index.getX(i));
  34185. }
  34186. }
  34187. }
  34188. if (newIndices.length / 3 !== numberOfTriangles) {
  34189. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  34190. } // build final geometry
  34191. var newGeometry = geometry.clone();
  34192. newGeometry.setIndex(newIndices);
  34193. return newGeometry;
  34194. }
  34195. /**
  34196. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  34197. *
  34198. * Creates BufferGeometries from primitives.
  34199. *
  34200. * @param {Array<GLTF.Primitive>} primitives
  34201. * @return {Promise<Array<BufferGeometry>>}
  34202. */
  34203. GLTFParser.prototype.loadGeometries = function (primitives) {
  34204. var parser = this;
  34205. var extensions = this.extensions;
  34206. var cache = this.primitiveCache;
  34207. function createDracoPrimitive(primitive) {
  34208. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  34209. return addPrimitiveAttributes(geometry, primitive, parser);
  34210. });
  34211. }
  34212. var pending = [];
  34213. for (var i = 0, il = primitives.length; i < il; i++) {
  34214. var primitive = primitives[i];
  34215. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  34216. var cached = cache[cacheKey];
  34217. if (cached) {
  34218. // Use the cached geometry if it exists
  34219. pending.push(cached.promise);
  34220. } else {
  34221. var geometryPromise;
  34222. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  34223. // Use DRACO geometry if available
  34224. geometryPromise = createDracoPrimitive(primitive);
  34225. } else {
  34226. // Otherwise create a new geometry
  34227. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  34228. } // Cache this geometry
  34229. cache[cacheKey] = {
  34230. primitive: primitive,
  34231. promise: geometryPromise
  34232. };
  34233. pending.push(geometryPromise);
  34234. }
  34235. }
  34236. return Promise.all(pending);
  34237. };
  34238. /**
  34239. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  34240. * @param {number} meshIndex
  34241. * @return {Promise<Group|Mesh|SkinnedMesh>}
  34242. */
  34243. GLTFParser.prototype.loadMesh = function (meshIndex) {
  34244. var parser = this;
  34245. var json = this.json;
  34246. var extensions = this.extensions;
  34247. var meshDef = json.meshes[meshIndex];
  34248. var primitives = meshDef.primitives;
  34249. var pending = [];
  34250. for (var i = 0, il = primitives.length; i < il; i++) {
  34251. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  34252. pending.push(material);
  34253. }
  34254. pending.push(parser.loadGeometries(primitives));
  34255. return Promise.all(pending).then(function (results) {
  34256. var materials = results.slice(0, results.length - 1);
  34257. var geometries = results[results.length - 1];
  34258. var meshes = [];
  34259. for (var i = 0, il = geometries.length; i < il; i++) {
  34260. var geometry = geometries[i];
  34261. var primitive = primitives[i]; // 1. create Mesh
  34262. var mesh;
  34263. var material = materials[i];
  34264. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  34265. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  34266. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  34267. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  34268. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  34269. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  34270. mesh.normalizeSkinWeights();
  34271. }
  34272. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  34273. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleStripDrawMode);
  34274. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  34275. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleFanDrawMode);
  34276. }
  34277. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  34278. mesh = new _threeModule.LineSegments(geometry, material);
  34279. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  34280. mesh = new _threeModule.Line(geometry, material);
  34281. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  34282. mesh = new _threeModule.LineLoop(geometry, material);
  34283. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  34284. mesh = new _threeModule.Points(geometry, material);
  34285. } else {
  34286. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  34287. }
  34288. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  34289. updateMorphTargets(mesh, meshDef);
  34290. }
  34291. mesh.name = parser.createUniqueName(meshDef.name || 'mesh_' + meshIndex);
  34292. assignExtrasToUserData(mesh, meshDef);
  34293. if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive);
  34294. parser.assignFinalMaterial(mesh);
  34295. meshes.push(mesh);
  34296. }
  34297. if (meshes.length === 1) {
  34298. return meshes[0];
  34299. }
  34300. var group = new _threeModule.Group();
  34301. for (var i = 0, il = meshes.length; i < il; i++) {
  34302. group.add(meshes[i]);
  34303. }
  34304. return group;
  34305. });
  34306. };
  34307. /**
  34308. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  34309. * @param {number} cameraIndex
  34310. * @return {Promise<THREE.Camera>}
  34311. */
  34312. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  34313. var camera;
  34314. var cameraDef = this.json.cameras[cameraIndex];
  34315. var params = cameraDef[cameraDef.type];
  34316. if (!params) {
  34317. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  34318. return;
  34319. }
  34320. if (cameraDef.type === 'perspective') {
  34321. camera = new _threeModule.PerspectiveCamera(_threeModule.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  34322. } else if (cameraDef.type === 'orthographic') {
  34323. camera = new _threeModule.OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar);
  34324. }
  34325. if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name);
  34326. assignExtrasToUserData(camera, cameraDef);
  34327. return Promise.resolve(camera);
  34328. };
  34329. /**
  34330. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  34331. * @param {number} skinIndex
  34332. * @return {Promise<Object>}
  34333. */
  34334. GLTFParser.prototype.loadSkin = function (skinIndex) {
  34335. var skinDef = this.json.skins[skinIndex];
  34336. var skinEntry = {
  34337. joints: skinDef.joints
  34338. };
  34339. if (skinDef.inverseBindMatrices === undefined) {
  34340. return Promise.resolve(skinEntry);
  34341. }
  34342. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  34343. skinEntry.inverseBindMatrices = accessor;
  34344. return skinEntry;
  34345. });
  34346. };
  34347. /**
  34348. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  34349. * @param {number} animationIndex
  34350. * @return {Promise<AnimationClip>}
  34351. */
  34352. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  34353. var json = this.json;
  34354. var animationDef = json.animations[animationIndex];
  34355. var pendingNodes = [];
  34356. var pendingInputAccessors = [];
  34357. var pendingOutputAccessors = [];
  34358. var pendingSamplers = [];
  34359. var pendingTargets = [];
  34360. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  34361. var channel = animationDef.channels[i];
  34362. var sampler = animationDef.samplers[channel.sampler];
  34363. var target = channel.target;
  34364. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  34365. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  34366. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  34367. pendingNodes.push(this.getDependency('node', name));
  34368. pendingInputAccessors.push(this.getDependency('accessor', input));
  34369. pendingOutputAccessors.push(this.getDependency('accessor', output));
  34370. pendingSamplers.push(sampler);
  34371. pendingTargets.push(target);
  34372. }
  34373. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  34374. var nodes = dependencies[0];
  34375. var inputAccessors = dependencies[1];
  34376. var outputAccessors = dependencies[2];
  34377. var samplers = dependencies[3];
  34378. var targets = dependencies[4];
  34379. var tracks = [];
  34380. for (var i = 0, il = nodes.length; i < il; i++) {
  34381. var node = nodes[i];
  34382. var inputAccessor = inputAccessors[i];
  34383. var outputAccessor = outputAccessors[i];
  34384. var sampler = samplers[i];
  34385. var target = targets[i];
  34386. if (node === undefined) continue;
  34387. node.updateMatrix();
  34388. node.matrixAutoUpdate = true;
  34389. var TypedKeyframeTrack;
  34390. switch (PATH_PROPERTIES[target.path]) {
  34391. case PATH_PROPERTIES.weights:
  34392. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  34393. break;
  34394. case PATH_PROPERTIES.rotation:
  34395. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  34396. break;
  34397. case PATH_PROPERTIES.position:
  34398. case PATH_PROPERTIES.scale:
  34399. default:
  34400. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  34401. break;
  34402. }
  34403. var targetName = node.name ? node.name : node.uuid;
  34404. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  34405. var targetNames = [];
  34406. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  34407. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  34408. node.traverse(function (object) {
  34409. if (object.isMesh === true && object.morphTargetInfluences) {
  34410. targetNames.push(object.name ? object.name : object.uuid);
  34411. }
  34412. });
  34413. } else {
  34414. targetNames.push(targetName);
  34415. }
  34416. var outputArray = outputAccessor.array;
  34417. if (outputAccessor.normalized) {
  34418. var scale;
  34419. if (outputArray.constructor === Int8Array) {
  34420. scale = 1 / 127;
  34421. } else if (outputArray.constructor === Uint8Array) {
  34422. scale = 1 / 255;
  34423. } else if (outputArray.constructor == Int16Array) {
  34424. scale = 1 / 32767;
  34425. } else if (outputArray.constructor === Uint16Array) {
  34426. scale = 1 / 65535;
  34427. } else {
  34428. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  34429. }
  34430. var scaled = new Float32Array(outputArray.length);
  34431. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  34432. scaled[j] = outputArray[j] * scale;
  34433. }
  34434. outputArray = scaled;
  34435. }
  34436. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  34437. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  34438. if (sampler.interpolation === 'CUBICSPLINE') {
  34439. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  34440. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  34441. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  34442. // must be divided by three to get the interpolant's sampleSize argument.
  34443. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  34444. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  34445. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  34446. }
  34447. tracks.push(track);
  34448. }
  34449. }
  34450. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  34451. return new _threeModule.AnimationClip(name, undefined, tracks);
  34452. });
  34453. };
  34454. /**
  34455. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  34456. * @param {number} nodeIndex
  34457. * @return {Promise<Object3D>}
  34458. */
  34459. GLTFParser.prototype.loadNode = function (nodeIndex) {
  34460. var json = this.json;
  34461. var extensions = this.extensions;
  34462. var parser = this;
  34463. var nodeDef = json.nodes[nodeIndex]; // reserve node's name before its dependencies, so the root has the intended name.
  34464. var nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : '';
  34465. return function () {
  34466. var pending = [];
  34467. if (nodeDef.mesh !== undefined) {
  34468. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  34469. var node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); // if weights are provided on the node, override weights on the mesh.
  34470. if (nodeDef.weights !== undefined) {
  34471. node.traverse(function (o) {
  34472. if (!o.isMesh) return;
  34473. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  34474. o.morphTargetInfluences[i] = nodeDef.weights[i];
  34475. }
  34476. });
  34477. }
  34478. return node;
  34479. }));
  34480. }
  34481. if (nodeDef.camera !== undefined) {
  34482. pending.push(parser.getDependency('camera', nodeDef.camera).then(function (camera) {
  34483. return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera);
  34484. }));
  34485. }
  34486. parser._invokeAll(function (ext) {
  34487. return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex);
  34488. }).forEach(function (promise) {
  34489. pending.push(promise);
  34490. });
  34491. return Promise.all(pending);
  34492. }().then(function (objects) {
  34493. var node; // .isBone isn't in glTF spec. See ._markDefs
  34494. if (nodeDef.isBone === true) {
  34495. node = new _threeModule.Bone();
  34496. } else if (objects.length > 1) {
  34497. node = new _threeModule.Group();
  34498. } else if (objects.length === 1) {
  34499. node = objects[0];
  34500. } else {
  34501. node = new _threeModule.Object3D();
  34502. }
  34503. if (node !== objects[0]) {
  34504. for (var i = 0, il = objects.length; i < il; i++) {
  34505. node.add(objects[i]);
  34506. }
  34507. }
  34508. if (nodeDef.name) {
  34509. node.userData.name = nodeDef.name;
  34510. node.name = nodeName;
  34511. }
  34512. assignExtrasToUserData(node, nodeDef);
  34513. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  34514. if (nodeDef.matrix !== undefined) {
  34515. var matrix = new _threeModule.Matrix4();
  34516. matrix.fromArray(nodeDef.matrix);
  34517. node.applyMatrix4(matrix);
  34518. } else {
  34519. if (nodeDef.translation !== undefined) {
  34520. node.position.fromArray(nodeDef.translation);
  34521. }
  34522. if (nodeDef.rotation !== undefined) {
  34523. node.quaternion.fromArray(nodeDef.rotation);
  34524. }
  34525. if (nodeDef.scale !== undefined) {
  34526. node.scale.fromArray(nodeDef.scale);
  34527. }
  34528. }
  34529. parser.associations.set(node, {
  34530. type: 'nodes',
  34531. index: nodeIndex
  34532. });
  34533. return node;
  34534. });
  34535. };
  34536. /**
  34537. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  34538. * @param {number} sceneIndex
  34539. * @return {Promise<Group>}
  34540. */
  34541. GLTFParser.prototype.loadScene = function () {
  34542. // scene node hierachy builder
  34543. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  34544. var nodeDef = json.nodes[nodeId];
  34545. return parser.getDependency('node', nodeId).then(function (node) {
  34546. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  34547. var skinEntry;
  34548. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  34549. skinEntry = skin;
  34550. var pendingJoints = [];
  34551. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  34552. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  34553. }
  34554. return Promise.all(pendingJoints);
  34555. }).then(function (jointNodes) {
  34556. node.traverse(function (mesh) {
  34557. if (!mesh.isMesh) return;
  34558. var bones = [];
  34559. var boneInverses = [];
  34560. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  34561. var jointNode = jointNodes[j];
  34562. if (jointNode) {
  34563. bones.push(jointNode);
  34564. var mat = new _threeModule.Matrix4();
  34565. if (skinEntry.inverseBindMatrices !== undefined) {
  34566. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  34567. }
  34568. boneInverses.push(mat);
  34569. } else {
  34570. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  34571. }
  34572. }
  34573. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  34574. });
  34575. return node;
  34576. });
  34577. }).then(function (node) {
  34578. // build node hierachy
  34579. parentObject.add(node);
  34580. var pending = [];
  34581. if (nodeDef.children) {
  34582. var children = nodeDef.children;
  34583. for (var i = 0, il = children.length; i < il; i++) {
  34584. var child = children[i];
  34585. pending.push(buildNodeHierachy(child, node, json, parser));
  34586. }
  34587. }
  34588. return Promise.all(pending);
  34589. });
  34590. }
  34591. return function loadScene(sceneIndex) {
  34592. var json = this.json;
  34593. var extensions = this.extensions;
  34594. var sceneDef = this.json.scenes[sceneIndex];
  34595. var parser = this; // Loader returns Group, not Scene.
  34596. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  34597. var scene = new _threeModule.Group();
  34598. if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name);
  34599. assignExtrasToUserData(scene, sceneDef);
  34600. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  34601. var nodeIds = sceneDef.nodes || [];
  34602. var pending = [];
  34603. for (var i = 0, il = nodeIds.length; i < il; i++) {
  34604. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  34605. }
  34606. return Promise.all(pending).then(function () {
  34607. return scene;
  34608. });
  34609. };
  34610. }();
  34611. return GLTFLoader;
  34612. }();
  34613. exports.GLTFLoader = GLTFLoader;
  34614. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  34615. "use strict";
  34616. Object.defineProperty(exports, "__esModule", {
  34617. value: true
  34618. });
  34619. exports.B3DMLoader = void 0;
  34620. var _B3DMLoaderBase2 = require("../base/B3DMLoaderBase.js");
  34621. var _three = require("three");
  34622. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  34623. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34624. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34625. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34626. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34627. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34628. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34629. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34630. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34631. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34632. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34633. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34634. var B3DMLoader =
  34635. /*#__PURE__*/
  34636. function (_B3DMLoaderBase) {
  34637. _inherits(B3DMLoader, _B3DMLoaderBase);
  34638. function B3DMLoader() {
  34639. var _this;
  34640. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34641. _classCallCheck(this, B3DMLoader);
  34642. _this = _possibleConstructorReturn(this, _getPrototypeOf(B3DMLoader).call(this));
  34643. _this.manager = manager;
  34644. return _this;
  34645. }
  34646. _createClass(B3DMLoader, [{
  34647. key: "parse",
  34648. value: function parse(buffer) {
  34649. var _this2 = this;
  34650. var b3dm = _get(_getPrototypeOf(B3DMLoader.prototype), "parse", this).call(this, buffer);
  34651. var gltfBuffer = b3dm.glbBytes.slice().buffer;
  34652. return new Promise(function (resolve, reject) {
  34653. var manager = _this2.manager;
  34654. var loader = manager.getHandler('path.gltf') || new _GLTFLoader.GLTFLoader(manager);
  34655. loader.parse(gltfBuffer, null, function (model) {
  34656. model.batchTable = b3dm.batchTable;
  34657. model.featureTable = b3dm.featureTable;
  34658. model.scene.batchTable = b3dm.batchTable;
  34659. model.scene.featureTable = b3dm.featureTable;
  34660. resolve(model);
  34661. }, reject);
  34662. });
  34663. }
  34664. }]);
  34665. return B3DMLoader;
  34666. }(_B3DMLoaderBase2.B3DMLoaderBase);
  34667. exports.B3DMLoader = B3DMLoader;
  34668. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/base/PNTSLoaderBase.js":[function(require,module,exports) {
  34669. "use strict";
  34670. Object.defineProperty(exports, "__esModule", {
  34671. value: true
  34672. });
  34673. exports.PNTSLoaderBase = void 0;
  34674. var _FeatureTable = require("../utilities/FeatureTable.js");
  34675. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34676. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34677. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34678. var PNTSLoaderBase =
  34679. /*#__PURE__*/
  34680. function () {
  34681. function PNTSLoaderBase() {
  34682. _classCallCheck(this, PNTSLoaderBase);
  34683. this.fetchOptions = {};
  34684. }
  34685. _createClass(PNTSLoaderBase, [{
  34686. key: "load",
  34687. value: function load(url) {
  34688. var _this = this;
  34689. return fetch(url, this.fetchOptions).then(function (res) {
  34690. if (!res.ok) {
  34691. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  34692. }
  34693. return res.arrayBuffer();
  34694. }).then(function (buffer) {
  34695. return _this.parse(buffer);
  34696. });
  34697. }
  34698. }, {
  34699. key: "parse",
  34700. value: function parse(buffer) {
  34701. var dataView = new DataView(buffer); // 28-byte header
  34702. // 4 bytes
  34703. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  34704. console.assert(magic === 'pnts'); // 4 bytes
  34705. var version = dataView.getUint32(4, true);
  34706. console.assert(version === 1); // 4 bytes
  34707. var byteLength = dataView.getUint32(8, true);
  34708. console.assert(byteLength === buffer.byteLength); // 4 bytes
  34709. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  34710. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  34711. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  34712. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  34713. var featureTableStart = 28;
  34714. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  34715. var batchLength = featureTable.getData('BATCH_LENGTH') || featureTable.getData('POINTS_LENGTH');
  34716. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  34717. var batchTable = new _FeatureTable.BatchTable(buffer, batchLength, batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  34718. return {
  34719. version: version,
  34720. featureTable: featureTable,
  34721. batchTable: batchTable
  34722. };
  34723. }
  34724. }]);
  34725. return PNTSLoaderBase;
  34726. }();
  34727. exports.PNTSLoaderBase = PNTSLoaderBase;
  34728. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js"}],"../src/three/PNTSLoader.js":[function(require,module,exports) {
  34729. "use strict";
  34730. Object.defineProperty(exports, "__esModule", {
  34731. value: true
  34732. });
  34733. exports.PNTSLoader = void 0;
  34734. var _PNTSLoaderBase2 = require("../base/PNTSLoaderBase.js");
  34735. var _three = require("three");
  34736. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34737. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34738. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34739. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34740. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34741. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34742. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34743. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34744. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34745. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34746. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34747. var PNTSLoader =
  34748. /*#__PURE__*/
  34749. function (_PNTSLoaderBase) {
  34750. _inherits(PNTSLoader, _PNTSLoaderBase);
  34751. function PNTSLoader() {
  34752. var _this;
  34753. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34754. _classCallCheck(this, PNTSLoader);
  34755. _this = _possibleConstructorReturn(this, _getPrototypeOf(PNTSLoader).call(this));
  34756. _this.manager = manager;
  34757. return _this;
  34758. }
  34759. _createClass(PNTSLoader, [{
  34760. key: "parse",
  34761. value: function parse(buffer) {
  34762. var result = _get(_getPrototypeOf(PNTSLoader.prototype), "parse", this).call(this, buffer);
  34763. var featureTable = result.featureTable; // global semantics
  34764. var POINTS_LENGTH = featureTable.getData('POINTS_LENGTH'); // RTC_CENTER
  34765. // QUANTIZED_VOLUME_OFFSET
  34766. // QUANTIZED_VOLUME_SCALE
  34767. // CONSTANT_RGBA
  34768. // BATCH_LENGTH
  34769. var POSITION = featureTable.getData('POSITION', POINTS_LENGTH, 'FLOAT', 'VEC3');
  34770. var RGB = featureTable.getData('RGB', POINTS_LENGTH, 'UNSIGNED_BYTE', 'VEC3'); // POSITION_QUANTIZED
  34771. // RGBA
  34772. // RGB565
  34773. // NORMAL
  34774. // NORMAL_OCT16P
  34775. // BATCH_ID
  34776. if (POSITION === null) {
  34777. throw new Error('PNTSLoader : POSITION_QUANTIZED feature type is not supported.');
  34778. }
  34779. var geometry = new _three.BufferGeometry();
  34780. geometry.setAttribute('position', new _three.BufferAttribute(POSITION, 3, false));
  34781. var material = new _three.PointsMaterial();
  34782. material.size = 2;
  34783. material.sizeAttenuation = false;
  34784. if (RGB !== null) {
  34785. geometry.setAttribute('color', new _three.BufferAttribute(RGB, 3, true));
  34786. material.vertexColors = true;
  34787. }
  34788. var object = new _three.Points(geometry, material);
  34789. result.scene = object;
  34790. result.scene.featureTable = featureTable;
  34791. return result;
  34792. }
  34793. }]);
  34794. return PNTSLoader;
  34795. }(_PNTSLoaderBase2.PNTSLoaderBase);
  34796. exports.PNTSLoader = PNTSLoader;
  34797. },{"../base/PNTSLoaderBase.js":"../src/base/PNTSLoaderBase.js","three":"../node_modules/three/build/three.module.js"}],"../src/base/I3DMLoaderBase.js":[function(require,module,exports) {
  34798. "use strict";
  34799. Object.defineProperty(exports, "__esModule", {
  34800. value: true
  34801. });
  34802. exports.I3DMLoaderBase = void 0;
  34803. var _FeatureTable = require("../utilities/FeatureTable.js");
  34804. var _arrayToString = require("../utilities/arrayToString.js");
  34805. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34806. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34807. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34808. var I3DMLoaderBase =
  34809. /*#__PURE__*/
  34810. function () {
  34811. function I3DMLoaderBase() {
  34812. _classCallCheck(this, I3DMLoaderBase);
  34813. this.fetchOptions = {};
  34814. }
  34815. _createClass(I3DMLoaderBase, [{
  34816. key: "load",
  34817. value: function load(url) {
  34818. var _this = this;
  34819. return fetch(url, this.fetchOptions).then(function (res) {
  34820. if (!res.ok) {
  34821. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  34822. }
  34823. return res.arrayBuffer();
  34824. }).then(function (buffer) {
  34825. return _this.parse(buffer);
  34826. });
  34827. }
  34828. }, {
  34829. key: "parse",
  34830. value: function parse(buffer) {
  34831. var dataView = new DataView(buffer); // 32-byte header
  34832. // 4 bytes
  34833. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  34834. console.assert(magic === 'i3dm'); // 4 bytes
  34835. var version = dataView.getUint32(4, true);
  34836. console.assert(version === 1); // 4 bytes
  34837. var byteLength = dataView.getUint32(8, true);
  34838. console.assert(byteLength === buffer.byteLength); // 4 bytes
  34839. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  34840. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  34841. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  34842. var batchTableBinaryByteLength = dataView.getUint32(24, true); // 4 bytes
  34843. var gltfFormat = dataView.getUint32(28, true); // Feature Table
  34844. var featureTableStart = 32;
  34845. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  34846. var batchLength = featureTable.getData('INSTANCES_LENGTH');
  34847. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  34848. var batchTable = new _FeatureTable.BatchTable(buffer, batchLength, batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  34849. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  34850. var bodyBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart);
  34851. var glbBytes = null;
  34852. var promise = null;
  34853. if (gltfFormat) {
  34854. glbBytes = bodyBytes;
  34855. promise = Promise.resolve();
  34856. } else {
  34857. var externalUri = (0, _arrayToString.arrayToString)(bodyBytes);
  34858. promise = fetch(externalUri, this.fetchOptions).then(function (res) {
  34859. return res.buffer;
  34860. }).then(function (buffer) {
  34861. glbBytes = new Uint8Array(buffer);
  34862. });
  34863. }
  34864. return promise.then(function () {
  34865. return {
  34866. version: version,
  34867. featureTable: featureTable,
  34868. batchTable: batchTable,
  34869. glbBytes: glbBytes
  34870. };
  34871. });
  34872. }
  34873. }]);
  34874. return I3DMLoaderBase;
  34875. }();
  34876. exports.I3DMLoaderBase = I3DMLoaderBase;
  34877. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js","../utilities/arrayToString.js":"../src/utilities/arrayToString.js"}],"../src/three/I3DMLoader.js":[function(require,module,exports) {
  34878. "use strict";
  34879. Object.defineProperty(exports, "__esModule", {
  34880. value: true
  34881. });
  34882. exports.I3DMLoader = void 0;
  34883. var _I3DMLoaderBase2 = require("../base/I3DMLoaderBase.js");
  34884. var _three = require("three");
  34885. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  34886. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34887. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34888. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34889. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34890. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34891. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34892. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34893. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34894. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34895. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34896. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34897. var tempPos = new _three.Vector3();
  34898. var tempQuat = new _three.Quaternion();
  34899. var tempSca = new _three.Vector3();
  34900. var tempMat = new _three.Matrix4();
  34901. var I3DMLoader =
  34902. /*#__PURE__*/
  34903. function (_I3DMLoaderBase) {
  34904. _inherits(I3DMLoader, _I3DMLoaderBase);
  34905. function I3DMLoader() {
  34906. var _this;
  34907. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34908. _classCallCheck(this, I3DMLoader);
  34909. _this = _possibleConstructorReturn(this, _getPrototypeOf(I3DMLoader).call(this));
  34910. _this.manager = manager;
  34911. return _this;
  34912. }
  34913. _createClass(I3DMLoader, [{
  34914. key: "parse",
  34915. value: function parse(buffer) {
  34916. var _this2 = this;
  34917. return _get(_getPrototypeOf(I3DMLoader.prototype), "parse", this).call(this, buffer).then(function (i3dm) {
  34918. var featureTable = i3dm.featureTable,
  34919. batchTable = i3dm.batchTable;
  34920. var gltfBuffer = i3dm.glbBytes.slice().buffer;
  34921. return new Promise(function (resolve, reject) {
  34922. var manager = _this2.manager;
  34923. var loader = manager.getHandler('path.gltf') || new _GLTFLoader.GLTFLoader(manager);
  34924. loader.parse(gltfBuffer, null, function (model) {
  34925. var INSTANCES_LENGTH = featureTable.getData('INSTANCES_LENGTH'); // RTC_CENTER
  34926. // QUANTIZED_VOLUME_OFFSET
  34927. // QUANTIZED_VOLUME_SCALE
  34928. // EAST_NORTH_UP
  34929. var POSITION = featureTable.getData('POSITION', INSTANCES_LENGTH, 'FLOAT', 'VEC3'); // POSITION_QUANTIZED
  34930. // NORMAL_UP
  34931. // NORMAL_RIGHT
  34932. // NORMAL_UP_OCT32P
  34933. // NORMAL_RIGHT_OCT32P
  34934. // SCALE
  34935. // SCALE_NON_UNIFORM
  34936. // BATCH_ID
  34937. var instanceMap = new Map();
  34938. var instances = [];
  34939. model.scene.traverse(function (child) {
  34940. if (child.isMesh) {
  34941. var geometry = child.geometry,
  34942. material = child.material;
  34943. var instancedMesh = new _three.InstancedMesh(geometry, material, INSTANCES_LENGTH);
  34944. instances.push(instancedMesh);
  34945. instanceMap.set(child, instancedMesh);
  34946. }
  34947. });
  34948. var averageVector = new _three.Vector3();
  34949. var transformedVector = new _three.Vector3();
  34950. for (var i = 0; i < INSTANCES_LENGTH; i++) {
  34951. // TODO: handle quantized position
  34952. averageVector.x += POSITION[i * 3 + 0] / INSTANCES_LENGTH;
  34953. averageVector.y += POSITION[i * 3 + 1] / INSTANCES_LENGTH;
  34954. averageVector.z += POSITION[i * 3 + 2] / INSTANCES_LENGTH;
  34955. } // replace the meshes with instanced meshes
  34956. instanceMap.forEach(function (instancedMesh, mesh) {
  34957. var parent = mesh.parent;
  34958. if (parent) {
  34959. // Mesh have no children
  34960. parent.remove(mesh);
  34961. parent.add(instancedMesh); // Center the instance around an average point to avoid jitter at large scales.
  34962. transformedVector.copy(averageVector).applyQuaternion(parent.quaternion).multiply(parent.scale);
  34963. instancedMesh.add(transformedVector);
  34964. }
  34965. });
  34966. for (var _i = 0; _i < INSTANCES_LENGTH; _i++) {
  34967. // TODO: handle quantized position
  34968. tempPos.set(POSITION[_i * 3 + 0] - averageVector.x, POSITION[_i * 3 + 1] - averageVector.y, POSITION[_i * 3 + 2] - averageVector.z); // TODO: handle normal orientation features
  34969. tempQuat.set(0, 0, 0, 1); // TODO: handle scale features
  34970. tempSca.set(1, 1, 1);
  34971. tempMat.compose(tempPos, tempQuat, tempSca);
  34972. for (var j = 0, l = instances.length; j < l; j++) {
  34973. var instance = instances[j];
  34974. instance.setMatrixAt(_i, tempMat);
  34975. }
  34976. }
  34977. model.batchTable = batchTable;
  34978. model.featureTable = featureTable;
  34979. model.scene.batchTable = batchTable;
  34980. model.scene.featureTable = featureTable;
  34981. resolve(model);
  34982. }, reject);
  34983. });
  34984. });
  34985. }
  34986. }]);
  34987. return I3DMLoader;
  34988. }(_I3DMLoaderBase2.I3DMLoaderBase);
  34989. exports.I3DMLoader = I3DMLoader;
  34990. },{"../base/I3DMLoaderBase.js":"../src/base/I3DMLoaderBase.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/base/CMPTLoaderBase.js":[function(require,module,exports) {
  34991. "use strict";
  34992. Object.defineProperty(exports, "__esModule", {
  34993. value: true
  34994. });
  34995. exports.CMPTLoaderBase = void 0;
  34996. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34997. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34998. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34999. // CMPT File Format
  35000. // https://github.com/CesiumGS/3d-tiles/blob/master/specification/TileFormats/Composite/README.md
  35001. var CMPTLoaderBase =
  35002. /*#__PURE__*/
  35003. function () {
  35004. function CMPTLoaderBase() {
  35005. _classCallCheck(this, CMPTLoaderBase);
  35006. this.fetchOptions = {};
  35007. }
  35008. _createClass(CMPTLoaderBase, [{
  35009. key: "load",
  35010. value: function load(url) {
  35011. var _this = this;
  35012. return fetch(url, this.fetchOptions).then(function (res) {
  35013. if (!res.ok) {
  35014. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  35015. }
  35016. return res.arrayBuffer();
  35017. }).then(function (buffer) {
  35018. return _this.parse(buffer);
  35019. });
  35020. }
  35021. }, {
  35022. key: "parse",
  35023. value: function parse(buffer) {
  35024. var dataView = new DataView(buffer); // 16-byte header
  35025. // 4 bytes
  35026. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  35027. console.assert(magic === 'cmpt'); // 4 bytes
  35028. var version = dataView.getUint32(4, true);
  35029. console.assert(version === 1); // 4 bytes
  35030. var byteLength = dataView.getUint32(8, true);
  35031. console.assert(byteLength === buffer.byteLength); // 4 bytes
  35032. var tilesLength = dataView.getUint32(12, true);
  35033. var tiles = [];
  35034. var offset = 16;
  35035. for (var i = 0; i < tilesLength; i++) {
  35036. var tileView = new DataView(buffer, offset, 12);
  35037. var tileMagic = String.fromCharCode(tileView.getUint8(0)) + String.fromCharCode(tileView.getUint8(1)) + String.fromCharCode(tileView.getUint8(2)) + String.fromCharCode(tileView.getUint8(3));
  35038. var tileVersion = tileView.getUint32(4, true);
  35039. var _byteLength = tileView.getUint32(8, true);
  35040. var tileBuffer = new Uint8Array(buffer, offset, _byteLength);
  35041. tiles.push({
  35042. type: tileMagic,
  35043. buffer: tileBuffer,
  35044. version: tileVersion
  35045. });
  35046. offset += _byteLength;
  35047. }
  35048. return {
  35049. version: version,
  35050. tiles: tiles
  35051. };
  35052. }
  35053. }]);
  35054. return CMPTLoaderBase;
  35055. }();
  35056. exports.CMPTLoaderBase = CMPTLoaderBase;
  35057. },{}],"../src/three/CMPTLoader.js":[function(require,module,exports) {
  35058. "use strict";
  35059. Object.defineProperty(exports, "__esModule", {
  35060. value: true
  35061. });
  35062. exports.CMPTLoader = void 0;
  35063. var _three = require("three");
  35064. var _CMPTLoaderBase2 = require("../base/CMPTLoaderBase.js");
  35065. var _B3DMLoader = require("./B3DMLoader.js");
  35066. var _PNTSLoader = require("./PNTSLoader.js");
  35067. var _I3DMLoader = require("./I3DMLoader.js");
  35068. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35069. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35070. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35071. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35072. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35073. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35074. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35075. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35076. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35077. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35078. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35079. var CMPTLoader =
  35080. /*#__PURE__*/
  35081. function (_CMPTLoaderBase) {
  35082. _inherits(CMPTLoader, _CMPTLoaderBase);
  35083. function CMPTLoader() {
  35084. var _this;
  35085. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  35086. _classCallCheck(this, CMPTLoader);
  35087. _this = _possibleConstructorReturn(this, _getPrototypeOf(CMPTLoader).call(this));
  35088. _this.manager = manager;
  35089. return _this;
  35090. }
  35091. _createClass(CMPTLoader, [{
  35092. key: "parse",
  35093. value: function parse(buffer) {
  35094. var result = _get(_getPrototypeOf(CMPTLoader.prototype), "parse", this).call(this, buffer);
  35095. var manager = this.manager;
  35096. var group = new _three.Group();
  35097. var results = [];
  35098. var promises = [];
  35099. for (var i in result.tiles) {
  35100. var _result$tiles$i = result.tiles[i],
  35101. type = _result$tiles$i.type,
  35102. _buffer = _result$tiles$i.buffer;
  35103. switch (type) {
  35104. case 'b3dm':
  35105. {
  35106. var slicedBuffer = _buffer.slice();
  35107. var promise = new _B3DMLoader.B3DMLoader(manager).parse(slicedBuffer.buffer).then(function (res) {
  35108. results.push(res);
  35109. group.add(res.scene);
  35110. });
  35111. promises.push(promise);
  35112. break;
  35113. }
  35114. case 'pnts':
  35115. {
  35116. var _slicedBuffer = _buffer.slice();
  35117. var pointsResult = new _PNTSLoader.PNTSLoader(manager).parse(_slicedBuffer.buffer);
  35118. results.push(pointsResult);
  35119. group.add(pointsResult.scene);
  35120. break;
  35121. }
  35122. case 'i3dm':
  35123. {
  35124. var _slicedBuffer2 = _buffer.slice();
  35125. var _promise = new _I3DMLoader.I3DMLoader(manager).parse(_slicedBuffer2.buffer).then(function (res) {
  35126. results.push(res);
  35127. group.add(res.scene);
  35128. });
  35129. promises.push(_promise);
  35130. break;
  35131. }
  35132. }
  35133. }
  35134. return Promise.all(promises).then(function () {
  35135. return {
  35136. tiles: results,
  35137. scene: group
  35138. };
  35139. });
  35140. }
  35141. }]);
  35142. return CMPTLoader;
  35143. }(_CMPTLoaderBase2.CMPTLoaderBase);
  35144. exports.CMPTLoader = CMPTLoader;
  35145. },{"three":"../node_modules/three/build/three.module.js","../base/CMPTLoaderBase.js":"../src/base/CMPTLoaderBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./PNTSLoader.js":"../src/three/PNTSLoader.js","./I3DMLoader.js":"../src/three/I3DMLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  35146. "use strict";
  35147. Object.defineProperty(exports, "__esModule", {
  35148. value: true
  35149. });
  35150. exports.TilesGroup = void 0;
  35151. var _three = require("three");
  35152. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35153. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35154. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35155. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35156. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35157. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35158. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35159. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35160. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35161. // Specialization of "Group" that only updates world matrices of children if
  35162. // the transform has changed since the last update and ignores the "force"
  35163. // parameter under the assumption that the children tiles will not move.
  35164. var tempMat = new _three.Matrix4();
  35165. var TilesGroup =
  35166. /*#__PURE__*/
  35167. function (_Group) {
  35168. _inherits(TilesGroup, _Group);
  35169. function TilesGroup(tilesRenderer) {
  35170. var _this;
  35171. _classCallCheck(this, TilesGroup);
  35172. _this = _possibleConstructorReturn(this, _getPrototypeOf(TilesGroup).call(this));
  35173. _this.tilesRenderer = tilesRenderer;
  35174. return _this;
  35175. }
  35176. _createClass(TilesGroup, [{
  35177. key: "raycast",
  35178. value: function raycast(raycaster, intersects) {
  35179. this.tilesRenderer.raycast(raycaster, intersects);
  35180. }
  35181. }, {
  35182. key: "updateMatrixWorld",
  35183. value: function updateMatrixWorld(force) {
  35184. if (this.matrixAutoUpdate) {
  35185. this.updateMatrix();
  35186. }
  35187. if (this.matrixWorldNeedsUpdate || force) {
  35188. if (this.parent === null) {
  35189. tempMat.copy(this.matrix);
  35190. } else {
  35191. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  35192. }
  35193. this.matrixWorldNeedsUpdate = false; // check if the matrix changed relative to what it was.
  35194. var elA = tempMat.elements;
  35195. var elB = this.matrixWorld.elements;
  35196. var isDifferent = false;
  35197. for (var i = 0; i < 16; i++) {
  35198. var itemA = elA[i];
  35199. var itemB = elB[i];
  35200. var diff = Math.abs(itemA - itemB);
  35201. if (diff > Number.EPSILON) {
  35202. isDifferent = true;
  35203. break;
  35204. }
  35205. }
  35206. if (isDifferent) {
  35207. this.matrixWorld.copy(tempMat); // update children
  35208. // the children will not have to change unless the parent group has updated
  35209. var children = this.children;
  35210. for (var _i = 0, l = children.length; _i < l; _i++) {
  35211. children[_i].updateMatrixWorld();
  35212. }
  35213. }
  35214. }
  35215. }
  35216. }]);
  35217. return TilesGroup;
  35218. }(_three.Group);
  35219. exports.TilesGroup = TilesGroup;
  35220. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  35221. "use strict";
  35222. Object.defineProperty(exports, "__esModule", {
  35223. value: true
  35224. });
  35225. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  35226. exports.raycastTraverse = raycastTraverse;
  35227. var _three = require("three");
  35228. var _sphere = new _three.Sphere();
  35229. var _mat = new _three.Matrix4();
  35230. var _vec = new _three.Vector3();
  35231. var _vec2 = new _three.Vector3();
  35232. var _ray = new _three.Ray();
  35233. var _hitArray = [];
  35234. function distanceSort(a, b) {
  35235. return a.distance - b.distance;
  35236. }
  35237. function intersectTileScene(scene, raycaster, intersects) {
  35238. // Don't intersect the box3 helpers because those are used for debugging
  35239. scene.traverse(function (c) {
  35240. // We set the default raycast function to empty so three.js doesn't automatically cast against it
  35241. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  35242. });
  35243. } // Returns the closest hit when traversing the tree
  35244. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  35245. // If the root is active make sure we've checked it
  35246. if (activeTiles.has(root)) {
  35247. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  35248. if (_hitArray.length > 0) {
  35249. if (_hitArray.length > 1) {
  35250. _hitArray.sort(distanceSort);
  35251. }
  35252. var res = _hitArray[0];
  35253. _hitArray.length = 0;
  35254. return res;
  35255. } else {
  35256. return null;
  35257. }
  35258. } // TODO: can we avoid creating a new array here every time to save on memory?
  35259. var array = [];
  35260. var children = root.children;
  35261. for (var i = 0, l = children.length; i < l; i++) {
  35262. var tile = children[i];
  35263. var cached = tile.cached;
  35264. var groupMatrixWorld = group.matrixWorld;
  35265. _mat.copy(groupMatrixWorld); // if we don't hit the sphere then early out
  35266. var sphere = cached.sphere;
  35267. if (sphere) {
  35268. _sphere.copy(sphere);
  35269. _sphere.applyMatrix4(_mat);
  35270. if (!raycaster.ray.intersectsSphere(_sphere)) {
  35271. continue;
  35272. }
  35273. } // TODO: check region?
  35274. var boundingBox = cached.box;
  35275. var obbMat = cached.boxTransform;
  35276. if (boundingBox) {
  35277. _mat.multiply(obbMat).invert();
  35278. _ray.copy(raycaster.ray);
  35279. _ray.applyMatrix4(_mat);
  35280. if (_ray.intersectBox(boundingBox, _vec)) {
  35281. // account for tile scale
  35282. var invScale = void 0;
  35283. _vec2.setFromMatrixScale(_mat);
  35284. invScale = _vec2.x;
  35285. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  35286. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  35287. } // if we intersect the box save the distance to the tile bounds
  35288. var data = {
  35289. distance: Infinity,
  35290. tile: null
  35291. };
  35292. array.push(data);
  35293. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  35294. data.tile = tile;
  35295. } else {
  35296. continue;
  35297. }
  35298. }
  35299. } // sort them by ascending distance
  35300. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  35301. // couldn't possible include a best hit
  35302. var bestDistanceSquared = Infinity;
  35303. var bestHit = null;
  35304. for (var _i = 0, _l = array.length; _i < _l; _i++) {
  35305. var _data = array[_i];
  35306. var distanceSquared = _data.distance;
  35307. if (distanceSquared > bestDistanceSquared) {
  35308. break;
  35309. } else {
  35310. var _tile = _data.tile;
  35311. var scene = _tile.cached.scene;
  35312. var hit = null;
  35313. if (activeTiles.has(_tile)) {
  35314. // save the hit if it's closer
  35315. intersectTileScene(scene, raycaster, _hitArray);
  35316. if (_hitArray.length > 0) {
  35317. if (_hitArray.length > 1) {
  35318. _hitArray.sort(distanceSort);
  35319. }
  35320. hit = _hitArray[0];
  35321. }
  35322. } else {
  35323. hit = raycastTraverseFirstHit(_tile, group, activeTiles, raycaster);
  35324. }
  35325. if (hit) {
  35326. var hitDistanceSquared = hit.distance * hit.distance;
  35327. if (hitDistanceSquared < bestDistanceSquared) {
  35328. bestDistanceSquared = hitDistanceSquared;
  35329. bestHit = hit;
  35330. }
  35331. _hitArray.length = 0;
  35332. }
  35333. }
  35334. }
  35335. return bestHit;
  35336. }
  35337. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  35338. var cached = tile.cached;
  35339. var groupMatrixWorld = group.matrixWorld;
  35340. _mat.copy(groupMatrixWorld); // Early out if we don't hit this tile sphere
  35341. var sphere = cached.sphere;
  35342. if (sphere) {
  35343. _sphere.copy(sphere);
  35344. _sphere.applyMatrix4(_mat);
  35345. if (!raycaster.ray.intersectsSphere(_sphere)) {
  35346. return;
  35347. }
  35348. } // Early out if we don't this this tile box
  35349. var boundingBox = cached.box;
  35350. var obbMat = cached.boxTransform;
  35351. if (boundingBox) {
  35352. _mat.multiply(obbMat).invert();
  35353. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  35354. if (!_ray.intersectsBox(boundingBox)) {
  35355. return;
  35356. }
  35357. } // TODO: check region
  35358. var scene = cached.scene;
  35359. if (activeTiles.has(tile)) {
  35360. intersectTileScene(scene, raycaster, intersects);
  35361. return;
  35362. }
  35363. var children = tile.children;
  35364. for (var i = 0, l = children.length; i < l; i++) {
  35365. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  35366. }
  35367. }
  35368. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  35369. "use strict";
  35370. Object.defineProperty(exports, "__esModule", {
  35371. value: true
  35372. });
  35373. exports.TilesRenderer = void 0;
  35374. var _TilesRendererBase2 = require("../base/TilesRendererBase.js");
  35375. var _B3DMLoader = require("./B3DMLoader.js");
  35376. var _PNTSLoader = require("./PNTSLoader.js");
  35377. var _I3DMLoader = require("./I3DMLoader.js");
  35378. var _CMPTLoader = require("./CMPTLoader.js");
  35379. var _TilesGroup = require("./TilesGroup.js");
  35380. var _three = require("three");
  35381. var _raycastTraverse = require("./raycastTraverse.js");
  35382. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35383. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35384. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35385. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35386. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35387. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35388. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35389. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35390. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35391. function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); }
  35392. function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; }
  35393. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  35394. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35395. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35396. var INITIAL_FRUSTUM_CULLED = Symbol('INITIAL_FRUSTUM_CULLED');
  35397. var DEG2RAD = _three.Math.DEG2RAD;
  35398. var tempMat = new _three.Matrix4();
  35399. var tempMat2 = new _three.Matrix4();
  35400. var tempVector = new _three.Vector3();
  35401. var vecX = new _three.Vector3();
  35402. var vecY = new _three.Vector3();
  35403. var vecZ = new _three.Vector3();
  35404. var X_AXIS = new _three.Vector3(1, 0, 0);
  35405. var Y_AXIS = new _three.Vector3(0, 1, 0);
  35406. function emptyRaycast() {}
  35407. function updateFrustumCulled(object, toInitialValue) {
  35408. object.traverse(function (c) {
  35409. c.frustumCulled = c[INITIAL_FRUSTUM_CULLED] && toInitialValue;
  35410. });
  35411. }
  35412. var TilesRenderer =
  35413. /*#__PURE__*/
  35414. function (_TilesRendererBase) {
  35415. _inherits(TilesRenderer, _TilesRendererBase);
  35416. _createClass(TilesRenderer, [{
  35417. key: "autoDisableRendererCulling",
  35418. get: function get() {
  35419. return this._autoDisableRendererCulling;
  35420. },
  35421. set: function set(value) {
  35422. if (this._autoDisableRendererCulling !== value) {
  35423. _set(_getPrototypeOf(TilesRenderer.prototype), "_autoDisableRendererCulling", value, this, true);
  35424. this.traverse(function (tile) {
  35425. if (tile.scene) {
  35426. updateFrustumCulled(tile.scene, value);
  35427. }
  35428. });
  35429. }
  35430. }
  35431. }]);
  35432. function TilesRenderer() {
  35433. var _getPrototypeOf2;
  35434. var _this;
  35435. _classCallCheck(this, TilesRenderer);
  35436. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  35437. args[_key] = arguments[_key];
  35438. }
  35439. _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(TilesRenderer)).call.apply(_getPrototypeOf2, [this].concat(args)));
  35440. _this.group = new _TilesGroup.TilesGroup(_assertThisInitialized(_this));
  35441. _this.cameras = [];
  35442. _this.cameraMap = new Map();
  35443. _this.cameraInfo = [];
  35444. _this.activeTiles = new Set();
  35445. _this.visibleTiles = new Set();
  35446. _this._autoDisableRendererCulling = true;
  35447. _this.onLoadTileSet = null;
  35448. _this.onLoadModel = null;
  35449. _this.onDisposeModel = null;
  35450. _this.manager = new _three.LoadingManager();
  35451. return _this;
  35452. }
  35453. /* Public API */
  35454. _createClass(TilesRenderer, [{
  35455. key: "getBounds",
  35456. value: function getBounds(box) {
  35457. if (!this.root) {
  35458. return false;
  35459. }
  35460. var cached = this.root.cached;
  35461. var boundingBox = cached.box;
  35462. var obbMat = cached.boxTransform;
  35463. if (boundingBox) {
  35464. box.copy(boundingBox);
  35465. box.applyMatrix4(obbMat);
  35466. return true;
  35467. } else {
  35468. return false;
  35469. }
  35470. }
  35471. }, {
  35472. key: "forEachLoadedModel",
  35473. value: function forEachLoadedModel(callback) {
  35474. this.traverse(function (tile) {
  35475. var scene = tile.cached.scene;
  35476. if (scene) {
  35477. callback(scene, tile);
  35478. }
  35479. });
  35480. }
  35481. }, {
  35482. key: "raycast",
  35483. value: function raycast(raycaster, intersects) {
  35484. if (!this.root) {
  35485. return;
  35486. }
  35487. if (raycaster.firstHitOnly) {
  35488. var hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  35489. if (hit) {
  35490. intersects.push(hit);
  35491. }
  35492. } else {
  35493. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  35494. }
  35495. }
  35496. }, {
  35497. key: "hasCamera",
  35498. value: function hasCamera(camera) {
  35499. return this.cameraMap.has(camera);
  35500. }
  35501. }, {
  35502. key: "setCamera",
  35503. value: function setCamera(camera) {
  35504. var cameras = this.cameras;
  35505. var cameraMap = this.cameraMap;
  35506. if (!cameraMap.has(camera)) {
  35507. cameraMap.set(camera, new _three.Vector2());
  35508. cameras.push(camera);
  35509. return true;
  35510. }
  35511. return false;
  35512. }
  35513. }, {
  35514. key: "setResolution",
  35515. value: function setResolution(camera, xOrVec, y) {
  35516. var cameraMap = this.cameraMap;
  35517. if (!cameraMap.has(camera)) {
  35518. return false;
  35519. }
  35520. if (xOrVec instanceof _three.Vector2) {
  35521. cameraMap.get(camera).copy(xOrVec);
  35522. } else {
  35523. cameraMap.get(camera).set(xOrVec, y);
  35524. }
  35525. return true;
  35526. }
  35527. }, {
  35528. key: "setResolutionFromRenderer",
  35529. value: function setResolutionFromRenderer(camera, renderer) {
  35530. var cameraMap = this.cameraMap;
  35531. if (!cameraMap.has(camera)) {
  35532. return false;
  35533. }
  35534. var resolution = cameraMap.get(camera);
  35535. renderer.getSize(resolution);
  35536. resolution.multiplyScalar(renderer.getPixelRatio());
  35537. return true;
  35538. }
  35539. }, {
  35540. key: "deleteCamera",
  35541. value: function deleteCamera(camera) {
  35542. var cameras = this.cameras;
  35543. var cameraMap = this.cameraMap;
  35544. if (cameraMap.has(camera)) {
  35545. var index = cameras.indexOf(camera);
  35546. cameras.splice(index, 1);
  35547. cameraMap.delete(camera);
  35548. return true;
  35549. }
  35550. return false;
  35551. }
  35552. /* Overriden */
  35553. }, {
  35554. key: "fetchTileSet",
  35555. value: function fetchTileSet(url) {
  35556. var _get2,
  35557. _this2 = this;
  35558. for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  35559. rest[_key2 - 1] = arguments[_key2];
  35560. }
  35561. var pr = (_get2 = _get(_getPrototypeOf(TilesRenderer.prototype), "fetchTileSet", this)).call.apply(_get2, [this, url].concat(rest));
  35562. pr.then(function (json) {
  35563. if (_this2.onLoadTileSet) {
  35564. // Push this onto the end of the event stack to ensure this runs
  35565. // after the base renderer has placed the provided json where it
  35566. // needs to be placed and is ready for an update.
  35567. Promise.resolve().then(function () {
  35568. _this2.onLoadTileSet(json, url);
  35569. });
  35570. }
  35571. });
  35572. return pr;
  35573. }
  35574. }, {
  35575. key: "update",
  35576. value: function update() {
  35577. var group = this.group;
  35578. var cameras = this.cameras;
  35579. var cameraMap = this.cameraMap;
  35580. var cameraInfo = this.cameraInfo;
  35581. if (cameras.length === 0) {
  35582. console.warn('TilesRenderer: no cameras defined. Cannot update 3d tiles.');
  35583. return;
  35584. } // automatically scale the array of cameraInfo to match the cameras
  35585. while (cameraInfo.length > cameras.length) {
  35586. cameraInfo.pop();
  35587. }
  35588. while (cameraInfo.length < cameras.length) {
  35589. cameraInfo.push({
  35590. frustum: new _three.Frustum(),
  35591. sseDenominator: -1,
  35592. position: new _three.Vector3(),
  35593. invScale: -1,
  35594. pixelSize: 0
  35595. });
  35596. } // extract scale of group container
  35597. tempMat2.copy(group.matrixWorld).invert();
  35598. var invScale;
  35599. tempVector.setFromMatrixScale(tempMat2);
  35600. invScale = tempVector.x;
  35601. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  35602. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  35603. } // store the camera cameraInfo in the 3d tiles root frame
  35604. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  35605. var camera = cameras[i];
  35606. var info = cameraInfo[i];
  35607. var frustum = info.frustum;
  35608. var position = info.position;
  35609. var resolution = cameraMap.get(camera);
  35610. if (resolution.width === 0 || resolution.height === 0) {
  35611. console.warn('TilesRenderer: resolution for camera error calculation is not set.');
  35612. }
  35613. if (camera.isPerspectiveCamera) {
  35614. info.sseDenominator = 2 * Math.tan(0.5 * camera.fov * DEG2RAD) / resolution.height;
  35615. }
  35616. if (camera.isOrthographicCamera) {
  35617. var w = camera.right - camera.left;
  35618. var h = camera.top - camera.bottom;
  35619. info.pixelSize = Math.max(h / resolution.height, w / resolution.width);
  35620. }
  35621. info.invScale = invScale; // get frustum in grop root frame
  35622. tempMat.copy(group.matrixWorld);
  35623. tempMat.premultiply(camera.matrixWorldInverse);
  35624. tempMat.premultiply(camera.projectionMatrix);
  35625. frustum.setFromProjectionMatrix(tempMat); // get transform position in group root frame
  35626. position.set(0, 0, 0);
  35627. position.applyMatrix4(camera.matrixWorld);
  35628. position.applyMatrix4(tempMat2);
  35629. }
  35630. _get(_getPrototypeOf(TilesRenderer.prototype), "update", this).call(this);
  35631. }
  35632. }, {
  35633. key: "preprocessNode",
  35634. value: function preprocessNode(tile, parentTile, tileSetDir) {
  35635. _get(_getPrototypeOf(TilesRenderer.prototype), "preprocessNode", this).call(this, tile, parentTile, tileSetDir);
  35636. var transform = new _three.Matrix4();
  35637. if (tile.transform) {
  35638. var transformArr = tile.transform;
  35639. for (var i = 0; i < 16; i++) {
  35640. transform.elements[i] = transformArr[i];
  35641. }
  35642. } else {
  35643. transform.identity();
  35644. }
  35645. if (parentTile) {
  35646. transform.multiply(parentTile.cached.transform);
  35647. }
  35648. var box = null;
  35649. var boxTransform = null;
  35650. var boxTransformInverse = null;
  35651. if ('box' in tile.boundingVolume) {
  35652. var data = tile.boundingVolume.box;
  35653. box = new _three.Box3();
  35654. boxTransform = new _three.Matrix4();
  35655. boxTransformInverse = new _three.Matrix4(); // get the extents of the bounds in each axis
  35656. vecX.set(data[3], data[4], data[5]);
  35657. vecY.set(data[6], data[7], data[8]);
  35658. vecZ.set(data[9], data[10], data[11]);
  35659. var scaleX = vecX.length();
  35660. var scaleY = vecY.length();
  35661. var scaleZ = vecZ.length();
  35662. vecX.normalize();
  35663. vecY.normalize();
  35664. vecZ.normalize(); // create the oriented frame that the box exists in
  35665. boxTransform.set(vecX.x, vecY.x, vecZ.x, data[0], vecX.y, vecY.y, vecZ.y, data[1], vecX.z, vecY.z, vecZ.z, data[2], 0, 0, 0, 1);
  35666. boxTransform.premultiply(transform);
  35667. boxTransformInverse.copy(boxTransform).invert(); // scale the box by the extents
  35668. box.min.set(-scaleX, -scaleY, -scaleZ);
  35669. box.max.set(scaleX, scaleY, scaleZ);
  35670. }
  35671. var sphere = null;
  35672. if ('sphere' in tile.boundingVolume) {
  35673. var _data = tile.boundingVolume.sphere;
  35674. sphere = new _three.Sphere();
  35675. sphere.center.set(_data[0], _data[1], _data[2]);
  35676. sphere.radius = _data[3];
  35677. sphere.applyMatrix4(transform);
  35678. } else if ('box' in tile.boundingVolume) {
  35679. var _data2 = tile.boundingVolume.box;
  35680. sphere = new _three.Sphere();
  35681. box.getBoundingSphere(sphere);
  35682. sphere.center.set(_data2[0], _data2[1], _data2[2]);
  35683. sphere.applyMatrix4(transform);
  35684. }
  35685. var region = null;
  35686. if ('region' in tile.boundingVolume) {
  35687. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  35688. }
  35689. tile.cached = {
  35690. loadIndex: 0,
  35691. transform: transform,
  35692. active: false,
  35693. inFrustum: [],
  35694. box: box,
  35695. boxTransform: boxTransform,
  35696. boxTransformInverse: boxTransformInverse,
  35697. sphere: sphere,
  35698. region: region,
  35699. scene: null,
  35700. geometry: null,
  35701. material: null,
  35702. distance: Infinity
  35703. };
  35704. }
  35705. }, {
  35706. key: "parseTile",
  35707. value: function parseTile(buffer, tile, extension) {
  35708. var _this3 = this;
  35709. tile._loadIndex = tile._loadIndex || 0;
  35710. tile._loadIndex++;
  35711. var manager = this.manager;
  35712. var loadIndex = tile._loadIndex;
  35713. var promise = null;
  35714. switch (extension) {
  35715. case 'b3dm':
  35716. promise = new _B3DMLoader.B3DMLoader(manager).parse(buffer).then(function (res) {
  35717. return res.scene;
  35718. });
  35719. break;
  35720. case 'pnts':
  35721. promise = Promise.resolve(new _PNTSLoader.PNTSLoader(manager).parse(buffer).scene);
  35722. break;
  35723. case 'i3dm':
  35724. promise = new _I3DMLoader.I3DMLoader(manager).parse(buffer).then(function (res) {
  35725. return res.scene;
  35726. });
  35727. break;
  35728. case 'cmpt':
  35729. promise = new _CMPTLoader.CMPTLoader(manager).parse(buffer).then(function (res) {
  35730. return res.scene;
  35731. });
  35732. break;
  35733. default:
  35734. console.warn("TilesRenderer: Content type \"".concat(extension, "\" not supported."));
  35735. promise = Promise.resolve(null);
  35736. break;
  35737. }
  35738. return promise.then(function (scene) {
  35739. if (tile._loadIndex !== loadIndex) {
  35740. return;
  35741. }
  35742. var upAxis = _this3.rootTileSet.asset && _this3.rootTileSet.asset.gltfUpAxis || 'y';
  35743. var cached = tile.cached;
  35744. var cachedTransform = cached.transform;
  35745. switch (upAxis.toLowerCase()) {
  35746. case 'x':
  35747. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  35748. break;
  35749. case 'y':
  35750. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  35751. break;
  35752. case 'z':
  35753. break;
  35754. }
  35755. scene.matrix.premultiply(cachedTransform);
  35756. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  35757. scene.traverse(function (c) {
  35758. c[INITIAL_FRUSTUM_CULLED] = c.frustumCulled;
  35759. });
  35760. updateFrustumCulled(scene, _this3.autoDisableRendererCulling);
  35761. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  35762. scene.traverse(function (c) {
  35763. c.raycast = emptyRaycast;
  35764. });
  35765. var materials = [];
  35766. var geometry = [];
  35767. var textures = [];
  35768. scene.traverse(function (c) {
  35769. if (c.geometry) {
  35770. geometry.push(c.geometry);
  35771. }
  35772. if (c.material) {
  35773. var material = c.material;
  35774. materials.push(c.material);
  35775. for (var key in material) {
  35776. var value = material[key];
  35777. if (value && value.isTexture) {
  35778. textures.push(value);
  35779. }
  35780. }
  35781. }
  35782. });
  35783. cached.materials = materials;
  35784. cached.geometry = geometry;
  35785. cached.textures = textures;
  35786. if (_this3.onLoadModel) {
  35787. _this3.onLoadModel(scene, tile);
  35788. }
  35789. });
  35790. }
  35791. }, {
  35792. key: "disposeTile",
  35793. value: function disposeTile(tile) {
  35794. // This could get called before the tile has finished downloading
  35795. var cached = tile.cached;
  35796. if (cached.scene) {
  35797. var materials = cached.materials;
  35798. var geometry = cached.geometry;
  35799. var textures = cached.textures;
  35800. for (var i = 0, l = geometry.length; i < l; i++) {
  35801. geometry[i].dispose();
  35802. }
  35803. for (var _i = 0, _l = materials.length; _i < _l; _i++) {
  35804. materials[_i].dispose();
  35805. }
  35806. for (var _i2 = 0, _l2 = textures.length; _i2 < _l2; _i2++) {
  35807. var texture = textures[_i2];
  35808. texture.dispose();
  35809. }
  35810. if (this.onDisposeModel) {
  35811. this.onDisposeModel(cached.scene, tile);
  35812. }
  35813. cached.scene = null;
  35814. cached.materials = null;
  35815. cached.textures = null;
  35816. cached.geometry = null;
  35817. }
  35818. tile._loadIndex++;
  35819. }
  35820. }, {
  35821. key: "setTileVisible",
  35822. value: function setTileVisible(tile, visible) {
  35823. var scene = tile.cached.scene;
  35824. var visibleTiles = this.visibleTiles;
  35825. var group = this.group;
  35826. if (visible) {
  35827. group.add(scene);
  35828. visibleTiles.add(tile);
  35829. scene.updateMatrixWorld(true);
  35830. } else {
  35831. group.remove(scene);
  35832. visibleTiles.delete(tile);
  35833. }
  35834. }
  35835. }, {
  35836. key: "setTileActive",
  35837. value: function setTileActive(tile, active) {
  35838. var activeTiles = this.activeTiles;
  35839. if (active) {
  35840. activeTiles.add(tile);
  35841. } else {
  35842. activeTiles.delete(tile);
  35843. }
  35844. }
  35845. }, {
  35846. key: "calculateError",
  35847. value: function calculateError(tile) {
  35848. if (tile.geometricError === 0.0) {
  35849. return 0.0;
  35850. }
  35851. var cached = tile.cached;
  35852. var inFrustum = cached.inFrustum;
  35853. var cameras = this.cameras;
  35854. var cameraInfo = this.cameraInfo; // TODO: Use the content bounding volume here?
  35855. var boundingVolume = tile.boundingVolume;
  35856. if ('box' in boundingVolume) {
  35857. var boundingBox = cached.box;
  35858. var boxTransformInverse = cached.boxTransformInverse;
  35859. var maxError = -Infinity;
  35860. var minDistance = Infinity;
  35861. for (var i = 0, l = cameras.length; i < l; i++) {
  35862. if (!inFrustum[i]) {
  35863. continue;
  35864. } // transform camera position into local frame of the tile bounding box
  35865. var camera = cameras[i];
  35866. var info = cameraInfo[i];
  35867. var invScale = info.invScale;
  35868. tempVector.copy(info.position);
  35869. tempVector.applyMatrix4(boxTransformInverse);
  35870. var error = void 0;
  35871. if (camera.isOrthographicCamera) {
  35872. var pixelSize = info.pixelSize;
  35873. error = tile.geometricError / (pixelSize * invScale);
  35874. } else {
  35875. var distance = boundingBox.distanceToPoint(tempVector);
  35876. var scaledDistance = distance * invScale;
  35877. var sseDenominator = info.sseDenominator;
  35878. error = tile.geometricError / (scaledDistance * sseDenominator);
  35879. minDistance = Math.min(minDistance, scaledDistance);
  35880. }
  35881. maxError = Math.max(maxError, error);
  35882. }
  35883. tile.cached.distance = minDistance;
  35884. return maxError;
  35885. } else if ('sphere' in boundingVolume) {
  35886. // const sphere = cached.sphere;
  35887. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  35888. } else if ('region' in boundingVolume) {
  35889. // unsupported
  35890. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  35891. }
  35892. return Infinity;
  35893. }
  35894. }, {
  35895. key: "tileInView",
  35896. value: function tileInView(tile) {
  35897. // TODO: we should use the more precise bounding volumes here if possible
  35898. // cache the root-space planes
  35899. // Use separating axis theorem for frustum and obb
  35900. var cached = tile.cached;
  35901. var sphere = cached.sphere;
  35902. var inFrustum = cached.inFrustum;
  35903. if (sphere) {
  35904. var cameraInfo = this.cameraInfo;
  35905. var inView = false;
  35906. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  35907. // Track which camera frustums this tile is in so we can use it
  35908. // to ignore the error calculations for cameras that can't see it
  35909. var frustum = cameraInfo[i].frustum;
  35910. if (frustum.intersectsSphere(sphere)) {
  35911. inView = true;
  35912. inFrustum[i] = true;
  35913. } else {
  35914. inFrustum[i] = false;
  35915. }
  35916. }
  35917. return inView;
  35918. }
  35919. return true;
  35920. }
  35921. }]);
  35922. return TilesRenderer;
  35923. }(_TilesRendererBase2.TilesRendererBase);
  35924. exports.TilesRenderer = TilesRenderer;
  35925. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./PNTSLoader.js":"../src/three/PNTSLoader.js","./I3DMLoader.js":"../src/three/I3DMLoader.js","./CMPTLoader.js":"../src/three/CMPTLoader.js","./TilesGroup.js":"../src/three/TilesGroup.js","three":"../node_modules/three/build/three.module.js","./raycastTraverse.js":"../src/three/raycastTraverse.js"}],"../src/three/SphereHelper.js":[function(require,module,exports) {
  35926. "use strict";
  35927. Object.defineProperty(exports, "__esModule", {
  35928. value: true
  35929. });
  35930. exports.SphereHelper = void 0;
  35931. var _three = require("three");
  35932. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35933. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35934. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35935. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35936. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35937. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35938. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35939. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35940. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35941. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35942. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35943. var _vector = new _three.Vector3();
  35944. var axes = ['x', 'y', 'z'];
  35945. var SphereHelper =
  35946. /*#__PURE__*/
  35947. function (_LineSegments) {
  35948. _inherits(SphereHelper, _LineSegments);
  35949. function SphereHelper(sphere) {
  35950. var _this;
  35951. var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0xffff00;
  35952. var angleSteps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 40;
  35953. _classCallCheck(this, SphereHelper);
  35954. var geometry = new _three.BufferGeometry();
  35955. var positions = [];
  35956. for (var i = 0; i < 3; i++) {
  35957. var axis1 = axes[i];
  35958. var axis2 = axes[(i + 1) % 3];
  35959. _vector.set(0, 0, 0);
  35960. for (var a = 0; a < angleSteps; a++) {
  35961. var angle = void 0;
  35962. angle = 2 * Math.PI * a / (angleSteps - 1);
  35963. _vector[axis1] = Math.sin(angle);
  35964. _vector[axis2] = Math.cos(angle);
  35965. positions.push(_vector.x, _vector.y, _vector.z);
  35966. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  35967. _vector[axis1] = Math.sin(angle);
  35968. _vector[axis2] = Math.cos(angle);
  35969. positions.push(_vector.x, _vector.y, _vector.z);
  35970. }
  35971. }
  35972. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  35973. geometry.computeBoundingSphere();
  35974. _this = _possibleConstructorReturn(this, _getPrototypeOf(SphereHelper).call(this, geometry, new _three.LineBasicMaterial({
  35975. color: color,
  35976. toneMapped: false
  35977. })));
  35978. _this.sphere = sphere;
  35979. _this.type = 'SphereHelper';
  35980. return _this;
  35981. }
  35982. _createClass(SphereHelper, [{
  35983. key: "updateMatrixWorld",
  35984. value: function updateMatrixWorld(force) {
  35985. var sphere = this.sphere;
  35986. this.position.copy(sphere.center);
  35987. this.scale.setScalar(sphere.radius);
  35988. _get(_getPrototypeOf(SphereHelper.prototype), "updateMatrixWorld", this).call(this, force);
  35989. }
  35990. }]);
  35991. return SphereHelper;
  35992. }(_three.LineSegments);
  35993. exports.SphereHelper = SphereHelper;
  35994. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  35995. "use strict";
  35996. Object.defineProperty(exports, "__esModule", {
  35997. value: true
  35998. });
  35999. exports.DebugTilesRenderer = exports.RANDOM_COLOR = exports.IS_LEAF = exports.RELATIVE_DEPTH = exports.DEPTH = exports.DISTANCE = exports.GEOMETRIC_ERROR = exports.SCREEN_ERROR = exports.NONE = void 0;
  36000. var _three = require("three");
  36001. var _TilesRenderer2 = require("./TilesRenderer.js");
  36002. var _SphereHelper = require("./SphereHelper.js");
  36003. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  36004. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36005. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36006. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36007. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  36008. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  36009. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  36010. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  36011. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  36012. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  36013. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  36014. var ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  36015. var HAS_RANDOM_COLOR = Symbol('HAS_RANDOM_COLOR');
  36016. function emptyRaycast() {}
  36017. var NONE = 0;
  36018. exports.NONE = NONE;
  36019. var SCREEN_ERROR = 1;
  36020. exports.SCREEN_ERROR = SCREEN_ERROR;
  36021. var GEOMETRIC_ERROR = 2;
  36022. exports.GEOMETRIC_ERROR = GEOMETRIC_ERROR;
  36023. var DISTANCE = 3;
  36024. exports.DISTANCE = DISTANCE;
  36025. var DEPTH = 4;
  36026. exports.DEPTH = DEPTH;
  36027. var RELATIVE_DEPTH = 5;
  36028. exports.RELATIVE_DEPTH = RELATIVE_DEPTH;
  36029. var IS_LEAF = 6;
  36030. exports.IS_LEAF = IS_LEAF;
  36031. var RANDOM_COLOR = 7;
  36032. exports.RANDOM_COLOR = RANDOM_COLOR;
  36033. var DebugTilesRenderer =
  36034. /*#__PURE__*/
  36035. function (_TilesRenderer) {
  36036. _inherits(DebugTilesRenderer, _TilesRenderer);
  36037. function DebugTilesRenderer() {
  36038. var _getPrototypeOf2;
  36039. var _this;
  36040. _classCallCheck(this, DebugTilesRenderer);
  36041. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36042. args[_key] = arguments[_key];
  36043. }
  36044. _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(DebugTilesRenderer)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36045. var tilesGroup = _this.group;
  36046. var boxGroup = new _three.Group();
  36047. tilesGroup.add(boxGroup);
  36048. var sphereGroup = new _three.Group();
  36049. tilesGroup.add(sphereGroup);
  36050. _this.displayBoxBounds = false;
  36051. _this.displaySphereBounds = false;
  36052. _this.colorMode = NONE;
  36053. _this.boxGroup = boxGroup;
  36054. _this.sphereGroup = sphereGroup;
  36055. _this.maxDebugDepth = -1;
  36056. _this.maxDebugDistance = -1;
  36057. _this.maxDebugError = -1;
  36058. _this.extremeDebugDepth = -1;
  36059. _this.extremeDebugError = -1;
  36060. return _this;
  36061. }
  36062. _createClass(DebugTilesRenderer, [{
  36063. key: "initExtremes",
  36064. value: function initExtremes() {
  36065. // initialize the extreme values of the hierarchy
  36066. var maxDepth = -1;
  36067. this.traverse(function (tile) {
  36068. maxDepth = Math.max(maxDepth, tile.__depth);
  36069. });
  36070. var maxError = -1;
  36071. this.traverse(function (tile) {
  36072. maxError = Math.max(maxError, tile.geometricError);
  36073. });
  36074. this.extremeDebugDepth = maxDepth;
  36075. this.extremeDebugError = maxError;
  36076. }
  36077. }, {
  36078. key: "loadTileSet",
  36079. value: function loadTileSet() {
  36080. var _get2,
  36081. _this2 = this;
  36082. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  36083. args[_key2] = arguments[_key2];
  36084. }
  36085. var pr = (_get2 = _get(_getPrototypeOf(DebugTilesRenderer.prototype), "loadTileSet", this)).call.apply(_get2, [this].concat(args));
  36086. pr.then(function () {
  36087. return _this2.initExtremes();
  36088. }).catch(function () {// error is logged internally
  36089. });
  36090. return pr;
  36091. }
  36092. }, {
  36093. key: "getTileInformationFromActiveObject",
  36094. value: function getTileInformationFromActiveObject(object) {
  36095. // Find which tile this scene is associated with. This is slow and
  36096. // intended for debug purposes only.
  36097. var targetTile = null;
  36098. var activeTiles = this.activeTiles;
  36099. activeTiles.forEach(function (tile) {
  36100. if (targetTile) {
  36101. return true;
  36102. }
  36103. var scene = tile.cached.scene;
  36104. if (scene) {
  36105. scene.traverse(function (c) {
  36106. if (c === object) {
  36107. targetTile = tile;
  36108. }
  36109. });
  36110. }
  36111. });
  36112. if (targetTile) {
  36113. return {
  36114. distanceToCamera: targetTile.cached.distance,
  36115. geometricError: targetTile.geometricError,
  36116. screenSpaceError: targetTile.__error,
  36117. depth: targetTile.__depth,
  36118. isLeaf: targetTile.__isLeaf
  36119. };
  36120. } else {
  36121. return null;
  36122. }
  36123. }
  36124. }, {
  36125. key: "update",
  36126. value: function update() {
  36127. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "update", this).call(this);
  36128. if (!this.root) {
  36129. return;
  36130. } // set box or sphere visibility
  36131. this.boxGroup.visible = this.displayBoxBounds;
  36132. this.sphereGroup.visible = this.displaySphereBounds; // get max values to use for materials
  36133. var maxDepth = -1;
  36134. if (this.maxDebugDepth === -1) {
  36135. maxDepth = this.extremeDebugDepth;
  36136. } else {
  36137. maxDepth = this.maxDebugDepth;
  36138. }
  36139. var maxError = -1;
  36140. if (this.maxDebugError === -1) {
  36141. maxError = this.extremeDebugError;
  36142. } else {
  36143. maxError = this.maxDebugError;
  36144. }
  36145. var maxDistance = -1;
  36146. if (this.maxDebugDistance === -1) {
  36147. maxDistance = this.root.cached.sphere.radius;
  36148. } else {
  36149. maxDistance = this.maxDebugDistance;
  36150. }
  36151. var errorTarget = this.errorTarget;
  36152. var colorMode = this.colorMode;
  36153. var visibleTiles = this.visibleTiles;
  36154. visibleTiles.forEach(function (tile) {
  36155. var scene = tile.cached.scene; // create a random color per-tile
  36156. var h, s, l;
  36157. if (colorMode === RANDOM_COLOR) {
  36158. h = Math.random();
  36159. s = 0.5 + Math.random() * 0.5;
  36160. l = 0.375 + Math.random() * 0.25;
  36161. }
  36162. scene.traverse(function (c) {
  36163. var currMaterial = c.material;
  36164. if (currMaterial) {
  36165. // Reset the material if needed
  36166. var originalMaterial = c[ORIGINAL_MATERIAL];
  36167. if (colorMode === NONE && currMaterial !== originalMaterial) {
  36168. c.material.dispose();
  36169. c.material = c[ORIGINAL_MATERIAL];
  36170. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  36171. if (c.isPoints) {
  36172. var pointsMaterial = new _three.PointsMaterial();
  36173. pointsMaterial.size = originalMaterial.size;
  36174. pointsMaterial.sizeAttenuation = originalMaterial.sizeAttenuation;
  36175. c.material = pointsMaterial;
  36176. } else {
  36177. c.material = new _three.MeshBasicMaterial();
  36178. }
  36179. }
  36180. if (colorMode !== RANDOM_COLOR) {
  36181. delete c.material[HAS_RANDOM_COLOR];
  36182. } // Set the color on the basic material
  36183. switch (colorMode) {
  36184. case DEPTH:
  36185. {
  36186. var val = tile.__depth / maxDepth;
  36187. c.material.color.setRGB(val, val, val);
  36188. break;
  36189. }
  36190. case RELATIVE_DEPTH:
  36191. {
  36192. var _val = tile.__depthFromRenderedParent / maxDepth;
  36193. c.material.color.setRGB(_val, _val, _val);
  36194. break;
  36195. }
  36196. case SCREEN_ERROR:
  36197. {
  36198. var _val2 = tile.__error / errorTarget;
  36199. if (_val2 > 1.0) {
  36200. c.material.color.setRGB(1.0, 0.0, 0.0);
  36201. } else {
  36202. c.material.color.setRGB(_val2, _val2, _val2);
  36203. }
  36204. break;
  36205. }
  36206. case GEOMETRIC_ERROR:
  36207. {
  36208. var _val3 = Math.min(tile.geometricError / maxError, 1);
  36209. c.material.color.setRGB(_val3, _val3, _val3);
  36210. break;
  36211. }
  36212. case DISTANCE:
  36213. {
  36214. // We don't update the distance if the geometric error is 0.0 so
  36215. // it will always be black.
  36216. var _val4 = Math.min(tile.cached.distance / maxDistance, 1);
  36217. c.material.color.setRGB(_val4, _val4, _val4);
  36218. break;
  36219. }
  36220. case IS_LEAF:
  36221. {
  36222. if (!tile.children || tile.children.length === 0) {
  36223. c.material.color.set(0xffffff);
  36224. } else {
  36225. c.material.color.set(0);
  36226. }
  36227. break;
  36228. }
  36229. case RANDOM_COLOR:
  36230. {
  36231. if (!c.material[HAS_RANDOM_COLOR]) {
  36232. c.material.color.setHSL(h, s, l);
  36233. c.material[HAS_RANDOM_COLOR] = true;
  36234. }
  36235. break;
  36236. }
  36237. }
  36238. }
  36239. });
  36240. });
  36241. }
  36242. }, {
  36243. key: "setTileVisible",
  36244. value: function setTileVisible(tile, visible) {
  36245. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "setTileVisible", this).call(this, tile, visible);
  36246. var cached = tile.cached;
  36247. var sphereGroup = this.sphereGroup;
  36248. var boxGroup = this.boxGroup;
  36249. var boxHelperGroup = cached.boxHelperGroup;
  36250. var sphereHelper = cached.sphereHelper;
  36251. if (!visible) {
  36252. boxGroup.remove(boxHelperGroup);
  36253. sphereGroup.remove(sphereHelper);
  36254. } else {
  36255. boxGroup.add(boxHelperGroup);
  36256. boxHelperGroup.updateMatrixWorld(true);
  36257. sphereGroup.add(sphereHelper);
  36258. sphereHelper.updateMatrixWorld(true);
  36259. }
  36260. }
  36261. }, {
  36262. key: "parseTile",
  36263. value: function parseTile(buffer, tile, extension) {
  36264. var _this3 = this;
  36265. return _get(_getPrototypeOf(DebugTilesRenderer.prototype), "parseTile", this).call(this, buffer, tile, extension).then(function () {
  36266. var cached = tile.cached;
  36267. var scene = cached.scene;
  36268. if (scene) {
  36269. var cachedBox = cached.box;
  36270. var cachedBoxMat = cached.boxTransform; // Create debug bounding box
  36271. var boxHelperGroup = new _three.Group();
  36272. boxHelperGroup.matrix.copy(cachedBoxMat);
  36273. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  36274. var boxHelper = new _three.Box3Helper(cachedBox);
  36275. boxHelper.raycast = emptyRaycast;
  36276. boxHelperGroup.add(boxHelper);
  36277. cached.boxHelperGroup = boxHelperGroup;
  36278. if (_this3.visibleTiles.has(tile) && _this3.displayBoxBounds) {
  36279. _this3.boxGroup.add(boxHelperGroup);
  36280. boxHelperGroup.updateMatrixWorld(true);
  36281. } // Create debugbounding sphere
  36282. var cachedSphere = cached.sphere;
  36283. var sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  36284. sphereHelper.raycast = emptyRaycast;
  36285. cached.sphereHelper = sphereHelper;
  36286. if (_this3.visibleTiles.has(tile) && _this3.displaySphereBounds) {
  36287. _this3.sphereGroup.add(sphereHelper);
  36288. sphereHelper.updateMatrixWorld(true);
  36289. } // Cache the original materials
  36290. scene.traverse(function (c) {
  36291. var material = c.material;
  36292. if (material) {
  36293. c[ORIGINAL_MATERIAL] = material;
  36294. }
  36295. });
  36296. }
  36297. });
  36298. }
  36299. }, {
  36300. key: "disposeTile",
  36301. value: function disposeTile(tile) {
  36302. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "disposeTile", this).call(this, tile);
  36303. var cached = tile.cached;
  36304. if (cached.boxHelperGroup) {
  36305. cached.boxHelperGroup.children[0].geometry.dispose();
  36306. cached.sphereHelper.geometry.dispose();
  36307. delete cached.boxHelperGroup;
  36308. delete cached.sphereHelper;
  36309. }
  36310. }
  36311. }]);
  36312. return DebugTilesRenderer;
  36313. }(_TilesRenderer2.TilesRenderer);
  36314. exports.DebugTilesRenderer = DebugTilesRenderer;
  36315. },{"three":"../node_modules/three/build/three.module.js","./TilesRenderer.js":"../src/three/TilesRenderer.js","./SphereHelper.js":"../src/three/SphereHelper.js"}],"../src/index.js":[function(require,module,exports) {
  36316. "use strict";
  36317. Object.defineProperty(exports, "__esModule", {
  36318. value: true
  36319. });
  36320. Object.defineProperty(exports, "DebugTilesRenderer", {
  36321. enumerable: true,
  36322. get: function () {
  36323. return _DebugTilesRenderer.DebugTilesRenderer;
  36324. }
  36325. });
  36326. Object.defineProperty(exports, "NONE", {
  36327. enumerable: true,
  36328. get: function () {
  36329. return _DebugTilesRenderer.NONE;
  36330. }
  36331. });
  36332. Object.defineProperty(exports, "SCREEN_ERROR", {
  36333. enumerable: true,
  36334. get: function () {
  36335. return _DebugTilesRenderer.SCREEN_ERROR;
  36336. }
  36337. });
  36338. Object.defineProperty(exports, "GEOMETRIC_ERROR", {
  36339. enumerable: true,
  36340. get: function () {
  36341. return _DebugTilesRenderer.GEOMETRIC_ERROR;
  36342. }
  36343. });
  36344. Object.defineProperty(exports, "DISTANCE", {
  36345. enumerable: true,
  36346. get: function () {
  36347. return _DebugTilesRenderer.DISTANCE;
  36348. }
  36349. });
  36350. Object.defineProperty(exports, "DEPTH", {
  36351. enumerable: true,
  36352. get: function () {
  36353. return _DebugTilesRenderer.DEPTH;
  36354. }
  36355. });
  36356. Object.defineProperty(exports, "RELATIVE_DEPTH", {
  36357. enumerable: true,
  36358. get: function () {
  36359. return _DebugTilesRenderer.RELATIVE_DEPTH;
  36360. }
  36361. });
  36362. Object.defineProperty(exports, "IS_LEAF", {
  36363. enumerable: true,
  36364. get: function () {
  36365. return _DebugTilesRenderer.IS_LEAF;
  36366. }
  36367. });
  36368. Object.defineProperty(exports, "RANDOM_COLOR", {
  36369. enumerable: true,
  36370. get: function () {
  36371. return _DebugTilesRenderer.RANDOM_COLOR;
  36372. }
  36373. });
  36374. Object.defineProperty(exports, "TilesRenderer", {
  36375. enumerable: true,
  36376. get: function () {
  36377. return _TilesRenderer.TilesRenderer;
  36378. }
  36379. });
  36380. Object.defineProperty(exports, "B3DMLoader", {
  36381. enumerable: true,
  36382. get: function () {
  36383. return _B3DMLoader.B3DMLoader;
  36384. }
  36385. });
  36386. Object.defineProperty(exports, "PNTSLoader", {
  36387. enumerable: true,
  36388. get: function () {
  36389. return _PNTSLoader.PNTSLoader;
  36390. }
  36391. });
  36392. Object.defineProperty(exports, "I3DMLoader", {
  36393. enumerable: true,
  36394. get: function () {
  36395. return _I3DMLoader.I3DMLoader;
  36396. }
  36397. });
  36398. Object.defineProperty(exports, "CMPTLoader", {
  36399. enumerable: true,
  36400. get: function () {
  36401. return _CMPTLoader.CMPTLoader;
  36402. }
  36403. });
  36404. Object.defineProperty(exports, "TilesRendererBase", {
  36405. enumerable: true,
  36406. get: function () {
  36407. return _TilesRendererBase.TilesRendererBase;
  36408. }
  36409. });
  36410. Object.defineProperty(exports, "B3DMLoaderBase", {
  36411. enumerable: true,
  36412. get: function () {
  36413. return _B3DMLoaderBase.B3DMLoaderBase;
  36414. }
  36415. });
  36416. Object.defineProperty(exports, "I3DMLoaderBase", {
  36417. enumerable: true,
  36418. get: function () {
  36419. return _I3DMLoaderBase.I3DMLoaderBase;
  36420. }
  36421. });
  36422. Object.defineProperty(exports, "PNTSLoaderBase", {
  36423. enumerable: true,
  36424. get: function () {
  36425. return _PNTSLoaderBase.PNTSLoaderBase;
  36426. }
  36427. });
  36428. Object.defineProperty(exports, "CMPTLoaderBase", {
  36429. enumerable: true,
  36430. get: function () {
  36431. return _CMPTLoaderBase.CMPTLoaderBase;
  36432. }
  36433. });
  36434. Object.defineProperty(exports, "LRUCache", {
  36435. enumerable: true,
  36436. get: function () {
  36437. return _LRUCache.LRUCache;
  36438. }
  36439. });
  36440. Object.defineProperty(exports, "PriorityQueue", {
  36441. enumerable: true,
  36442. get: function () {
  36443. return _PriorityQueue.PriorityQueue;
  36444. }
  36445. });
  36446. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  36447. var _TilesRenderer = require("./three/TilesRenderer.js");
  36448. var _B3DMLoader = require("./three/B3DMLoader.js");
  36449. var _PNTSLoader = require("./three/PNTSLoader.js");
  36450. var _I3DMLoader = require("./three/I3DMLoader.js");
  36451. var _CMPTLoader = require("./three/CMPTLoader.js");
  36452. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  36453. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  36454. var _I3DMLoaderBase = require("./base/I3DMLoaderBase.js");
  36455. var _PNTSLoaderBase = require("./base/PNTSLoaderBase.js");
  36456. var _CMPTLoaderBase = require("./base/CMPTLoaderBase.js");
  36457. var _LRUCache = require("./utilities/LRUCache.js");
  36458. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  36459. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./three/PNTSLoader.js":"../src/three/PNTSLoader.js","./three/I3DMLoader.js":"../src/three/I3DMLoader.js","./three/CMPTLoader.js":"../src/three/CMPTLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./base/I3DMLoaderBase.js":"../src/base/I3DMLoaderBase.js","./base/PNTSLoaderBase.js":"../src/base/PNTSLoaderBase.js","./base/CMPTLoaderBase.js":"../src/base/CMPTLoaderBase.js","./utilities/LRUCache.js":"../src/utilities/LRUCache.js","./utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  36460. "use strict";
  36461. Object.defineProperty(exports, "__esModule", {
  36462. value: true
  36463. });
  36464. exports.MapControls = exports.OrbitControls = void 0;
  36465. var _threeModule = require("../../../build/three.module.js");
  36466. // This set of controls performs orbiting, dollying (zooming), and panning.
  36467. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  36468. //
  36469. // Orbit - left mouse / touch: one-finger move
  36470. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  36471. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  36472. var OrbitControls = function (object, domElement) {
  36473. if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
  36474. if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
  36475. this.object = object;
  36476. this.domElement = domElement; // Set to false to disable this control
  36477. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  36478. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  36479. this.minDistance = 0;
  36480. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  36481. this.minZoom = 0;
  36482. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  36483. // Range is 0 to Math.PI radians.
  36484. this.minPolarAngle = 0; // radians
  36485. this.maxPolarAngle = Math.PI; // radians
  36486. // How far you can orbit horizontally, upper and lower limits.
  36487. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  36488. this.minAzimuthAngle = -Infinity; // radians
  36489. this.maxAzimuthAngle = Infinity; // radians
  36490. // Set to true to enable damping (inertia)
  36491. // If damping is enabled, you must call controls.update() in your animation loop
  36492. this.enableDamping = false;
  36493. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  36494. // Set to false to disable zooming
  36495. this.enableZoom = true;
  36496. this.zoomSpeed = 1.0; // Set to false to disable rotating
  36497. this.enableRotate = true;
  36498. this.rotateSpeed = 1.0; // Set to false to disable panning
  36499. this.enablePan = true;
  36500. this.panSpeed = 1.0;
  36501. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  36502. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  36503. // Set to true to automatically rotate around the target
  36504. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  36505. this.autoRotate = false;
  36506. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  36507. // Set to false to disable use of the keys
  36508. this.enableKeys = true; // The four arrow keys
  36509. this.keys = {
  36510. LEFT: 37,
  36511. UP: 38,
  36512. RIGHT: 39,
  36513. BOTTOM: 40
  36514. }; // Mouse buttons
  36515. this.mouseButtons = {
  36516. LEFT: _threeModule.MOUSE.ROTATE,
  36517. MIDDLE: _threeModule.MOUSE.DOLLY,
  36518. RIGHT: _threeModule.MOUSE.PAN
  36519. }; // Touch fingers
  36520. this.touches = {
  36521. ONE: _threeModule.TOUCH.ROTATE,
  36522. TWO: _threeModule.TOUCH.DOLLY_PAN
  36523. }; // for reset
  36524. this.target0 = this.target.clone();
  36525. this.position0 = this.object.position.clone();
  36526. this.zoom0 = this.object.zoom; //
  36527. // public methods
  36528. //
  36529. this.getPolarAngle = function () {
  36530. return spherical.phi;
  36531. };
  36532. this.getAzimuthalAngle = function () {
  36533. return spherical.theta;
  36534. };
  36535. this.saveState = function () {
  36536. scope.target0.copy(scope.target);
  36537. scope.position0.copy(scope.object.position);
  36538. scope.zoom0 = scope.object.zoom;
  36539. };
  36540. this.reset = function () {
  36541. scope.target.copy(scope.target0);
  36542. scope.object.position.copy(scope.position0);
  36543. scope.object.zoom = scope.zoom0;
  36544. scope.object.updateProjectionMatrix();
  36545. scope.dispatchEvent(changeEvent);
  36546. scope.update();
  36547. state = STATE.NONE;
  36548. }; // this method is exposed, but perhaps it would be better if we can make it private...
  36549. this.update = function () {
  36550. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  36551. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  36552. var quatInverse = quat.clone().invert();
  36553. var lastPosition = new _threeModule.Vector3();
  36554. var lastQuaternion = new _threeModule.Quaternion();
  36555. var twoPI = 2 * Math.PI;
  36556. return function update() {
  36557. var position = scope.object.position;
  36558. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  36559. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  36560. spherical.setFromVector3(offset);
  36561. if (scope.autoRotate && state === STATE.NONE) {
  36562. rotateLeft(getAutoRotationAngle());
  36563. }
  36564. if (scope.enableDamping) {
  36565. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  36566. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  36567. } else {
  36568. spherical.theta += sphericalDelta.theta;
  36569. spherical.phi += sphericalDelta.phi;
  36570. } // restrict theta to be between desired limits
  36571. var min = scope.minAzimuthAngle;
  36572. var max = scope.maxAzimuthAngle;
  36573. if (isFinite(min) && isFinite(max)) {
  36574. if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI;
  36575. if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI;
  36576. if (min <= max) {
  36577. spherical.theta = Math.max(min, Math.min(max, spherical.theta));
  36578. } else {
  36579. spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
  36580. }
  36581. } // restrict phi to be between desired limits
  36582. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  36583. spherical.makeSafe();
  36584. spherical.radius *= scale; // restrict radius to be between desired limits
  36585. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  36586. if (scope.enableDamping === true) {
  36587. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  36588. } else {
  36589. scope.target.add(panOffset);
  36590. }
  36591. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  36592. offset.applyQuaternion(quatInverse);
  36593. position.copy(scope.target).add(offset);
  36594. scope.object.lookAt(scope.target);
  36595. if (scope.enableDamping === true) {
  36596. sphericalDelta.theta *= 1 - scope.dampingFactor;
  36597. sphericalDelta.phi *= 1 - scope.dampingFactor;
  36598. panOffset.multiplyScalar(1 - scope.dampingFactor);
  36599. } else {
  36600. sphericalDelta.set(0, 0, 0);
  36601. panOffset.set(0, 0, 0);
  36602. }
  36603. scale = 1; // update condition is:
  36604. // min(camera displacement, camera rotation in radians)^2 > EPS
  36605. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  36606. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  36607. scope.dispatchEvent(changeEvent);
  36608. lastPosition.copy(scope.object.position);
  36609. lastQuaternion.copy(scope.object.quaternion);
  36610. zoomChanged = false;
  36611. return true;
  36612. }
  36613. return false;
  36614. };
  36615. }();
  36616. this.dispose = function () {
  36617. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  36618. scope.domElement.removeEventListener('pointerdown', onPointerDown, false);
  36619. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  36620. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  36621. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  36622. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  36623. scope.domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, false);
  36624. scope.domElement.ownerDocument.removeEventListener('pointerup', onPointerUp, false);
  36625. scope.domElement.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  36626. }; //
  36627. // internals
  36628. //
  36629. var scope = this;
  36630. var changeEvent = {
  36631. type: 'change'
  36632. };
  36633. var startEvent = {
  36634. type: 'start'
  36635. };
  36636. var endEvent = {
  36637. type: 'end'
  36638. };
  36639. var STATE = {
  36640. NONE: -1,
  36641. ROTATE: 0,
  36642. DOLLY: 1,
  36643. PAN: 2,
  36644. TOUCH_ROTATE: 3,
  36645. TOUCH_PAN: 4,
  36646. TOUCH_DOLLY_PAN: 5,
  36647. TOUCH_DOLLY_ROTATE: 6
  36648. };
  36649. var state = STATE.NONE;
  36650. var EPS = 0.000001; // current position in spherical coordinates
  36651. var spherical = new _threeModule.Spherical();
  36652. var sphericalDelta = new _threeModule.Spherical();
  36653. var scale = 1;
  36654. var panOffset = new _threeModule.Vector3();
  36655. var zoomChanged = false;
  36656. var rotateStart = new _threeModule.Vector2();
  36657. var rotateEnd = new _threeModule.Vector2();
  36658. var rotateDelta = new _threeModule.Vector2();
  36659. var panStart = new _threeModule.Vector2();
  36660. var panEnd = new _threeModule.Vector2();
  36661. var panDelta = new _threeModule.Vector2();
  36662. var dollyStart = new _threeModule.Vector2();
  36663. var dollyEnd = new _threeModule.Vector2();
  36664. var dollyDelta = new _threeModule.Vector2();
  36665. function getAutoRotationAngle() {
  36666. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  36667. }
  36668. function getZoomScale() {
  36669. return Math.pow(0.95, scope.zoomSpeed);
  36670. }
  36671. function rotateLeft(angle) {
  36672. sphericalDelta.theta -= angle;
  36673. }
  36674. function rotateUp(angle) {
  36675. sphericalDelta.phi -= angle;
  36676. }
  36677. var panLeft = function () {
  36678. var v = new _threeModule.Vector3();
  36679. return function panLeft(distance, objectMatrix) {
  36680. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  36681. v.multiplyScalar(-distance);
  36682. panOffset.add(v);
  36683. };
  36684. }();
  36685. var panUp = function () {
  36686. var v = new _threeModule.Vector3();
  36687. return function panUp(distance, objectMatrix) {
  36688. if (scope.screenSpacePanning === true) {
  36689. v.setFromMatrixColumn(objectMatrix, 1);
  36690. } else {
  36691. v.setFromMatrixColumn(objectMatrix, 0);
  36692. v.crossVectors(scope.object.up, v);
  36693. }
  36694. v.multiplyScalar(distance);
  36695. panOffset.add(v);
  36696. };
  36697. }(); // deltaX and deltaY are in pixels; right and down are positive
  36698. var pan = function () {
  36699. var offset = new _threeModule.Vector3();
  36700. return function pan(deltaX, deltaY) {
  36701. var element = scope.domElement;
  36702. if (scope.object.isPerspectiveCamera) {
  36703. // perspective
  36704. var position = scope.object.position;
  36705. offset.copy(position).sub(scope.target);
  36706. var targetDistance = offset.length(); // half of the fov is center to top of screen
  36707. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  36708. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  36709. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  36710. } else if (scope.object.isOrthographicCamera) {
  36711. // orthographic
  36712. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  36713. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  36714. } else {
  36715. // camera neither orthographic nor perspective
  36716. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  36717. scope.enablePan = false;
  36718. }
  36719. };
  36720. }();
  36721. function dollyOut(dollyScale) {
  36722. if (scope.object.isPerspectiveCamera) {
  36723. scale /= dollyScale;
  36724. } else if (scope.object.isOrthographicCamera) {
  36725. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  36726. scope.object.updateProjectionMatrix();
  36727. zoomChanged = true;
  36728. } else {
  36729. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  36730. scope.enableZoom = false;
  36731. }
  36732. }
  36733. function dollyIn(dollyScale) {
  36734. if (scope.object.isPerspectiveCamera) {
  36735. scale *= dollyScale;
  36736. } else if (scope.object.isOrthographicCamera) {
  36737. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  36738. scope.object.updateProjectionMatrix();
  36739. zoomChanged = true;
  36740. } else {
  36741. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  36742. scope.enableZoom = false;
  36743. }
  36744. } //
  36745. // event callbacks - update the object state
  36746. //
  36747. function handleMouseDownRotate(event) {
  36748. rotateStart.set(event.clientX, event.clientY);
  36749. }
  36750. function handleMouseDownDolly(event) {
  36751. dollyStart.set(event.clientX, event.clientY);
  36752. }
  36753. function handleMouseDownPan(event) {
  36754. panStart.set(event.clientX, event.clientY);
  36755. }
  36756. function handleMouseMoveRotate(event) {
  36757. rotateEnd.set(event.clientX, event.clientY);
  36758. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  36759. var element = scope.domElement;
  36760. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  36761. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  36762. rotateStart.copy(rotateEnd);
  36763. scope.update();
  36764. }
  36765. function handleMouseMoveDolly(event) {
  36766. dollyEnd.set(event.clientX, event.clientY);
  36767. dollyDelta.subVectors(dollyEnd, dollyStart);
  36768. if (dollyDelta.y > 0) {
  36769. dollyOut(getZoomScale());
  36770. } else if (dollyDelta.y < 0) {
  36771. dollyIn(getZoomScale());
  36772. }
  36773. dollyStart.copy(dollyEnd);
  36774. scope.update();
  36775. }
  36776. function handleMouseMovePan(event) {
  36777. panEnd.set(event.clientX, event.clientY);
  36778. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  36779. pan(panDelta.x, panDelta.y);
  36780. panStart.copy(panEnd);
  36781. scope.update();
  36782. }
  36783. function handleMouseUp()
  36784. /*event*/
  36785. {// no-op
  36786. }
  36787. function handleMouseWheel(event) {
  36788. if (event.deltaY < 0) {
  36789. dollyIn(getZoomScale());
  36790. } else if (event.deltaY > 0) {
  36791. dollyOut(getZoomScale());
  36792. }
  36793. scope.update();
  36794. }
  36795. function handleKeyDown(event) {
  36796. var needsUpdate = false;
  36797. switch (event.keyCode) {
  36798. case scope.keys.UP:
  36799. pan(0, scope.keyPanSpeed);
  36800. needsUpdate = true;
  36801. break;
  36802. case scope.keys.BOTTOM:
  36803. pan(0, -scope.keyPanSpeed);
  36804. needsUpdate = true;
  36805. break;
  36806. case scope.keys.LEFT:
  36807. pan(scope.keyPanSpeed, 0);
  36808. needsUpdate = true;
  36809. break;
  36810. case scope.keys.RIGHT:
  36811. pan(-scope.keyPanSpeed, 0);
  36812. needsUpdate = true;
  36813. break;
  36814. }
  36815. if (needsUpdate) {
  36816. // prevent the browser from scrolling on cursor keys
  36817. event.preventDefault();
  36818. scope.update();
  36819. }
  36820. }
  36821. function handleTouchStartRotate(event) {
  36822. if (event.touches.length == 1) {
  36823. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  36824. } else {
  36825. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36826. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36827. rotateStart.set(x, y);
  36828. }
  36829. }
  36830. function handleTouchStartPan(event) {
  36831. if (event.touches.length == 1) {
  36832. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  36833. } else {
  36834. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36835. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36836. panStart.set(x, y);
  36837. }
  36838. }
  36839. function handleTouchStartDolly(event) {
  36840. var dx = event.touches[0].pageX - event.touches[1].pageX;
  36841. var dy = event.touches[0].pageY - event.touches[1].pageY;
  36842. var distance = Math.sqrt(dx * dx + dy * dy);
  36843. dollyStart.set(0, distance);
  36844. }
  36845. function handleTouchStartDollyPan(event) {
  36846. if (scope.enableZoom) handleTouchStartDolly(event);
  36847. if (scope.enablePan) handleTouchStartPan(event);
  36848. }
  36849. function handleTouchStartDollyRotate(event) {
  36850. if (scope.enableZoom) handleTouchStartDolly(event);
  36851. if (scope.enableRotate) handleTouchStartRotate(event);
  36852. }
  36853. function handleTouchMoveRotate(event) {
  36854. if (event.touches.length == 1) {
  36855. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  36856. } else {
  36857. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36858. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36859. rotateEnd.set(x, y);
  36860. }
  36861. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  36862. var element = scope.domElement;
  36863. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  36864. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  36865. rotateStart.copy(rotateEnd);
  36866. }
  36867. function handleTouchMovePan(event) {
  36868. if (event.touches.length == 1) {
  36869. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  36870. } else {
  36871. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36872. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36873. panEnd.set(x, y);
  36874. }
  36875. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  36876. pan(panDelta.x, panDelta.y);
  36877. panStart.copy(panEnd);
  36878. }
  36879. function handleTouchMoveDolly(event) {
  36880. var dx = event.touches[0].pageX - event.touches[1].pageX;
  36881. var dy = event.touches[0].pageY - event.touches[1].pageY;
  36882. var distance = Math.sqrt(dx * dx + dy * dy);
  36883. dollyEnd.set(0, distance);
  36884. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  36885. dollyOut(dollyDelta.y);
  36886. dollyStart.copy(dollyEnd);
  36887. }
  36888. function handleTouchMoveDollyPan(event) {
  36889. if (scope.enableZoom) handleTouchMoveDolly(event);
  36890. if (scope.enablePan) handleTouchMovePan(event);
  36891. }
  36892. function handleTouchMoveDollyRotate(event) {
  36893. if (scope.enableZoom) handleTouchMoveDolly(event);
  36894. if (scope.enableRotate) handleTouchMoveRotate(event);
  36895. }
  36896. function handleTouchEnd()
  36897. /*event*/
  36898. {} // no-op
  36899. //
  36900. // event handlers - FSM: listen for events and reset state
  36901. //
  36902. function onPointerDown(event) {
  36903. if (scope.enabled === false) return;
  36904. switch (event.pointerType) {
  36905. case 'mouse':
  36906. case 'pen':
  36907. onMouseDown(event);
  36908. break;
  36909. // TODO touch
  36910. }
  36911. }
  36912. function onPointerMove(event) {
  36913. if (scope.enabled === false) return;
  36914. switch (event.pointerType) {
  36915. case 'mouse':
  36916. case 'pen':
  36917. onMouseMove(event);
  36918. break;
  36919. // TODO touch
  36920. }
  36921. }
  36922. function onPointerUp(event) {
  36923. switch (event.pointerType) {
  36924. case 'mouse':
  36925. case 'pen':
  36926. onMouseUp(event);
  36927. break;
  36928. // TODO touch
  36929. }
  36930. }
  36931. function onMouseDown(event) {
  36932. // Prevent the browser from scrolling.
  36933. event.preventDefault(); // Manually set the focus since calling preventDefault above
  36934. // prevents the browser from setting it automatically.
  36935. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  36936. var mouseAction;
  36937. switch (event.button) {
  36938. case 0:
  36939. mouseAction = scope.mouseButtons.LEFT;
  36940. break;
  36941. case 1:
  36942. mouseAction = scope.mouseButtons.MIDDLE;
  36943. break;
  36944. case 2:
  36945. mouseAction = scope.mouseButtons.RIGHT;
  36946. break;
  36947. default:
  36948. mouseAction = -1;
  36949. }
  36950. switch (mouseAction) {
  36951. case _threeModule.MOUSE.DOLLY:
  36952. if (scope.enableZoom === false) return;
  36953. handleMouseDownDolly(event);
  36954. state = STATE.DOLLY;
  36955. break;
  36956. case _threeModule.MOUSE.ROTATE:
  36957. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  36958. if (scope.enablePan === false) return;
  36959. handleMouseDownPan(event);
  36960. state = STATE.PAN;
  36961. } else {
  36962. if (scope.enableRotate === false) return;
  36963. handleMouseDownRotate(event);
  36964. state = STATE.ROTATE;
  36965. }
  36966. break;
  36967. case _threeModule.MOUSE.PAN:
  36968. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  36969. if (scope.enableRotate === false) return;
  36970. handleMouseDownRotate(event);
  36971. state = STATE.ROTATE;
  36972. } else {
  36973. if (scope.enablePan === false) return;
  36974. handleMouseDownPan(event);
  36975. state = STATE.PAN;
  36976. }
  36977. break;
  36978. default:
  36979. state = STATE.NONE;
  36980. }
  36981. if (state !== STATE.NONE) {
  36982. scope.domElement.ownerDocument.addEventListener('pointermove', onPointerMove, false);
  36983. scope.domElement.ownerDocument.addEventListener('pointerup', onPointerUp, false);
  36984. scope.dispatchEvent(startEvent);
  36985. }
  36986. }
  36987. function onMouseMove(event) {
  36988. if (scope.enabled === false) return;
  36989. event.preventDefault();
  36990. switch (state) {
  36991. case STATE.ROTATE:
  36992. if (scope.enableRotate === false) return;
  36993. handleMouseMoveRotate(event);
  36994. break;
  36995. case STATE.DOLLY:
  36996. if (scope.enableZoom === false) return;
  36997. handleMouseMoveDolly(event);
  36998. break;
  36999. case STATE.PAN:
  37000. if (scope.enablePan === false) return;
  37001. handleMouseMovePan(event);
  37002. break;
  37003. }
  37004. }
  37005. function onMouseUp(event) {
  37006. scope.domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, false);
  37007. scope.domElement.ownerDocument.removeEventListener('pointerup', onPointerUp, false);
  37008. if (scope.enabled === false) return;
  37009. handleMouseUp(event);
  37010. scope.dispatchEvent(endEvent);
  37011. state = STATE.NONE;
  37012. }
  37013. function onMouseWheel(event) {
  37014. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  37015. event.preventDefault();
  37016. event.stopPropagation();
  37017. scope.dispatchEvent(startEvent);
  37018. handleMouseWheel(event);
  37019. scope.dispatchEvent(endEvent);
  37020. }
  37021. function onKeyDown(event) {
  37022. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  37023. handleKeyDown(event);
  37024. }
  37025. function onTouchStart(event) {
  37026. if (scope.enabled === false) return;
  37027. event.preventDefault(); // prevent scrolling
  37028. switch (event.touches.length) {
  37029. case 1:
  37030. switch (scope.touches.ONE) {
  37031. case _threeModule.TOUCH.ROTATE:
  37032. if (scope.enableRotate === false) return;
  37033. handleTouchStartRotate(event);
  37034. state = STATE.TOUCH_ROTATE;
  37035. break;
  37036. case _threeModule.TOUCH.PAN:
  37037. if (scope.enablePan === false) return;
  37038. handleTouchStartPan(event);
  37039. state = STATE.TOUCH_PAN;
  37040. break;
  37041. default:
  37042. state = STATE.NONE;
  37043. }
  37044. break;
  37045. case 2:
  37046. switch (scope.touches.TWO) {
  37047. case _threeModule.TOUCH.DOLLY_PAN:
  37048. if (scope.enableZoom === false && scope.enablePan === false) return;
  37049. handleTouchStartDollyPan(event);
  37050. state = STATE.TOUCH_DOLLY_PAN;
  37051. break;
  37052. case _threeModule.TOUCH.DOLLY_ROTATE:
  37053. if (scope.enableZoom === false && scope.enableRotate === false) return;
  37054. handleTouchStartDollyRotate(event);
  37055. state = STATE.TOUCH_DOLLY_ROTATE;
  37056. break;
  37057. default:
  37058. state = STATE.NONE;
  37059. }
  37060. break;
  37061. default:
  37062. state = STATE.NONE;
  37063. }
  37064. if (state !== STATE.NONE) {
  37065. scope.dispatchEvent(startEvent);
  37066. }
  37067. }
  37068. function onTouchMove(event) {
  37069. if (scope.enabled === false) return;
  37070. event.preventDefault(); // prevent scrolling
  37071. event.stopPropagation();
  37072. switch (state) {
  37073. case STATE.TOUCH_ROTATE:
  37074. if (scope.enableRotate === false) return;
  37075. handleTouchMoveRotate(event);
  37076. scope.update();
  37077. break;
  37078. case STATE.TOUCH_PAN:
  37079. if (scope.enablePan === false) return;
  37080. handleTouchMovePan(event);
  37081. scope.update();
  37082. break;
  37083. case STATE.TOUCH_DOLLY_PAN:
  37084. if (scope.enableZoom === false && scope.enablePan === false) return;
  37085. handleTouchMoveDollyPan(event);
  37086. scope.update();
  37087. break;
  37088. case STATE.TOUCH_DOLLY_ROTATE:
  37089. if (scope.enableZoom === false && scope.enableRotate === false) return;
  37090. handleTouchMoveDollyRotate(event);
  37091. scope.update();
  37092. break;
  37093. default:
  37094. state = STATE.NONE;
  37095. }
  37096. }
  37097. function onTouchEnd(event) {
  37098. if (scope.enabled === false) return;
  37099. handleTouchEnd(event);
  37100. scope.dispatchEvent(endEvent);
  37101. state = STATE.NONE;
  37102. }
  37103. function onContextMenu(event) {
  37104. if (scope.enabled === false) return;
  37105. event.preventDefault();
  37106. } //
  37107. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  37108. scope.domElement.addEventListener('pointerdown', onPointerDown, false);
  37109. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  37110. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  37111. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  37112. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  37113. scope.domElement.addEventListener('keydown', onKeyDown, false); // force an update at start
  37114. this.update();
  37115. };
  37116. exports.OrbitControls = OrbitControls;
  37117. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  37118. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  37119. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  37120. // This is very similar to OrbitControls, another set of touch behavior
  37121. //
  37122. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  37123. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  37124. // Pan - left mouse, or arrow keys / touch: one-finger move
  37125. var MapControls = function (object, domElement) {
  37126. OrbitControls.call(this, object, domElement);
  37127. this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up
  37128. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  37129. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  37130. this.touches.ONE = _threeModule.TOUCH.PAN;
  37131. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  37132. };
  37133. exports.MapControls = MapControls;
  37134. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  37135. MapControls.prototype.constructor = MapControls;
  37136. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/libs/dat.gui.module.js":[function(require,module,exports) {
  37137. "use strict";
  37138. Object.defineProperty(exports, "__esModule", {
  37139. value: true
  37140. });
  37141. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  37142. /**
  37143. * dat-gui JavaScript Controller Library
  37144. * http://code.google.com/p/dat-gui
  37145. *
  37146. * Copyright 2011 Data Arts Team, Google Creative Lab
  37147. *
  37148. * Licensed under the Apache License, Version 2.0 (the "License");
  37149. * you may not use this file except in compliance with the License.
  37150. * You may obtain a copy of the License at
  37151. *
  37152. * http://www.apache.org/licenses/LICENSE-2.0
  37153. */
  37154. function ___$insertStyle(css) {
  37155. if (!css) {
  37156. return;
  37157. }
  37158. if (typeof window === 'undefined') {
  37159. return;
  37160. }
  37161. var style = document.createElement('style');
  37162. style.setAttribute('type', 'text/css');
  37163. style.innerHTML = css;
  37164. document.head.appendChild(style);
  37165. return css;
  37166. }
  37167. function colorToString(color, forceCSSHex) {
  37168. var colorFormat = color.__state.conversionName.toString();
  37169. var r = Math.round(color.r);
  37170. var g = Math.round(color.g);
  37171. var b = Math.round(color.b);
  37172. var a = color.a;
  37173. var h = Math.round(color.h);
  37174. var s = color.s.toFixed(1);
  37175. var v = color.v.toFixed(1);
  37176. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  37177. var str = color.hex.toString(16);
  37178. while (str.length < 6) {
  37179. str = '0' + str;
  37180. }
  37181. return '#' + str;
  37182. } else if (colorFormat === 'CSS_RGB') {
  37183. return 'rgb(' + r + ',' + g + ',' + b + ')';
  37184. } else if (colorFormat === 'CSS_RGBA') {
  37185. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  37186. } else if (colorFormat === 'HEX') {
  37187. return '0x' + color.hex.toString(16);
  37188. } else if (colorFormat === 'RGB_ARRAY') {
  37189. return '[' + r + ',' + g + ',' + b + ']';
  37190. } else if (colorFormat === 'RGBA_ARRAY') {
  37191. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  37192. } else if (colorFormat === 'RGB_OBJ') {
  37193. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  37194. } else if (colorFormat === 'RGBA_OBJ') {
  37195. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  37196. } else if (colorFormat === 'HSV_OBJ') {
  37197. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  37198. } else if (colorFormat === 'HSVA_OBJ') {
  37199. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  37200. }
  37201. return 'unknown format';
  37202. }
  37203. var ARR_EACH = Array.prototype.forEach;
  37204. var ARR_SLICE = Array.prototype.slice;
  37205. var Common = {
  37206. BREAK: {},
  37207. extend: function extend(target) {
  37208. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  37209. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  37210. keys.forEach(function (key) {
  37211. if (!this.isUndefined(obj[key])) {
  37212. target[key] = obj[key];
  37213. }
  37214. }.bind(this));
  37215. }, this);
  37216. return target;
  37217. },
  37218. defaults: function defaults(target) {
  37219. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  37220. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  37221. keys.forEach(function (key) {
  37222. if (this.isUndefined(target[key])) {
  37223. target[key] = obj[key];
  37224. }
  37225. }.bind(this));
  37226. }, this);
  37227. return target;
  37228. },
  37229. compose: function compose() {
  37230. var toCall = ARR_SLICE.call(arguments);
  37231. return function () {
  37232. var args = ARR_SLICE.call(arguments);
  37233. for (var i = toCall.length - 1; i >= 0; i--) {
  37234. args = [toCall[i].apply(this, args)];
  37235. }
  37236. return args[0];
  37237. };
  37238. },
  37239. each: function each(obj, itr, scope) {
  37240. if (!obj) {
  37241. return;
  37242. }
  37243. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  37244. obj.forEach(itr, scope);
  37245. } else if (obj.length === obj.length + 0) {
  37246. var key = void 0;
  37247. var l = void 0;
  37248. for (key = 0, l = obj.length; key < l; key++) {
  37249. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  37250. return;
  37251. }
  37252. }
  37253. } else {
  37254. for (var _key in obj) {
  37255. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  37256. return;
  37257. }
  37258. }
  37259. }
  37260. },
  37261. defer: function defer(fnc) {
  37262. setTimeout(fnc, 0);
  37263. },
  37264. debounce: function debounce(func, threshold, callImmediately) {
  37265. var timeout = void 0;
  37266. return function () {
  37267. var obj = this;
  37268. var args = arguments;
  37269. function delayed() {
  37270. timeout = null;
  37271. if (!callImmediately) func.apply(obj, args);
  37272. }
  37273. var callNow = callImmediately || !timeout;
  37274. clearTimeout(timeout);
  37275. timeout = setTimeout(delayed, threshold);
  37276. if (callNow) {
  37277. func.apply(obj, args);
  37278. }
  37279. };
  37280. },
  37281. toArray: function toArray(obj) {
  37282. if (obj.toArray) return obj.toArray();
  37283. return ARR_SLICE.call(obj);
  37284. },
  37285. isUndefined: function isUndefined(obj) {
  37286. return obj === undefined;
  37287. },
  37288. isNull: function isNull(obj) {
  37289. return obj === null;
  37290. },
  37291. isNaN: function (_isNaN) {
  37292. function isNaN() {
  37293. return _isNaN.apply(this, arguments);
  37294. }
  37295. isNaN.toString = function () {
  37296. return _isNaN.toString();
  37297. };
  37298. return isNaN;
  37299. }(function (obj) {
  37300. return isNaN(obj);
  37301. }),
  37302. isArray: Array.isArray || function (obj) {
  37303. return obj.constructor === Array;
  37304. },
  37305. isObject: function isObject(obj) {
  37306. return obj === Object(obj);
  37307. },
  37308. isNumber: function isNumber(obj) {
  37309. return obj === obj + 0;
  37310. },
  37311. isString: function isString(obj) {
  37312. return obj === obj + '';
  37313. },
  37314. isBoolean: function isBoolean(obj) {
  37315. return obj === false || obj === true;
  37316. },
  37317. isFunction: function isFunction(obj) {
  37318. return obj instanceof Function;
  37319. }
  37320. };
  37321. var INTERPRETATIONS = [{
  37322. litmus: Common.isString,
  37323. conversions: {
  37324. THREE_CHAR_HEX: {
  37325. read: function read(original) {
  37326. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  37327. if (test === null) {
  37328. return false;
  37329. }
  37330. return {
  37331. space: 'HEX',
  37332. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  37333. };
  37334. },
  37335. write: colorToString
  37336. },
  37337. SIX_CHAR_HEX: {
  37338. read: function read(original) {
  37339. var test = original.match(/^#([A-F0-9]{6})$/i);
  37340. if (test === null) {
  37341. return false;
  37342. }
  37343. return {
  37344. space: 'HEX',
  37345. hex: parseInt('0x' + test[1].toString(), 0)
  37346. };
  37347. },
  37348. write: colorToString
  37349. },
  37350. CSS_RGB: {
  37351. read: function read(original) {
  37352. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  37353. if (test === null) {
  37354. return false;
  37355. }
  37356. return {
  37357. space: 'RGB',
  37358. r: parseFloat(test[1]),
  37359. g: parseFloat(test[2]),
  37360. b: parseFloat(test[3])
  37361. };
  37362. },
  37363. write: colorToString
  37364. },
  37365. CSS_RGBA: {
  37366. read: function read(original) {
  37367. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  37368. if (test === null) {
  37369. return false;
  37370. }
  37371. return {
  37372. space: 'RGB',
  37373. r: parseFloat(test[1]),
  37374. g: parseFloat(test[2]),
  37375. b: parseFloat(test[3]),
  37376. a: parseFloat(test[4])
  37377. };
  37378. },
  37379. write: colorToString
  37380. }
  37381. }
  37382. }, {
  37383. litmus: Common.isNumber,
  37384. conversions: {
  37385. HEX: {
  37386. read: function read(original) {
  37387. return {
  37388. space: 'HEX',
  37389. hex: original,
  37390. conversionName: 'HEX'
  37391. };
  37392. },
  37393. write: function write(color) {
  37394. return color.hex;
  37395. }
  37396. }
  37397. }
  37398. }, {
  37399. litmus: Common.isArray,
  37400. conversions: {
  37401. RGB_ARRAY: {
  37402. read: function read(original) {
  37403. if (original.length !== 3) {
  37404. return false;
  37405. }
  37406. return {
  37407. space: 'RGB',
  37408. r: original[0],
  37409. g: original[1],
  37410. b: original[2]
  37411. };
  37412. },
  37413. write: function write(color) {
  37414. return [color.r, color.g, color.b];
  37415. }
  37416. },
  37417. RGBA_ARRAY: {
  37418. read: function read(original) {
  37419. if (original.length !== 4) return false;
  37420. return {
  37421. space: 'RGB',
  37422. r: original[0],
  37423. g: original[1],
  37424. b: original[2],
  37425. a: original[3]
  37426. };
  37427. },
  37428. write: function write(color) {
  37429. return [color.r, color.g, color.b, color.a];
  37430. }
  37431. }
  37432. }
  37433. }, {
  37434. litmus: Common.isObject,
  37435. conversions: {
  37436. RGBA_OBJ: {
  37437. read: function read(original) {
  37438. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  37439. return {
  37440. space: 'RGB',
  37441. r: original.r,
  37442. g: original.g,
  37443. b: original.b,
  37444. a: original.a
  37445. };
  37446. }
  37447. return false;
  37448. },
  37449. write: function write(color) {
  37450. return {
  37451. r: color.r,
  37452. g: color.g,
  37453. b: color.b,
  37454. a: color.a
  37455. };
  37456. }
  37457. },
  37458. RGB_OBJ: {
  37459. read: function read(original) {
  37460. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  37461. return {
  37462. space: 'RGB',
  37463. r: original.r,
  37464. g: original.g,
  37465. b: original.b
  37466. };
  37467. }
  37468. return false;
  37469. },
  37470. write: function write(color) {
  37471. return {
  37472. r: color.r,
  37473. g: color.g,
  37474. b: color.b
  37475. };
  37476. }
  37477. },
  37478. HSVA_OBJ: {
  37479. read: function read(original) {
  37480. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  37481. return {
  37482. space: 'HSV',
  37483. h: original.h,
  37484. s: original.s,
  37485. v: original.v,
  37486. a: original.a
  37487. };
  37488. }
  37489. return false;
  37490. },
  37491. write: function write(color) {
  37492. return {
  37493. h: color.h,
  37494. s: color.s,
  37495. v: color.v,
  37496. a: color.a
  37497. };
  37498. }
  37499. },
  37500. HSV_OBJ: {
  37501. read: function read(original) {
  37502. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  37503. return {
  37504. space: 'HSV',
  37505. h: original.h,
  37506. s: original.s,
  37507. v: original.v
  37508. };
  37509. }
  37510. return false;
  37511. },
  37512. write: function write(color) {
  37513. return {
  37514. h: color.h,
  37515. s: color.s,
  37516. v: color.v
  37517. };
  37518. }
  37519. }
  37520. }
  37521. }];
  37522. var result = void 0;
  37523. var toReturn = void 0;
  37524. var interpret = function interpret() {
  37525. toReturn = false;
  37526. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  37527. Common.each(INTERPRETATIONS, function (family) {
  37528. if (family.litmus(original)) {
  37529. Common.each(family.conversions, function (conversion, conversionName) {
  37530. result = conversion.read(original);
  37531. if (toReturn === false && result !== false) {
  37532. toReturn = result;
  37533. result.conversionName = conversionName;
  37534. result.conversion = conversion;
  37535. return Common.BREAK;
  37536. }
  37537. });
  37538. return Common.BREAK;
  37539. }
  37540. });
  37541. return toReturn;
  37542. };
  37543. var tmpComponent = void 0;
  37544. var ColorMath = {
  37545. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  37546. var hi = Math.floor(h / 60) % 6;
  37547. var f = h / 60 - Math.floor(h / 60);
  37548. var p = v * (1.0 - s);
  37549. var q = v * (1.0 - f * s);
  37550. var t = v * (1.0 - (1.0 - f) * s);
  37551. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  37552. return {
  37553. r: c[0] * 255,
  37554. g: c[1] * 255,
  37555. b: c[2] * 255
  37556. };
  37557. },
  37558. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  37559. var min = Math.min(r, g, b);
  37560. var max = Math.max(r, g, b);
  37561. var delta = max - min;
  37562. var h = void 0;
  37563. var s = void 0;
  37564. if (max !== 0) {
  37565. s = delta / max;
  37566. } else {
  37567. return {
  37568. h: NaN,
  37569. s: 0,
  37570. v: 0
  37571. };
  37572. }
  37573. if (r === max) {
  37574. h = (g - b) / delta;
  37575. } else if (g === max) {
  37576. h = 2 + (b - r) / delta;
  37577. } else {
  37578. h = 4 + (r - g) / delta;
  37579. }
  37580. h /= 6;
  37581. if (h < 0) {
  37582. h += 1;
  37583. }
  37584. return {
  37585. h: h * 360,
  37586. s: s,
  37587. v: max / 255
  37588. };
  37589. },
  37590. rgb_to_hex: function rgb_to_hex(r, g, b) {
  37591. var hex = this.hex_with_component(0, 2, r);
  37592. hex = this.hex_with_component(hex, 1, g);
  37593. hex = this.hex_with_component(hex, 0, b);
  37594. return hex;
  37595. },
  37596. component_from_hex: function component_from_hex(hex, componentIndex) {
  37597. return hex >> componentIndex * 8 & 0xFF;
  37598. },
  37599. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  37600. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  37601. }
  37602. };
  37603. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  37604. return typeof obj;
  37605. } : function (obj) {
  37606. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  37607. };
  37608. var classCallCheck = function (instance, Constructor) {
  37609. if (!(instance instanceof Constructor)) {
  37610. throw new TypeError("Cannot call a class as a function");
  37611. }
  37612. };
  37613. var createClass = function () {
  37614. function defineProperties(target, props) {
  37615. for (var i = 0; i < props.length; i++) {
  37616. var descriptor = props[i];
  37617. descriptor.enumerable = descriptor.enumerable || false;
  37618. descriptor.configurable = true;
  37619. if ("value" in descriptor) descriptor.writable = true;
  37620. Object.defineProperty(target, descriptor.key, descriptor);
  37621. }
  37622. }
  37623. return function (Constructor, protoProps, staticProps) {
  37624. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  37625. if (staticProps) defineProperties(Constructor, staticProps);
  37626. return Constructor;
  37627. };
  37628. }();
  37629. var get = function get(object, property, receiver) {
  37630. if (object === null) object = Function.prototype;
  37631. var desc = Object.getOwnPropertyDescriptor(object, property);
  37632. if (desc === undefined) {
  37633. var parent = Object.getPrototypeOf(object);
  37634. if (parent === null) {
  37635. return undefined;
  37636. } else {
  37637. return get(parent, property, receiver);
  37638. }
  37639. } else if ("value" in desc) {
  37640. return desc.value;
  37641. } else {
  37642. var getter = desc.get;
  37643. if (getter === undefined) {
  37644. return undefined;
  37645. }
  37646. return getter.call(receiver);
  37647. }
  37648. };
  37649. var inherits = function (subClass, superClass) {
  37650. if (typeof superClass !== "function" && superClass !== null) {
  37651. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  37652. }
  37653. subClass.prototype = Object.create(superClass && superClass.prototype, {
  37654. constructor: {
  37655. value: subClass,
  37656. enumerable: false,
  37657. writable: true,
  37658. configurable: true
  37659. }
  37660. });
  37661. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  37662. };
  37663. var possibleConstructorReturn = function (self, call) {
  37664. if (!self) {
  37665. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  37666. }
  37667. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  37668. };
  37669. var Color = function () {
  37670. function Color() {
  37671. classCallCheck(this, Color);
  37672. this.__state = interpret.apply(this, arguments);
  37673. if (this.__state === false) {
  37674. throw new Error('Failed to interpret color arguments');
  37675. }
  37676. this.__state.a = this.__state.a || 1;
  37677. }
  37678. createClass(Color, [{
  37679. key: 'toString',
  37680. value: function toString() {
  37681. return colorToString(this);
  37682. }
  37683. }, {
  37684. key: 'toHexString',
  37685. value: function toHexString() {
  37686. return colorToString(this, true);
  37687. }
  37688. }, {
  37689. key: 'toOriginal',
  37690. value: function toOriginal() {
  37691. return this.__state.conversion.write(this);
  37692. }
  37693. }]);
  37694. return Color;
  37695. }();
  37696. function defineRGBComponent(target, component, componentHexIndex) {
  37697. Object.defineProperty(target, component, {
  37698. get: function get$$1() {
  37699. if (this.__state.space === 'RGB') {
  37700. return this.__state[component];
  37701. }
  37702. Color.recalculateRGB(this, component, componentHexIndex);
  37703. return this.__state[component];
  37704. },
  37705. set: function set$$1(v) {
  37706. if (this.__state.space !== 'RGB') {
  37707. Color.recalculateRGB(this, component, componentHexIndex);
  37708. this.__state.space = 'RGB';
  37709. }
  37710. this.__state[component] = v;
  37711. }
  37712. });
  37713. }
  37714. function defineHSVComponent(target, component) {
  37715. Object.defineProperty(target, component, {
  37716. get: function get$$1() {
  37717. if (this.__state.space === 'HSV') {
  37718. return this.__state[component];
  37719. }
  37720. Color.recalculateHSV(this);
  37721. return this.__state[component];
  37722. },
  37723. set: function set$$1(v) {
  37724. if (this.__state.space !== 'HSV') {
  37725. Color.recalculateHSV(this);
  37726. this.__state.space = 'HSV';
  37727. }
  37728. this.__state[component] = v;
  37729. }
  37730. });
  37731. }
  37732. Color.recalculateRGB = function (color, component, componentHexIndex) {
  37733. if (color.__state.space === 'HEX') {
  37734. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  37735. } else if (color.__state.space === 'HSV') {
  37736. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  37737. } else {
  37738. throw new Error('Corrupted color state');
  37739. }
  37740. };
  37741. Color.recalculateHSV = function (color) {
  37742. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  37743. Common.extend(color.__state, {
  37744. s: result.s,
  37745. v: result.v
  37746. });
  37747. if (!Common.isNaN(result.h)) {
  37748. color.__state.h = result.h;
  37749. } else if (Common.isUndefined(color.__state.h)) {
  37750. color.__state.h = 0;
  37751. }
  37752. };
  37753. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  37754. defineRGBComponent(Color.prototype, 'r', 2);
  37755. defineRGBComponent(Color.prototype, 'g', 1);
  37756. defineRGBComponent(Color.prototype, 'b', 0);
  37757. defineHSVComponent(Color.prototype, 'h');
  37758. defineHSVComponent(Color.prototype, 's');
  37759. defineHSVComponent(Color.prototype, 'v');
  37760. Object.defineProperty(Color.prototype, 'a', {
  37761. get: function get$$1() {
  37762. return this.__state.a;
  37763. },
  37764. set: function set$$1(v) {
  37765. this.__state.a = v;
  37766. }
  37767. });
  37768. Object.defineProperty(Color.prototype, 'hex', {
  37769. get: function get$$1() {
  37770. if (this.__state.space !== 'HEX') {
  37771. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  37772. this.__state.space = 'HEX';
  37773. }
  37774. return this.__state.hex;
  37775. },
  37776. set: function set$$1(v) {
  37777. this.__state.space = 'HEX';
  37778. this.__state.hex = v;
  37779. }
  37780. });
  37781. var Controller = function () {
  37782. function Controller(object, property) {
  37783. classCallCheck(this, Controller);
  37784. this.initialValue = object[property];
  37785. this.domElement = document.createElement('div');
  37786. this.object = object;
  37787. this.property = property;
  37788. this.__onChange = undefined;
  37789. this.__onFinishChange = undefined;
  37790. }
  37791. createClass(Controller, [{
  37792. key: 'onChange',
  37793. value: function onChange(fnc) {
  37794. this.__onChange = fnc;
  37795. return this;
  37796. }
  37797. }, {
  37798. key: 'onFinishChange',
  37799. value: function onFinishChange(fnc) {
  37800. this.__onFinishChange = fnc;
  37801. return this;
  37802. }
  37803. }, {
  37804. key: 'setValue',
  37805. value: function setValue(newValue) {
  37806. this.object[this.property] = newValue;
  37807. if (this.__onChange) {
  37808. this.__onChange.call(this, newValue);
  37809. }
  37810. this.updateDisplay();
  37811. return this;
  37812. }
  37813. }, {
  37814. key: 'getValue',
  37815. value: function getValue() {
  37816. return this.object[this.property];
  37817. }
  37818. }, {
  37819. key: 'updateDisplay',
  37820. value: function updateDisplay() {
  37821. return this;
  37822. }
  37823. }, {
  37824. key: 'isModified',
  37825. value: function isModified() {
  37826. return this.initialValue !== this.getValue();
  37827. }
  37828. }]);
  37829. return Controller;
  37830. }();
  37831. var EVENT_MAP = {
  37832. HTMLEvents: ['change'],
  37833. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  37834. KeyboardEvents: ['keydown']
  37835. };
  37836. var EVENT_MAP_INV = {};
  37837. Common.each(EVENT_MAP, function (v, k) {
  37838. Common.each(v, function (e) {
  37839. EVENT_MAP_INV[e] = k;
  37840. });
  37841. });
  37842. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  37843. function cssValueToPixels(val) {
  37844. if (val === '0' || Common.isUndefined(val)) {
  37845. return 0;
  37846. }
  37847. var match = val.match(CSS_VALUE_PIXELS);
  37848. if (!Common.isNull(match)) {
  37849. return parseFloat(match[1]);
  37850. }
  37851. return 0;
  37852. }
  37853. var dom = {
  37854. makeSelectable: function makeSelectable(elem, selectable) {
  37855. if (elem === undefined || elem.style === undefined) return;
  37856. elem.onselectstart = selectable ? function () {
  37857. return false;
  37858. } : function () {};
  37859. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  37860. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  37861. elem.unselectable = selectable ? 'on' : 'off';
  37862. },
  37863. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  37864. var vertical = vert;
  37865. var horizontal = hor;
  37866. if (Common.isUndefined(horizontal)) {
  37867. horizontal = true;
  37868. }
  37869. if (Common.isUndefined(vertical)) {
  37870. vertical = true;
  37871. }
  37872. elem.style.position = 'absolute';
  37873. if (horizontal) {
  37874. elem.style.left = 0;
  37875. elem.style.right = 0;
  37876. }
  37877. if (vertical) {
  37878. elem.style.top = 0;
  37879. elem.style.bottom = 0;
  37880. }
  37881. },
  37882. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  37883. var params = pars || {};
  37884. var className = EVENT_MAP_INV[eventType];
  37885. if (!className) {
  37886. throw new Error('Event type ' + eventType + ' not supported.');
  37887. }
  37888. var evt = document.createEvent(className);
  37889. switch (className) {
  37890. case 'MouseEvents':
  37891. {
  37892. var clientX = params.x || params.clientX || 0;
  37893. var clientY = params.y || params.clientY || 0;
  37894. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  37895. break;
  37896. }
  37897. case 'KeyboardEvents':
  37898. {
  37899. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  37900. Common.defaults(params, {
  37901. cancelable: true,
  37902. ctrlKey: false,
  37903. altKey: false,
  37904. shiftKey: false,
  37905. metaKey: false,
  37906. keyCode: undefined,
  37907. charCode: undefined
  37908. });
  37909. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  37910. break;
  37911. }
  37912. default:
  37913. {
  37914. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  37915. break;
  37916. }
  37917. }
  37918. Common.defaults(evt, aux);
  37919. elem.dispatchEvent(evt);
  37920. },
  37921. bind: function bind(elem, event, func, newBool) {
  37922. var bool = newBool || false;
  37923. if (elem.addEventListener) {
  37924. elem.addEventListener(event, func, bool);
  37925. } else if (elem.attachEvent) {
  37926. elem.attachEvent('on' + event, func);
  37927. }
  37928. return dom;
  37929. },
  37930. unbind: function unbind(elem, event, func, newBool) {
  37931. var bool = newBool || false;
  37932. if (elem.removeEventListener) {
  37933. elem.removeEventListener(event, func, bool);
  37934. } else if (elem.detachEvent) {
  37935. elem.detachEvent('on' + event, func);
  37936. }
  37937. return dom;
  37938. },
  37939. addClass: function addClass(elem, className) {
  37940. if (elem.className === undefined) {
  37941. elem.className = className;
  37942. } else if (elem.className !== className) {
  37943. var classes = elem.className.split(/ +/);
  37944. if (classes.indexOf(className) === -1) {
  37945. classes.push(className);
  37946. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  37947. }
  37948. }
  37949. return dom;
  37950. },
  37951. removeClass: function removeClass(elem, className) {
  37952. if (className) {
  37953. if (elem.className === className) {
  37954. elem.removeAttribute('class');
  37955. } else {
  37956. var classes = elem.className.split(/ +/);
  37957. var index = classes.indexOf(className);
  37958. if (index !== -1) {
  37959. classes.splice(index, 1);
  37960. elem.className = classes.join(' ');
  37961. }
  37962. }
  37963. } else {
  37964. elem.className = undefined;
  37965. }
  37966. return dom;
  37967. },
  37968. hasClass: function hasClass(elem, className) {
  37969. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  37970. },
  37971. getWidth: function getWidth(elem) {
  37972. var style = getComputedStyle(elem);
  37973. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  37974. },
  37975. getHeight: function getHeight(elem) {
  37976. var style = getComputedStyle(elem);
  37977. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  37978. },
  37979. getOffset: function getOffset(el) {
  37980. var elem = el;
  37981. var offset = {
  37982. left: 0,
  37983. top: 0
  37984. };
  37985. if (elem.offsetParent) {
  37986. do {
  37987. offset.left += elem.offsetLeft;
  37988. offset.top += elem.offsetTop;
  37989. elem = elem.offsetParent;
  37990. } while (elem);
  37991. }
  37992. return offset;
  37993. },
  37994. isActive: function isActive(elem) {
  37995. return elem === document.activeElement && (elem.type || elem.href);
  37996. }
  37997. };
  37998. var BooleanController = function (_Controller) {
  37999. inherits(BooleanController, _Controller);
  38000. function BooleanController(object, property) {
  38001. classCallCheck(this, BooleanController);
  38002. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  38003. var _this = _this2;
  38004. _this2.__prev = _this2.getValue();
  38005. _this2.__checkbox = document.createElement('input');
  38006. _this2.__checkbox.setAttribute('type', 'checkbox');
  38007. function onChange() {
  38008. _this.setValue(!_this.__prev);
  38009. }
  38010. dom.bind(_this2.__checkbox, 'change', onChange, false);
  38011. _this2.domElement.appendChild(_this2.__checkbox);
  38012. _this2.updateDisplay();
  38013. return _this2;
  38014. }
  38015. createClass(BooleanController, [{
  38016. key: 'setValue',
  38017. value: function setValue(v) {
  38018. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  38019. if (this.__onFinishChange) {
  38020. this.__onFinishChange.call(this, this.getValue());
  38021. }
  38022. this.__prev = this.getValue();
  38023. return toReturn;
  38024. }
  38025. }, {
  38026. key: 'updateDisplay',
  38027. value: function updateDisplay() {
  38028. if (this.getValue() === true) {
  38029. this.__checkbox.setAttribute('checked', 'checked');
  38030. this.__checkbox.checked = true;
  38031. this.__prev = true;
  38032. } else {
  38033. this.__checkbox.checked = false;
  38034. this.__prev = false;
  38035. }
  38036. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  38037. }
  38038. }]);
  38039. return BooleanController;
  38040. }(Controller);
  38041. var OptionController = function (_Controller) {
  38042. inherits(OptionController, _Controller);
  38043. function OptionController(object, property, opts) {
  38044. classCallCheck(this, OptionController);
  38045. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  38046. var options = opts;
  38047. var _this = _this2;
  38048. _this2.__select = document.createElement('select');
  38049. if (Common.isArray(options)) {
  38050. var map = {};
  38051. Common.each(options, function (element) {
  38052. map[element] = element;
  38053. });
  38054. options = map;
  38055. }
  38056. Common.each(options, function (value, key) {
  38057. var opt = document.createElement('option');
  38058. opt.innerHTML = key;
  38059. opt.setAttribute('value', value);
  38060. _this.__select.appendChild(opt);
  38061. });
  38062. _this2.updateDisplay();
  38063. dom.bind(_this2.__select, 'change', function () {
  38064. var desiredValue = this.options[this.selectedIndex].value;
  38065. _this.setValue(desiredValue);
  38066. });
  38067. _this2.domElement.appendChild(_this2.__select);
  38068. return _this2;
  38069. }
  38070. createClass(OptionController, [{
  38071. key: 'setValue',
  38072. value: function setValue(v) {
  38073. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  38074. if (this.__onFinishChange) {
  38075. this.__onFinishChange.call(this, this.getValue());
  38076. }
  38077. return toReturn;
  38078. }
  38079. }, {
  38080. key: 'updateDisplay',
  38081. value: function updateDisplay() {
  38082. if (dom.isActive(this.__select)) return this;
  38083. this.__select.value = this.getValue();
  38084. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  38085. }
  38086. }]);
  38087. return OptionController;
  38088. }(Controller);
  38089. var StringController = function (_Controller) {
  38090. inherits(StringController, _Controller);
  38091. function StringController(object, property) {
  38092. classCallCheck(this, StringController);
  38093. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  38094. var _this = _this2;
  38095. function onChange() {
  38096. _this.setValue(_this.__input.value);
  38097. }
  38098. function onBlur() {
  38099. if (_this.__onFinishChange) {
  38100. _this.__onFinishChange.call(_this, _this.getValue());
  38101. }
  38102. }
  38103. _this2.__input = document.createElement('input');
  38104. _this2.__input.setAttribute('type', 'text');
  38105. dom.bind(_this2.__input, 'keyup', onChange);
  38106. dom.bind(_this2.__input, 'change', onChange);
  38107. dom.bind(_this2.__input, 'blur', onBlur);
  38108. dom.bind(_this2.__input, 'keydown', function (e) {
  38109. if (e.keyCode === 13) {
  38110. this.blur();
  38111. }
  38112. });
  38113. _this2.updateDisplay();
  38114. _this2.domElement.appendChild(_this2.__input);
  38115. return _this2;
  38116. }
  38117. createClass(StringController, [{
  38118. key: 'updateDisplay',
  38119. value: function updateDisplay() {
  38120. if (!dom.isActive(this.__input)) {
  38121. this.__input.value = this.getValue();
  38122. }
  38123. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  38124. }
  38125. }]);
  38126. return StringController;
  38127. }(Controller);
  38128. function numDecimals(x) {
  38129. var _x = x.toString();
  38130. if (_x.indexOf('.') > -1) {
  38131. return _x.length - _x.indexOf('.') - 1;
  38132. }
  38133. return 0;
  38134. }
  38135. var NumberController = function (_Controller) {
  38136. inherits(NumberController, _Controller);
  38137. function NumberController(object, property, params) {
  38138. classCallCheck(this, NumberController);
  38139. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  38140. var _params = params || {};
  38141. _this.__min = _params.min;
  38142. _this.__max = _params.max;
  38143. _this.__step = _params.step;
  38144. if (Common.isUndefined(_this.__step)) {
  38145. if (_this.initialValue === 0) {
  38146. _this.__impliedStep = 1;
  38147. } else {
  38148. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  38149. }
  38150. } else {
  38151. _this.__impliedStep = _this.__step;
  38152. }
  38153. _this.__precision = numDecimals(_this.__impliedStep);
  38154. return _this;
  38155. }
  38156. createClass(NumberController, [{
  38157. key: 'setValue',
  38158. value: function setValue(v) {
  38159. var _v = v;
  38160. if (this.__min !== undefined && _v < this.__min) {
  38161. _v = this.__min;
  38162. } else if (this.__max !== undefined && _v > this.__max) {
  38163. _v = this.__max;
  38164. }
  38165. if (this.__step !== undefined && _v % this.__step !== 0) {
  38166. _v = Math.round(_v / this.__step) * this.__step;
  38167. }
  38168. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  38169. }
  38170. }, {
  38171. key: 'min',
  38172. value: function min(minValue) {
  38173. this.__min = minValue;
  38174. return this;
  38175. }
  38176. }, {
  38177. key: 'max',
  38178. value: function max(maxValue) {
  38179. this.__max = maxValue;
  38180. return this;
  38181. }
  38182. }, {
  38183. key: 'step',
  38184. value: function step(stepValue) {
  38185. this.__step = stepValue;
  38186. this.__impliedStep = stepValue;
  38187. this.__precision = numDecimals(stepValue);
  38188. return this;
  38189. }
  38190. }]);
  38191. return NumberController;
  38192. }(Controller);
  38193. function roundToDecimal(value, decimals) {
  38194. var tenTo = Math.pow(10, decimals);
  38195. return Math.round(value * tenTo) / tenTo;
  38196. }
  38197. var NumberControllerBox = function (_NumberController) {
  38198. inherits(NumberControllerBox, _NumberController);
  38199. function NumberControllerBox(object, property, params) {
  38200. classCallCheck(this, NumberControllerBox);
  38201. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  38202. _this2.__truncationSuspended = false;
  38203. var _this = _this2;
  38204. var prevY = void 0;
  38205. function onChange() {
  38206. var attempted = parseFloat(_this.__input.value);
  38207. if (!Common.isNaN(attempted)) {
  38208. _this.setValue(attempted);
  38209. }
  38210. }
  38211. function onFinish() {
  38212. if (_this.__onFinishChange) {
  38213. _this.__onFinishChange.call(_this, _this.getValue());
  38214. }
  38215. }
  38216. function onBlur() {
  38217. onFinish();
  38218. }
  38219. function onMouseDrag(e) {
  38220. var diff = prevY - e.clientY;
  38221. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  38222. prevY = e.clientY;
  38223. }
  38224. function onMouseUp() {
  38225. dom.unbind(window, 'mousemove', onMouseDrag);
  38226. dom.unbind(window, 'mouseup', onMouseUp);
  38227. onFinish();
  38228. }
  38229. function onMouseDown(e) {
  38230. dom.bind(window, 'mousemove', onMouseDrag);
  38231. dom.bind(window, 'mouseup', onMouseUp);
  38232. prevY = e.clientY;
  38233. }
  38234. _this2.__input = document.createElement('input');
  38235. _this2.__input.setAttribute('type', 'text');
  38236. dom.bind(_this2.__input, 'change', onChange);
  38237. dom.bind(_this2.__input, 'blur', onBlur);
  38238. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  38239. dom.bind(_this2.__input, 'keydown', function (e) {
  38240. if (e.keyCode === 13) {
  38241. _this.__truncationSuspended = true;
  38242. this.blur();
  38243. _this.__truncationSuspended = false;
  38244. onFinish();
  38245. }
  38246. });
  38247. _this2.updateDisplay();
  38248. _this2.domElement.appendChild(_this2.__input);
  38249. return _this2;
  38250. }
  38251. createClass(NumberControllerBox, [{
  38252. key: 'updateDisplay',
  38253. value: function updateDisplay() {
  38254. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  38255. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  38256. }
  38257. }]);
  38258. return NumberControllerBox;
  38259. }(NumberController);
  38260. function map(v, i1, i2, o1, o2) {
  38261. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  38262. }
  38263. var NumberControllerSlider = function (_NumberController) {
  38264. inherits(NumberControllerSlider, _NumberController);
  38265. function NumberControllerSlider(object, property, min, max, step) {
  38266. classCallCheck(this, NumberControllerSlider);
  38267. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  38268. min: min,
  38269. max: max,
  38270. step: step
  38271. }));
  38272. var _this = _this2;
  38273. _this2.__background = document.createElement('div');
  38274. _this2.__foreground = document.createElement('div');
  38275. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  38276. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  38277. dom.addClass(_this2.__background, 'slider');
  38278. dom.addClass(_this2.__foreground, 'slider-fg');
  38279. function onMouseDown(e) {
  38280. document.activeElement.blur();
  38281. dom.bind(window, 'mousemove', onMouseDrag);
  38282. dom.bind(window, 'mouseup', onMouseUp);
  38283. onMouseDrag(e);
  38284. }
  38285. function onMouseDrag(e) {
  38286. e.preventDefault();
  38287. var bgRect = _this.__background.getBoundingClientRect();
  38288. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  38289. return false;
  38290. }
  38291. function onMouseUp() {
  38292. dom.unbind(window, 'mousemove', onMouseDrag);
  38293. dom.unbind(window, 'mouseup', onMouseUp);
  38294. if (_this.__onFinishChange) {
  38295. _this.__onFinishChange.call(_this, _this.getValue());
  38296. }
  38297. }
  38298. function onTouchStart(e) {
  38299. if (e.touches.length !== 1) {
  38300. return;
  38301. }
  38302. dom.bind(window, 'touchmove', onTouchMove);
  38303. dom.bind(window, 'touchend', onTouchEnd);
  38304. onTouchMove(e);
  38305. }
  38306. function onTouchMove(e) {
  38307. var clientX = e.touches[0].clientX;
  38308. var bgRect = _this.__background.getBoundingClientRect();
  38309. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  38310. }
  38311. function onTouchEnd() {
  38312. dom.unbind(window, 'touchmove', onTouchMove);
  38313. dom.unbind(window, 'touchend', onTouchEnd);
  38314. if (_this.__onFinishChange) {
  38315. _this.__onFinishChange.call(_this, _this.getValue());
  38316. }
  38317. }
  38318. _this2.updateDisplay();
  38319. _this2.__background.appendChild(_this2.__foreground);
  38320. _this2.domElement.appendChild(_this2.__background);
  38321. return _this2;
  38322. }
  38323. createClass(NumberControllerSlider, [{
  38324. key: 'updateDisplay',
  38325. value: function updateDisplay() {
  38326. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  38327. this.__foreground.style.width = pct * 100 + '%';
  38328. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  38329. }
  38330. }]);
  38331. return NumberControllerSlider;
  38332. }(NumberController);
  38333. var FunctionController = function (_Controller) {
  38334. inherits(FunctionController, _Controller);
  38335. function FunctionController(object, property, text) {
  38336. classCallCheck(this, FunctionController);
  38337. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  38338. var _this = _this2;
  38339. _this2.__button = document.createElement('div');
  38340. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  38341. dom.bind(_this2.__button, 'click', function (e) {
  38342. e.preventDefault();
  38343. _this.fire();
  38344. return false;
  38345. });
  38346. dom.addClass(_this2.__button, 'button');
  38347. _this2.domElement.appendChild(_this2.__button);
  38348. return _this2;
  38349. }
  38350. createClass(FunctionController, [{
  38351. key: 'fire',
  38352. value: function fire() {
  38353. if (this.__onChange) {
  38354. this.__onChange.call(this);
  38355. }
  38356. this.getValue().call(this.object);
  38357. if (this.__onFinishChange) {
  38358. this.__onFinishChange.call(this, this.getValue());
  38359. }
  38360. }
  38361. }]);
  38362. return FunctionController;
  38363. }(Controller);
  38364. var ColorController = function (_Controller) {
  38365. inherits(ColorController, _Controller);
  38366. function ColorController(object, property) {
  38367. classCallCheck(this, ColorController);
  38368. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  38369. _this2.__color = new Color(_this2.getValue());
  38370. _this2.__temp = new Color(0);
  38371. var _this = _this2;
  38372. _this2.domElement = document.createElement('div');
  38373. dom.makeSelectable(_this2.domElement, false);
  38374. _this2.__selector = document.createElement('div');
  38375. _this2.__selector.className = 'selector';
  38376. _this2.__saturation_field = document.createElement('div');
  38377. _this2.__saturation_field.className = 'saturation-field';
  38378. _this2.__field_knob = document.createElement('div');
  38379. _this2.__field_knob.className = 'field-knob';
  38380. _this2.__field_knob_border = '2px solid ';
  38381. _this2.__hue_knob = document.createElement('div');
  38382. _this2.__hue_knob.className = 'hue-knob';
  38383. _this2.__hue_field = document.createElement('div');
  38384. _this2.__hue_field.className = 'hue-field';
  38385. _this2.__input = document.createElement('input');
  38386. _this2.__input.type = 'text';
  38387. _this2.__input_textShadow = '0 1px 1px ';
  38388. dom.bind(_this2.__input, 'keydown', function (e) {
  38389. if (e.keyCode === 13) {
  38390. onBlur.call(this);
  38391. }
  38392. });
  38393. dom.bind(_this2.__input, 'blur', onBlur);
  38394. dom.bind(_this2.__selector, 'mousedown', function () {
  38395. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  38396. dom.removeClass(_this.__selector, 'drag');
  38397. });
  38398. });
  38399. dom.bind(_this2.__selector, 'touchstart', function () {
  38400. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  38401. dom.removeClass(_this.__selector, 'drag');
  38402. });
  38403. });
  38404. var valueField = document.createElement('div');
  38405. Common.extend(_this2.__selector.style, {
  38406. width: '122px',
  38407. height: '102px',
  38408. padding: '3px',
  38409. backgroundColor: '#222',
  38410. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  38411. });
  38412. Common.extend(_this2.__field_knob.style, {
  38413. position: 'absolute',
  38414. width: '12px',
  38415. height: '12px',
  38416. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  38417. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  38418. borderRadius: '12px',
  38419. zIndex: 1
  38420. });
  38421. Common.extend(_this2.__hue_knob.style, {
  38422. position: 'absolute',
  38423. width: '15px',
  38424. height: '2px',
  38425. borderRight: '4px solid #fff',
  38426. zIndex: 1
  38427. });
  38428. Common.extend(_this2.__saturation_field.style, {
  38429. width: '100px',
  38430. height: '100px',
  38431. border: '1px solid #555',
  38432. marginRight: '3px',
  38433. display: 'inline-block',
  38434. cursor: 'pointer'
  38435. });
  38436. Common.extend(valueField.style, {
  38437. width: '100%',
  38438. height: '100%',
  38439. background: 'none'
  38440. });
  38441. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  38442. Common.extend(_this2.__hue_field.style, {
  38443. width: '15px',
  38444. height: '100px',
  38445. border: '1px solid #555',
  38446. cursor: 'ns-resize',
  38447. position: 'absolute',
  38448. top: '3px',
  38449. right: '3px'
  38450. });
  38451. hueGradient(_this2.__hue_field);
  38452. Common.extend(_this2.__input.style, {
  38453. outline: 'none',
  38454. textAlign: 'center',
  38455. color: '#fff',
  38456. border: 0,
  38457. fontWeight: 'bold',
  38458. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  38459. });
  38460. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  38461. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  38462. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  38463. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  38464. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  38465. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  38466. function fieldDown(e) {
  38467. setSV(e);
  38468. dom.bind(window, 'mousemove', setSV);
  38469. dom.bind(window, 'touchmove', setSV);
  38470. dom.bind(window, 'mouseup', fieldUpSV);
  38471. dom.bind(window, 'touchend', fieldUpSV);
  38472. }
  38473. function fieldDownH(e) {
  38474. setH(e);
  38475. dom.bind(window, 'mousemove', setH);
  38476. dom.bind(window, 'touchmove', setH);
  38477. dom.bind(window, 'mouseup', fieldUpH);
  38478. dom.bind(window, 'touchend', fieldUpH);
  38479. }
  38480. function fieldUpSV() {
  38481. dom.unbind(window, 'mousemove', setSV);
  38482. dom.unbind(window, 'touchmove', setSV);
  38483. dom.unbind(window, 'mouseup', fieldUpSV);
  38484. dom.unbind(window, 'touchend', fieldUpSV);
  38485. onFinish();
  38486. }
  38487. function fieldUpH() {
  38488. dom.unbind(window, 'mousemove', setH);
  38489. dom.unbind(window, 'touchmove', setH);
  38490. dom.unbind(window, 'mouseup', fieldUpH);
  38491. dom.unbind(window, 'touchend', fieldUpH);
  38492. onFinish();
  38493. }
  38494. function onBlur() {
  38495. var i = interpret(this.value);
  38496. if (i !== false) {
  38497. _this.__color.__state = i;
  38498. _this.setValue(_this.__color.toOriginal());
  38499. } else {
  38500. this.value = _this.__color.toString();
  38501. }
  38502. }
  38503. function onFinish() {
  38504. if (_this.__onFinishChange) {
  38505. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  38506. }
  38507. }
  38508. _this2.__saturation_field.appendChild(valueField);
  38509. _this2.__selector.appendChild(_this2.__field_knob);
  38510. _this2.__selector.appendChild(_this2.__saturation_field);
  38511. _this2.__selector.appendChild(_this2.__hue_field);
  38512. _this2.__hue_field.appendChild(_this2.__hue_knob);
  38513. _this2.domElement.appendChild(_this2.__input);
  38514. _this2.domElement.appendChild(_this2.__selector);
  38515. _this2.updateDisplay();
  38516. function setSV(e) {
  38517. if (e.type.indexOf('touch') === -1) {
  38518. e.preventDefault();
  38519. }
  38520. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  38521. var _ref = e.touches && e.touches[0] || e,
  38522. clientX = _ref.clientX,
  38523. clientY = _ref.clientY;
  38524. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  38525. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  38526. if (v > 1) {
  38527. v = 1;
  38528. } else if (v < 0) {
  38529. v = 0;
  38530. }
  38531. if (s > 1) {
  38532. s = 1;
  38533. } else if (s < 0) {
  38534. s = 0;
  38535. }
  38536. _this.__color.v = v;
  38537. _this.__color.s = s;
  38538. _this.setValue(_this.__color.toOriginal());
  38539. return false;
  38540. }
  38541. function setH(e) {
  38542. if (e.type.indexOf('touch') === -1) {
  38543. e.preventDefault();
  38544. }
  38545. var fieldRect = _this.__hue_field.getBoundingClientRect();
  38546. var _ref2 = e.touches && e.touches[0] || e,
  38547. clientY = _ref2.clientY;
  38548. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  38549. if (h > 1) {
  38550. h = 1;
  38551. } else if (h < 0) {
  38552. h = 0;
  38553. }
  38554. _this.__color.h = h * 360;
  38555. _this.setValue(_this.__color.toOriginal());
  38556. return false;
  38557. }
  38558. return _this2;
  38559. }
  38560. createClass(ColorController, [{
  38561. key: 'updateDisplay',
  38562. value: function updateDisplay() {
  38563. var i = interpret(this.getValue());
  38564. if (i !== false) {
  38565. var mismatch = false;
  38566. Common.each(Color.COMPONENTS, function (component) {
  38567. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  38568. mismatch = true;
  38569. return {};
  38570. }
  38571. }, this);
  38572. if (mismatch) {
  38573. Common.extend(this.__color.__state, i);
  38574. }
  38575. }
  38576. Common.extend(this.__temp.__state, this.__color.__state);
  38577. this.__temp.a = 1;
  38578. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  38579. var _flip = 255 - flip;
  38580. Common.extend(this.__field_knob.style, {
  38581. marginLeft: 100 * this.__color.s - 7 + 'px',
  38582. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  38583. backgroundColor: this.__temp.toHexString(),
  38584. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  38585. });
  38586. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  38587. this.__temp.s = 1;
  38588. this.__temp.v = 1;
  38589. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  38590. this.__input.value = this.__color.toString();
  38591. Common.extend(this.__input.style, {
  38592. backgroundColor: this.__color.toHexString(),
  38593. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  38594. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  38595. });
  38596. }
  38597. }]);
  38598. return ColorController;
  38599. }(Controller);
  38600. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  38601. function linearGradient(elem, x, a, b) {
  38602. elem.style.background = '';
  38603. Common.each(vendors, function (vendor) {
  38604. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  38605. });
  38606. }
  38607. function hueGradient(elem) {
  38608. elem.style.background = '';
  38609. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  38610. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  38611. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  38612. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  38613. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  38614. }
  38615. var css = {
  38616. load: function load(url, indoc) {
  38617. var doc = indoc || document;
  38618. var link = doc.createElement('link');
  38619. link.type = 'text/css';
  38620. link.rel = 'stylesheet';
  38621. link.href = url;
  38622. doc.getElementsByTagName('head')[0].appendChild(link);
  38623. },
  38624. inject: function inject(cssContent, indoc) {
  38625. var doc = indoc || document;
  38626. var injected = document.createElement('style');
  38627. injected.type = 'text/css';
  38628. injected.innerHTML = cssContent;
  38629. var head = doc.getElementsByTagName('head')[0];
  38630. try {
  38631. head.appendChild(injected);
  38632. } catch (e) {}
  38633. }
  38634. };
  38635. var saveDialogContents = "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n\n </div>\n\n </div>\n\n</div>";
  38636. var ControllerFactory = function ControllerFactory(object, property) {
  38637. var initialValue = object[property];
  38638. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  38639. return new OptionController(object, property, arguments[2]);
  38640. }
  38641. if (Common.isNumber(initialValue)) {
  38642. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  38643. if (Common.isNumber(arguments[4])) {
  38644. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  38645. }
  38646. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  38647. }
  38648. if (Common.isNumber(arguments[4])) {
  38649. return new NumberControllerBox(object, property, {
  38650. min: arguments[2],
  38651. max: arguments[3],
  38652. step: arguments[4]
  38653. });
  38654. }
  38655. return new NumberControllerBox(object, property, {
  38656. min: arguments[2],
  38657. max: arguments[3]
  38658. });
  38659. }
  38660. if (Common.isString(initialValue)) {
  38661. return new StringController(object, property);
  38662. }
  38663. if (Common.isFunction(initialValue)) {
  38664. return new FunctionController(object, property, '');
  38665. }
  38666. if (Common.isBoolean(initialValue)) {
  38667. return new BooleanController(object, property);
  38668. }
  38669. return null;
  38670. };
  38671. function requestAnimationFrame(callback) {
  38672. setTimeout(callback, 1000 / 60);
  38673. }
  38674. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  38675. var CenteredDiv = function () {
  38676. function CenteredDiv() {
  38677. classCallCheck(this, CenteredDiv);
  38678. this.backgroundElement = document.createElement('div');
  38679. Common.extend(this.backgroundElement.style, {
  38680. backgroundColor: 'rgba(0,0,0,0.8)',
  38681. top: 0,
  38682. left: 0,
  38683. display: 'none',
  38684. zIndex: '1000',
  38685. opacity: 0,
  38686. WebkitTransition: 'opacity 0.2s linear',
  38687. transition: 'opacity 0.2s linear'
  38688. });
  38689. dom.makeFullscreen(this.backgroundElement);
  38690. this.backgroundElement.style.position = 'fixed';
  38691. this.domElement = document.createElement('div');
  38692. Common.extend(this.domElement.style, {
  38693. position: 'fixed',
  38694. display: 'none',
  38695. zIndex: '1001',
  38696. opacity: 0,
  38697. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  38698. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  38699. });
  38700. document.body.appendChild(this.backgroundElement);
  38701. document.body.appendChild(this.domElement);
  38702. var _this = this;
  38703. dom.bind(this.backgroundElement, 'click', function () {
  38704. _this.hide();
  38705. });
  38706. }
  38707. createClass(CenteredDiv, [{
  38708. key: 'show',
  38709. value: function show() {
  38710. var _this = this;
  38711. this.backgroundElement.style.display = 'block';
  38712. this.domElement.style.display = 'block';
  38713. this.domElement.style.opacity = 0;
  38714. this.domElement.style.webkitTransform = 'scale(1.1)';
  38715. this.layout();
  38716. Common.defer(function () {
  38717. _this.backgroundElement.style.opacity = 1;
  38718. _this.domElement.style.opacity = 1;
  38719. _this.domElement.style.webkitTransform = 'scale(1)';
  38720. });
  38721. }
  38722. }, {
  38723. key: 'hide',
  38724. value: function hide() {
  38725. var _this = this;
  38726. var hide = function hide() {
  38727. _this.domElement.style.display = 'none';
  38728. _this.backgroundElement.style.display = 'none';
  38729. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  38730. dom.unbind(_this.domElement, 'transitionend', hide);
  38731. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  38732. };
  38733. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  38734. dom.bind(this.domElement, 'transitionend', hide);
  38735. dom.bind(this.domElement, 'oTransitionEnd', hide);
  38736. this.backgroundElement.style.opacity = 0;
  38737. this.domElement.style.opacity = 0;
  38738. this.domElement.style.webkitTransform = 'scale(1.1)';
  38739. }
  38740. }, {
  38741. key: 'layout',
  38742. value: function layout() {
  38743. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  38744. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  38745. }
  38746. }]);
  38747. return CenteredDiv;
  38748. }();
  38749. var styleSheet = ___$insertStyle(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");
  38750. css.inject(styleSheet);
  38751. var CSS_NAMESPACE = 'dg';
  38752. var HIDE_KEY_CODE = 72;
  38753. var CLOSE_BUTTON_HEIGHT = 20;
  38754. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  38755. var SUPPORTS_LOCAL_STORAGE = function () {
  38756. try {
  38757. return !!window.localStorage;
  38758. } catch (e) {
  38759. return false;
  38760. }
  38761. }();
  38762. var SAVE_DIALOGUE = void 0;
  38763. var autoPlaceVirgin = true;
  38764. var autoPlaceContainer = void 0;
  38765. var hide = false;
  38766. var hideableGuis = [];
  38767. var GUI = function GUI(pars) {
  38768. var _this = this;
  38769. var params = pars || {};
  38770. this.domElement = document.createElement('div');
  38771. this.__ul = document.createElement('ul');
  38772. this.domElement.appendChild(this.__ul);
  38773. dom.addClass(this.domElement, CSS_NAMESPACE);
  38774. this.__folders = {};
  38775. this.__controllers = [];
  38776. this.__rememberedObjects = [];
  38777. this.__rememberedObjectIndecesToControllers = [];
  38778. this.__listening = [];
  38779. params = Common.defaults(params, {
  38780. closeOnTop: false,
  38781. autoPlace: true,
  38782. width: GUI.DEFAULT_WIDTH
  38783. });
  38784. params = Common.defaults(params, {
  38785. resizable: params.autoPlace,
  38786. hideable: params.autoPlace
  38787. });
  38788. if (!Common.isUndefined(params.load)) {
  38789. if (params.preset) {
  38790. params.load.preset = params.preset;
  38791. }
  38792. } else {
  38793. params.load = {
  38794. preset: DEFAULT_DEFAULT_PRESET_NAME
  38795. };
  38796. }
  38797. if (Common.isUndefined(params.parent) && params.hideable) {
  38798. hideableGuis.push(this);
  38799. }
  38800. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  38801. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  38802. params.scrollable = true;
  38803. }
  38804. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  38805. var saveToLocalStorage = void 0;
  38806. var titleRow = void 0;
  38807. Object.defineProperties(this, {
  38808. parent: {
  38809. get: function get$$1() {
  38810. return params.parent;
  38811. }
  38812. },
  38813. scrollable: {
  38814. get: function get$$1() {
  38815. return params.scrollable;
  38816. }
  38817. },
  38818. autoPlace: {
  38819. get: function get$$1() {
  38820. return params.autoPlace;
  38821. }
  38822. },
  38823. closeOnTop: {
  38824. get: function get$$1() {
  38825. return params.closeOnTop;
  38826. }
  38827. },
  38828. preset: {
  38829. get: function get$$1() {
  38830. if (_this.parent) {
  38831. return _this.getRoot().preset;
  38832. }
  38833. return params.load.preset;
  38834. },
  38835. set: function set$$1(v) {
  38836. if (_this.parent) {
  38837. _this.getRoot().preset = v;
  38838. } else {
  38839. params.load.preset = v;
  38840. }
  38841. setPresetSelectIndex(this);
  38842. _this.revert();
  38843. }
  38844. },
  38845. width: {
  38846. get: function get$$1() {
  38847. return params.width;
  38848. },
  38849. set: function set$$1(v) {
  38850. params.width = v;
  38851. setWidth(_this, v);
  38852. }
  38853. },
  38854. name: {
  38855. get: function get$$1() {
  38856. return params.name;
  38857. },
  38858. set: function set$$1(v) {
  38859. params.name = v;
  38860. if (titleRow) {
  38861. titleRow.innerHTML = params.name;
  38862. }
  38863. }
  38864. },
  38865. closed: {
  38866. get: function get$$1() {
  38867. return params.closed;
  38868. },
  38869. set: function set$$1(v) {
  38870. params.closed = v;
  38871. if (params.closed) {
  38872. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  38873. } else {
  38874. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  38875. }
  38876. this.onResize();
  38877. if (_this.__closeButton) {
  38878. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  38879. }
  38880. }
  38881. },
  38882. load: {
  38883. get: function get$$1() {
  38884. return params.load;
  38885. }
  38886. },
  38887. useLocalStorage: {
  38888. get: function get$$1() {
  38889. return useLocalStorage;
  38890. },
  38891. set: function set$$1(bool) {
  38892. if (SUPPORTS_LOCAL_STORAGE) {
  38893. useLocalStorage = bool;
  38894. if (bool) {
  38895. dom.bind(window, 'unload', saveToLocalStorage);
  38896. } else {
  38897. dom.unbind(window, 'unload', saveToLocalStorage);
  38898. }
  38899. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  38900. }
  38901. }
  38902. }
  38903. });
  38904. if (Common.isUndefined(params.parent)) {
  38905. this.closed = params.closed || false;
  38906. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  38907. dom.makeSelectable(this.domElement, false);
  38908. if (SUPPORTS_LOCAL_STORAGE) {
  38909. if (useLocalStorage) {
  38910. _this.useLocalStorage = true;
  38911. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  38912. if (savedGui) {
  38913. params.load = JSON.parse(savedGui);
  38914. }
  38915. }
  38916. }
  38917. this.__closeButton = document.createElement('div');
  38918. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  38919. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  38920. if (params.closeOnTop) {
  38921. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  38922. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  38923. } else {
  38924. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  38925. this.domElement.appendChild(this.__closeButton);
  38926. }
  38927. dom.bind(this.__closeButton, 'click', function () {
  38928. _this.closed = !_this.closed;
  38929. });
  38930. } else {
  38931. if (params.closed === undefined) {
  38932. params.closed = true;
  38933. }
  38934. var titleRowName = document.createTextNode(params.name);
  38935. dom.addClass(titleRowName, 'controller-name');
  38936. titleRow = addRow(_this, titleRowName);
  38937. var onClickTitle = function onClickTitle(e) {
  38938. e.preventDefault();
  38939. _this.closed = !_this.closed;
  38940. return false;
  38941. };
  38942. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  38943. dom.addClass(titleRow, 'title');
  38944. dom.bind(titleRow, 'click', onClickTitle);
  38945. if (!params.closed) {
  38946. this.closed = false;
  38947. }
  38948. }
  38949. if (params.autoPlace) {
  38950. if (Common.isUndefined(params.parent)) {
  38951. if (autoPlaceVirgin) {
  38952. autoPlaceContainer = document.createElement('div');
  38953. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  38954. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  38955. document.body.appendChild(autoPlaceContainer);
  38956. autoPlaceVirgin = false;
  38957. }
  38958. autoPlaceContainer.appendChild(this.domElement);
  38959. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  38960. }
  38961. if (!this.parent) {
  38962. setWidth(_this, params.width);
  38963. }
  38964. }
  38965. this.__resizeHandler = function () {
  38966. _this.onResizeDebounced();
  38967. };
  38968. dom.bind(window, 'resize', this.__resizeHandler);
  38969. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  38970. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  38971. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  38972. this.onResize();
  38973. if (params.resizable) {
  38974. addResizeHandle(this);
  38975. }
  38976. saveToLocalStorage = function saveToLocalStorage() {
  38977. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  38978. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  38979. }
  38980. };
  38981. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  38982. function resetWidth() {
  38983. var root = _this.getRoot();
  38984. root.width += 1;
  38985. Common.defer(function () {
  38986. root.width -= 1;
  38987. });
  38988. }
  38989. if (!params.parent) {
  38990. resetWidth();
  38991. }
  38992. };
  38993. GUI.toggleHide = function () {
  38994. hide = !hide;
  38995. Common.each(hideableGuis, function (gui) {
  38996. gui.domElement.style.display = hide ? 'none' : '';
  38997. });
  38998. };
  38999. GUI.CLASS_AUTO_PLACE = 'a';
  39000. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  39001. GUI.CLASS_MAIN = 'main';
  39002. GUI.CLASS_CONTROLLER_ROW = 'cr';
  39003. GUI.CLASS_TOO_TALL = 'taller-than-window';
  39004. GUI.CLASS_CLOSED = 'closed';
  39005. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  39006. GUI.CLASS_CLOSE_TOP = 'close-top';
  39007. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  39008. GUI.CLASS_DRAG = 'drag';
  39009. GUI.DEFAULT_WIDTH = 245;
  39010. GUI.TEXT_CLOSED = 'Close Controls';
  39011. GUI.TEXT_OPEN = 'Open Controls';
  39012. GUI._keydownHandler = function (e) {
  39013. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  39014. GUI.toggleHide();
  39015. }
  39016. };
  39017. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  39018. Common.extend(GUI.prototype, {
  39019. add: function add(object, property) {
  39020. return _add(this, object, property, {
  39021. factoryArgs: Array.prototype.slice.call(arguments, 2)
  39022. });
  39023. },
  39024. addColor: function addColor(object, property) {
  39025. return _add(this, object, property, {
  39026. color: true
  39027. });
  39028. },
  39029. remove: function remove(controller) {
  39030. this.__ul.removeChild(controller.__li);
  39031. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  39032. var _this = this;
  39033. Common.defer(function () {
  39034. _this.onResize();
  39035. });
  39036. },
  39037. destroy: function destroy() {
  39038. if (this.parent) {
  39039. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  39040. }
  39041. if (this.autoPlace) {
  39042. autoPlaceContainer.removeChild(this.domElement);
  39043. }
  39044. var _this = this;
  39045. Common.each(this.__folders, function (subfolder) {
  39046. _this.removeFolder(subfolder);
  39047. });
  39048. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  39049. removeListeners(this);
  39050. },
  39051. addFolder: function addFolder(name) {
  39052. if (this.__folders[name] !== undefined) {
  39053. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  39054. }
  39055. var newGuiParams = {
  39056. name: name,
  39057. parent: this
  39058. };
  39059. newGuiParams.autoPlace = this.autoPlace;
  39060. if (this.load && this.load.folders && this.load.folders[name]) {
  39061. newGuiParams.closed = this.load.folders[name].closed;
  39062. newGuiParams.load = this.load.folders[name];
  39063. }
  39064. var gui = new GUI(newGuiParams);
  39065. this.__folders[name] = gui;
  39066. var li = addRow(this, gui.domElement);
  39067. dom.addClass(li, 'folder');
  39068. return gui;
  39069. },
  39070. removeFolder: function removeFolder(folder) {
  39071. this.__ul.removeChild(folder.domElement.parentElement);
  39072. delete this.__folders[folder.name];
  39073. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  39074. delete this.load.folders[folder.name];
  39075. }
  39076. removeListeners(folder);
  39077. var _this = this;
  39078. Common.each(folder.__folders, function (subfolder) {
  39079. folder.removeFolder(subfolder);
  39080. });
  39081. Common.defer(function () {
  39082. _this.onResize();
  39083. });
  39084. },
  39085. open: function open() {
  39086. this.closed = false;
  39087. },
  39088. close: function close() {
  39089. this.closed = true;
  39090. },
  39091. hide: function hide() {
  39092. this.domElement.style.display = 'none';
  39093. },
  39094. show: function show() {
  39095. this.domElement.style.display = '';
  39096. },
  39097. onResize: function onResize() {
  39098. var root = this.getRoot();
  39099. if (root.scrollable) {
  39100. var top = dom.getOffset(root.__ul).top;
  39101. var h = 0;
  39102. Common.each(root.__ul.childNodes, function (node) {
  39103. if (!(root.autoPlace && node === root.__save_row)) {
  39104. h += dom.getHeight(node);
  39105. }
  39106. });
  39107. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  39108. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  39109. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  39110. } else {
  39111. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  39112. root.__ul.style.height = 'auto';
  39113. }
  39114. }
  39115. if (root.__resize_handle) {
  39116. Common.defer(function () {
  39117. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  39118. });
  39119. }
  39120. if (root.__closeButton) {
  39121. root.__closeButton.style.width = root.width + 'px';
  39122. }
  39123. },
  39124. onResizeDebounced: Common.debounce(function () {
  39125. this.onResize();
  39126. }, 50),
  39127. remember: function remember() {
  39128. if (Common.isUndefined(SAVE_DIALOGUE)) {
  39129. SAVE_DIALOGUE = new CenteredDiv();
  39130. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  39131. }
  39132. if (this.parent) {
  39133. throw new Error('You can only call remember on a top level GUI.');
  39134. }
  39135. var _this = this;
  39136. Common.each(Array.prototype.slice.call(arguments), function (object) {
  39137. if (_this.__rememberedObjects.length === 0) {
  39138. addSaveMenu(_this);
  39139. }
  39140. if (_this.__rememberedObjects.indexOf(object) === -1) {
  39141. _this.__rememberedObjects.push(object);
  39142. }
  39143. });
  39144. if (this.autoPlace) {
  39145. setWidth(this, this.width);
  39146. }
  39147. },
  39148. getRoot: function getRoot() {
  39149. var gui = this;
  39150. while (gui.parent) {
  39151. gui = gui.parent;
  39152. }
  39153. return gui;
  39154. },
  39155. getSaveObject: function getSaveObject() {
  39156. var toReturn = this.load;
  39157. toReturn.closed = this.closed;
  39158. if (this.__rememberedObjects.length > 0) {
  39159. toReturn.preset = this.preset;
  39160. if (!toReturn.remembered) {
  39161. toReturn.remembered = {};
  39162. }
  39163. toReturn.remembered[this.preset] = getCurrentPreset(this);
  39164. }
  39165. toReturn.folders = {};
  39166. Common.each(this.__folders, function (element, key) {
  39167. toReturn.folders[key] = element.getSaveObject();
  39168. });
  39169. return toReturn;
  39170. },
  39171. save: function save() {
  39172. if (!this.load.remembered) {
  39173. this.load.remembered = {};
  39174. }
  39175. this.load.remembered[this.preset] = getCurrentPreset(this);
  39176. markPresetModified(this, false);
  39177. this.saveToLocalStorageIfPossible();
  39178. },
  39179. saveAs: function saveAs(presetName) {
  39180. if (!this.load.remembered) {
  39181. this.load.remembered = {};
  39182. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  39183. }
  39184. this.load.remembered[presetName] = getCurrentPreset(this);
  39185. this.preset = presetName;
  39186. addPresetOption(this, presetName, true);
  39187. this.saveToLocalStorageIfPossible();
  39188. },
  39189. revert: function revert(gui) {
  39190. Common.each(this.__controllers, function (controller) {
  39191. if (!this.getRoot().load.remembered) {
  39192. controller.setValue(controller.initialValue);
  39193. } else {
  39194. recallSavedValue(gui || this.getRoot(), controller);
  39195. }
  39196. if (controller.__onFinishChange) {
  39197. controller.__onFinishChange.call(controller, controller.getValue());
  39198. }
  39199. }, this);
  39200. Common.each(this.__folders, function (folder) {
  39201. folder.revert(folder);
  39202. });
  39203. if (!gui) {
  39204. markPresetModified(this.getRoot(), false);
  39205. }
  39206. },
  39207. listen: function listen(controller) {
  39208. var init = this.__listening.length === 0;
  39209. this.__listening.push(controller);
  39210. if (init) {
  39211. updateDisplays(this.__listening);
  39212. }
  39213. },
  39214. updateDisplay: function updateDisplay() {
  39215. Common.each(this.__controllers, function (controller) {
  39216. controller.updateDisplay();
  39217. });
  39218. Common.each(this.__folders, function (folder) {
  39219. folder.updateDisplay();
  39220. });
  39221. }
  39222. });
  39223. function addRow(gui, newDom, liBefore) {
  39224. var li = document.createElement('li');
  39225. if (newDom) {
  39226. li.appendChild(newDom);
  39227. }
  39228. if (liBefore) {
  39229. gui.__ul.insertBefore(li, liBefore);
  39230. } else {
  39231. gui.__ul.appendChild(li);
  39232. }
  39233. gui.onResize();
  39234. return li;
  39235. }
  39236. function removeListeners(gui) {
  39237. dom.unbind(window, 'resize', gui.__resizeHandler);
  39238. if (gui.saveToLocalStorageIfPossible) {
  39239. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  39240. }
  39241. }
  39242. function markPresetModified(gui, modified) {
  39243. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  39244. if (modified) {
  39245. opt.innerHTML = opt.value + '*';
  39246. } else {
  39247. opt.innerHTML = opt.value;
  39248. }
  39249. }
  39250. function augmentController(gui, li, controller) {
  39251. controller.__li = li;
  39252. controller.__gui = gui;
  39253. Common.extend(controller, {
  39254. options: function options(_options) {
  39255. if (arguments.length > 1) {
  39256. var nextSibling = controller.__li.nextElementSibling;
  39257. controller.remove();
  39258. return _add(gui, controller.object, controller.property, {
  39259. before: nextSibling,
  39260. factoryArgs: [Common.toArray(arguments)]
  39261. });
  39262. }
  39263. if (Common.isArray(_options) || Common.isObject(_options)) {
  39264. var _nextSibling = controller.__li.nextElementSibling;
  39265. controller.remove();
  39266. return _add(gui, controller.object, controller.property, {
  39267. before: _nextSibling,
  39268. factoryArgs: [_options]
  39269. });
  39270. }
  39271. },
  39272. name: function name(_name) {
  39273. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  39274. return controller;
  39275. },
  39276. listen: function listen() {
  39277. controller.__gui.listen(controller);
  39278. return controller;
  39279. },
  39280. remove: function remove() {
  39281. controller.__gui.remove(controller);
  39282. return controller;
  39283. }
  39284. });
  39285. if (controller instanceof NumberControllerSlider) {
  39286. var box = new NumberControllerBox(controller.object, controller.property, {
  39287. min: controller.__min,
  39288. max: controller.__max,
  39289. step: controller.__step
  39290. });
  39291. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  39292. var pc = controller[method];
  39293. var pb = box[method];
  39294. controller[method] = box[method] = function () {
  39295. var args = Array.prototype.slice.call(arguments);
  39296. pb.apply(box, args);
  39297. return pc.apply(controller, args);
  39298. };
  39299. });
  39300. dom.addClass(li, 'has-slider');
  39301. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  39302. } else if (controller instanceof NumberControllerBox) {
  39303. var r = function r(returned) {
  39304. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  39305. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  39306. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  39307. controller.remove();
  39308. var newController = _add(gui, controller.object, controller.property, {
  39309. before: controller.__li.nextElementSibling,
  39310. factoryArgs: [controller.__min, controller.__max, controller.__step]
  39311. });
  39312. newController.name(oldName);
  39313. if (wasListening) newController.listen();
  39314. return newController;
  39315. }
  39316. return returned;
  39317. };
  39318. controller.min = Common.compose(r, controller.min);
  39319. controller.max = Common.compose(r, controller.max);
  39320. } else if (controller instanceof BooleanController) {
  39321. dom.bind(li, 'click', function () {
  39322. dom.fakeEvent(controller.__checkbox, 'click');
  39323. });
  39324. dom.bind(controller.__checkbox, 'click', function (e) {
  39325. e.stopPropagation();
  39326. });
  39327. } else if (controller instanceof FunctionController) {
  39328. dom.bind(li, 'click', function () {
  39329. dom.fakeEvent(controller.__button, 'click');
  39330. });
  39331. dom.bind(li, 'mouseover', function () {
  39332. dom.addClass(controller.__button, 'hover');
  39333. });
  39334. dom.bind(li, 'mouseout', function () {
  39335. dom.removeClass(controller.__button, 'hover');
  39336. });
  39337. } else if (controller instanceof ColorController) {
  39338. dom.addClass(li, 'color');
  39339. controller.updateDisplay = Common.compose(function (val) {
  39340. li.style.borderLeftColor = controller.__color.toString();
  39341. return val;
  39342. }, controller.updateDisplay);
  39343. controller.updateDisplay();
  39344. }
  39345. controller.setValue = Common.compose(function (val) {
  39346. if (gui.getRoot().__preset_select && controller.isModified()) {
  39347. markPresetModified(gui.getRoot(), true);
  39348. }
  39349. return val;
  39350. }, controller.setValue);
  39351. }
  39352. function recallSavedValue(gui, controller) {
  39353. var root = gui.getRoot();
  39354. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  39355. if (matchedIndex !== -1) {
  39356. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  39357. if (controllerMap === undefined) {
  39358. controllerMap = {};
  39359. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  39360. }
  39361. controllerMap[controller.property] = controller;
  39362. if (root.load && root.load.remembered) {
  39363. var presetMap = root.load.remembered;
  39364. var preset = void 0;
  39365. if (presetMap[gui.preset]) {
  39366. preset = presetMap[gui.preset];
  39367. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  39368. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  39369. } else {
  39370. return;
  39371. }
  39372. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  39373. var value = preset[matchedIndex][controller.property];
  39374. controller.initialValue = value;
  39375. controller.setValue(value);
  39376. }
  39377. }
  39378. }
  39379. }
  39380. function _add(gui, object, property, params) {
  39381. if (object[property] === undefined) {
  39382. throw new Error('Object "' + object + '" has no property "' + property + '"');
  39383. }
  39384. var controller = void 0;
  39385. if (params.color) {
  39386. controller = new ColorController(object, property);
  39387. } else {
  39388. var factoryArgs = [object, property].concat(params.factoryArgs);
  39389. controller = ControllerFactory.apply(gui, factoryArgs);
  39390. }
  39391. if (params.before instanceof Controller) {
  39392. params.before = params.before.__li;
  39393. }
  39394. recallSavedValue(gui, controller);
  39395. dom.addClass(controller.domElement, 'c');
  39396. var name = document.createElement('span');
  39397. dom.addClass(name, 'property-name');
  39398. name.innerHTML = controller.property;
  39399. var container = document.createElement('div');
  39400. container.appendChild(name);
  39401. container.appendChild(controller.domElement);
  39402. var li = addRow(gui, container, params.before);
  39403. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  39404. if (controller instanceof ColorController) {
  39405. dom.addClass(li, 'color');
  39406. } else {
  39407. dom.addClass(li, _typeof(controller.getValue()));
  39408. }
  39409. augmentController(gui, li, controller);
  39410. gui.__controllers.push(controller);
  39411. return controller;
  39412. }
  39413. function getLocalStorageHash(gui, key) {
  39414. return document.location.href + '.' + key;
  39415. }
  39416. function addPresetOption(gui, name, setSelected) {
  39417. var opt = document.createElement('option');
  39418. opt.innerHTML = name;
  39419. opt.value = name;
  39420. gui.__preset_select.appendChild(opt);
  39421. if (setSelected) {
  39422. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  39423. }
  39424. }
  39425. function showHideExplain(gui, explain) {
  39426. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  39427. }
  39428. function addSaveMenu(gui) {
  39429. var div = gui.__save_row = document.createElement('li');
  39430. dom.addClass(gui.domElement, 'has-save');
  39431. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  39432. dom.addClass(div, 'save-row');
  39433. var gears = document.createElement('span');
  39434. gears.innerHTML = '&nbsp;';
  39435. dom.addClass(gears, 'button gears');
  39436. var button = document.createElement('span');
  39437. button.innerHTML = 'Save';
  39438. dom.addClass(button, 'button');
  39439. dom.addClass(button, 'save');
  39440. var button2 = document.createElement('span');
  39441. button2.innerHTML = 'New';
  39442. dom.addClass(button2, 'button');
  39443. dom.addClass(button2, 'save-as');
  39444. var button3 = document.createElement('span');
  39445. button3.innerHTML = 'Revert';
  39446. dom.addClass(button3, 'button');
  39447. dom.addClass(button3, 'revert');
  39448. var select = gui.__preset_select = document.createElement('select');
  39449. if (gui.load && gui.load.remembered) {
  39450. Common.each(gui.load.remembered, function (value, key) {
  39451. addPresetOption(gui, key, key === gui.preset);
  39452. });
  39453. } else {
  39454. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  39455. }
  39456. dom.bind(select, 'change', function () {
  39457. for (var index = 0; index < gui.__preset_select.length; index++) {
  39458. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  39459. }
  39460. gui.preset = this.value;
  39461. });
  39462. div.appendChild(select);
  39463. div.appendChild(gears);
  39464. div.appendChild(button);
  39465. div.appendChild(button2);
  39466. div.appendChild(button3);
  39467. if (SUPPORTS_LOCAL_STORAGE) {
  39468. var explain = document.getElementById('dg-local-explain');
  39469. var localStorageCheckBox = document.getElementById('dg-local-storage');
  39470. var saveLocally = document.getElementById('dg-save-locally');
  39471. saveLocally.style.display = 'block';
  39472. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  39473. localStorageCheckBox.setAttribute('checked', 'checked');
  39474. }
  39475. showHideExplain(gui, explain);
  39476. dom.bind(localStorageCheckBox, 'change', function () {
  39477. gui.useLocalStorage = !gui.useLocalStorage;
  39478. showHideExplain(gui, explain);
  39479. });
  39480. }
  39481. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  39482. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  39483. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  39484. SAVE_DIALOGUE.hide();
  39485. }
  39486. });
  39487. dom.bind(gears, 'click', function () {
  39488. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  39489. SAVE_DIALOGUE.show();
  39490. newConstructorTextArea.focus();
  39491. newConstructorTextArea.select();
  39492. });
  39493. dom.bind(button, 'click', function () {
  39494. gui.save();
  39495. });
  39496. dom.bind(button2, 'click', function () {
  39497. var presetName = prompt('Enter a new preset name.');
  39498. if (presetName) {
  39499. gui.saveAs(presetName);
  39500. }
  39501. });
  39502. dom.bind(button3, 'click', function () {
  39503. gui.revert();
  39504. });
  39505. }
  39506. function addResizeHandle(gui) {
  39507. var pmouseX = void 0;
  39508. gui.__resize_handle = document.createElement('div');
  39509. Common.extend(gui.__resize_handle.style, {
  39510. width: '6px',
  39511. marginLeft: '-3px',
  39512. height: '200px',
  39513. cursor: 'ew-resize',
  39514. position: 'absolute'
  39515. });
  39516. function drag(e) {
  39517. e.preventDefault();
  39518. gui.width += pmouseX - e.clientX;
  39519. gui.onResize();
  39520. pmouseX = e.clientX;
  39521. return false;
  39522. }
  39523. function dragStop() {
  39524. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  39525. dom.unbind(window, 'mousemove', drag);
  39526. dom.unbind(window, 'mouseup', dragStop);
  39527. }
  39528. function dragStart(e) {
  39529. e.preventDefault();
  39530. pmouseX = e.clientX;
  39531. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  39532. dom.bind(window, 'mousemove', drag);
  39533. dom.bind(window, 'mouseup', dragStop);
  39534. return false;
  39535. }
  39536. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  39537. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  39538. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  39539. }
  39540. function setWidth(gui, w) {
  39541. gui.domElement.style.width = w + 'px';
  39542. if (gui.__save_row && gui.autoPlace) {
  39543. gui.__save_row.style.width = w + 'px';
  39544. }
  39545. if (gui.__closeButton) {
  39546. gui.__closeButton.style.width = w + 'px';
  39547. }
  39548. }
  39549. function getCurrentPreset(gui, useInitialValues) {
  39550. var toReturn = {};
  39551. Common.each(gui.__rememberedObjects, function (val, index) {
  39552. var savedValues = {};
  39553. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  39554. Common.each(controllerMap, function (controller, property) {
  39555. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  39556. });
  39557. toReturn[index] = savedValues;
  39558. });
  39559. return toReturn;
  39560. }
  39561. function setPresetSelectIndex(gui) {
  39562. for (var index = 0; index < gui.__preset_select.length; index++) {
  39563. if (gui.__preset_select[index].value === gui.preset) {
  39564. gui.__preset_select.selectedIndex = index;
  39565. }
  39566. }
  39567. }
  39568. function updateDisplays(controllerArray) {
  39569. if (controllerArray.length !== 0) {
  39570. requestAnimationFrame$1.call(window, function () {
  39571. updateDisplays(controllerArray);
  39572. });
  39573. }
  39574. Common.each(controllerArray, function (c) {
  39575. c.updateDisplay();
  39576. });
  39577. }
  39578. var color = {
  39579. Color: Color,
  39580. math: ColorMath,
  39581. interpret: interpret
  39582. };
  39583. exports.color = color;
  39584. var controllers = {
  39585. Controller: Controller,
  39586. BooleanController: BooleanController,
  39587. OptionController: OptionController,
  39588. StringController: StringController,
  39589. NumberController: NumberController,
  39590. NumberControllerBox: NumberControllerBox,
  39591. NumberControllerSlider: NumberControllerSlider,
  39592. FunctionController: FunctionController,
  39593. ColorController: ColorController
  39594. };
  39595. exports.controllers = controllers;
  39596. var dom$1 = {
  39597. dom: dom
  39598. };
  39599. exports.dom = dom$1;
  39600. var gui = {
  39601. GUI: GUI
  39602. };
  39603. exports.gui = gui;
  39604. var GUI$1 = GUI;
  39605. exports.GUI = GUI$1;
  39606. var index = {
  39607. color: color,
  39608. controllers: controllers,
  39609. dom: dom$1,
  39610. gui: gui,
  39611. GUI: GUI$1
  39612. };
  39613. var _default = index;
  39614. exports.default = _default;
  39615. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  39616. "use strict";
  39617. Object.defineProperty(exports, "__esModule", {
  39618. value: true
  39619. });
  39620. exports.default = void 0;
  39621. var Stats = function () {
  39622. var mode = 0;
  39623. var container = document.createElement('div');
  39624. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  39625. container.addEventListener('click', function (event) {
  39626. event.preventDefault();
  39627. showPanel(++mode % container.children.length);
  39628. }, false); //
  39629. function addPanel(panel) {
  39630. container.appendChild(panel.dom);
  39631. return panel;
  39632. }
  39633. function showPanel(id) {
  39634. for (var i = 0; i < container.children.length; i++) {
  39635. container.children[i].style.display = i === id ? 'block' : 'none';
  39636. }
  39637. mode = id;
  39638. } //
  39639. var beginTime = (performance || Date).now(),
  39640. prevTime = beginTime,
  39641. frames = 0;
  39642. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  39643. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  39644. if (self.performance && self.performance.memory) {
  39645. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  39646. }
  39647. showPanel(0);
  39648. return {
  39649. REVISION: 16,
  39650. dom: container,
  39651. addPanel: addPanel,
  39652. showPanel: showPanel,
  39653. begin: function () {
  39654. beginTime = (performance || Date).now();
  39655. },
  39656. end: function () {
  39657. frames++;
  39658. var time = (performance || Date).now();
  39659. msPanel.update(time - beginTime, 200);
  39660. if (time >= prevTime + 1000) {
  39661. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  39662. prevTime = time;
  39663. frames = 0;
  39664. if (memPanel) {
  39665. var memory = performance.memory;
  39666. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  39667. }
  39668. }
  39669. return time;
  39670. },
  39671. update: function () {
  39672. beginTime = this.end();
  39673. },
  39674. // Backwards Compatibility
  39675. domElement: container,
  39676. setMode: showPanel
  39677. };
  39678. };
  39679. Stats.Panel = function (name, fg, bg) {
  39680. var min = Infinity,
  39681. max = 0,
  39682. round = Math.round;
  39683. var PR = round(window.devicePixelRatio || 1);
  39684. var WIDTH = 80 * PR,
  39685. HEIGHT = 48 * PR,
  39686. TEXT_X = 3 * PR,
  39687. TEXT_Y = 2 * PR,
  39688. GRAPH_X = 3 * PR,
  39689. GRAPH_Y = 15 * PR,
  39690. GRAPH_WIDTH = 74 * PR,
  39691. GRAPH_HEIGHT = 30 * PR;
  39692. var canvas = document.createElement('canvas');
  39693. canvas.width = WIDTH;
  39694. canvas.height = HEIGHT;
  39695. canvas.style.cssText = 'width:80px;height:48px';
  39696. var context = canvas.getContext('2d');
  39697. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  39698. context.textBaseline = 'top';
  39699. context.fillStyle = bg;
  39700. context.fillRect(0, 0, WIDTH, HEIGHT);
  39701. context.fillStyle = fg;
  39702. context.fillText(name, TEXT_X, TEXT_Y);
  39703. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  39704. context.fillStyle = bg;
  39705. context.globalAlpha = 0.9;
  39706. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  39707. return {
  39708. dom: canvas,
  39709. update: function (value, maxValue) {
  39710. min = Math.min(min, value);
  39711. max = Math.max(max, value);
  39712. context.fillStyle = bg;
  39713. context.globalAlpha = 1;
  39714. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  39715. context.fillStyle = fg;
  39716. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  39717. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  39718. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  39719. context.fillStyle = bg;
  39720. context.globalAlpha = 0.9;
  39721. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  39722. }
  39723. };
  39724. };
  39725. var _default = Stats;
  39726. exports.default = _default;
  39727. },{}],"customMaterial.js":[function(require,module,exports) {
  39728. "use strict";
  39729. var _index = require("../src/index.js");
  39730. var _three = require("three");
  39731. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  39732. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  39733. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  39734. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  39735. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  39736. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  39737. var camera, controls, scene, renderer, tiles, orthoCamera;
  39738. var offsetParent, box, dirLight, statsContainer;
  39739. var stats;
  39740. var DEFAULT = 0;
  39741. var GRADIENT = 1;
  39742. var TOPOGRAPHIC_LINES = 2;
  39743. var LIGHTING = 3;
  39744. var params = {
  39745. 'material': DEFAULT,
  39746. 'orthographic': false,
  39747. 'rebuild': initTiles
  39748. };
  39749. var gradientShader = {
  39750. vertexShader:
  39751. /* glsl */
  39752. "\n\t\tvarying vec3 wPosition;\n\t\tvoid main() {\n\n\t\t\t#include <begin_vertex>\n\t\t\t#include <project_vertex>\n\t\t\twPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;\n\n\t\t}\n\t",
  39753. fragmentShader:
  39754. /* glsl */
  39755. "\n\t\tvarying vec3 wPosition;\n\t\tvoid main() {\n\n\t\t\tfloat minVal = - 30.0;\n\t\t\tfloat maxVal = 30.0;\n\n\t\t\tfloat val = ( wPosition.y - minVal ) / ( maxVal - minVal );\n\n\t\t\tvec4 color1 = vec4( 0.149, 0.196, 0.219, 1.0 ) * 0.5;\n\t\t\tvec4 color2 = vec4( 1.0 );\n\n\t\t\tgl_FragColor = mix( color1, color2, val );\n\n\t\t}\n\t"
  39756. };
  39757. var topoShader = {
  39758. extensions: {
  39759. derivatives: true
  39760. },
  39761. vertexShader:
  39762. /* glsl */
  39763. "\n\t\tvarying vec3 wPosition;\n\t\tvarying vec3 vViewPosition;\n\t\tvoid main() {\n\n\t\t\t#include <begin_vertex>\n\t\t\t#include <project_vertex>\n\t\t\twPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;\n\t\t\tvViewPosition = - mvPosition.xyz;\n\n\t\t}\n\t",
  39764. fragmentShader:
  39765. /* glsl */
  39766. "\n\t\tvarying vec3 wPosition;\n\t\tvarying vec3 vViewPosition;\n\t\tvoid main() {\n\n\t\t\t// lighting\n\t\t\tvec3 fdx = vec3( dFdx( wPosition.x ), dFdx( wPosition.y ), dFdx( wPosition.z ) );\n\t\t\tvec3 fdy = vec3( dFdy( wPosition.x ), dFdy( wPosition.y ), dFdy( wPosition.z ) );\n\t\t\tvec3 worldNormal = normalize( cross( fdx, fdy ) );\n\n\t\t\tfloat lighting =\n\t\t\t\t0.4 +\n\t\t\t\tclamp( dot( worldNormal, vec3( 1.0, 1.0, 1.0 ) ), 0.0, 1.0 ) * 0.5 +\n\t\t\t\tclamp( dot( worldNormal, vec3( - 1.0, 1.0, - 1.0 ) ), 0.0, 1.0 ) * 0.3;\n\n\t\t\t// thickness scale\n\t\t\tfloat upwardness = dot( worldNormal, vec3( 0.0, 1.0, 0.0 ) );\n\t\t\tfloat yInv = clamp( 1.0 - abs( upwardness ), 0.0, 1.0 );\n\t\t\tfloat thicknessScale = pow( yInv, 0.4 );\n\t\t\tthicknessScale *= 0.25 + 0.5 * ( vViewPosition.z + 1.0 ) / 2.0;\n\n\t\t\t// thickness\n\t\t\tfloat thickness = 0.01 * thicknessScale;\n\t\t\tfloat thickness2 = thickness / 2.0;\n\t\t\tfloat m = mod( wPosition.y, 3.0 );\n\n\t\t\t// soften edge\n\t\t\tfloat center = thickness2;\n\t\t\tfloat dist = clamp( abs( m - thickness2 ) / thickness2, 0.0, 1.0 );\n\n\t\t\tvec4 topoColor = vec4( 0.149, 0.196, 0.219, 1.0 ) * 0.5;\n\t\t\tgl_FragColor = mix( topoColor * lighting, vec4( lighting ), dist );\n\n\t\t}\n\t"
  39767. };
  39768. init();
  39769. animate();
  39770. function updateMaterial(scene) {
  39771. var materialIndex = parseFloat(params.material);
  39772. scene.traverse(function (c) {
  39773. if (c.isMesh) {
  39774. c.material.dispose();
  39775. switch (materialIndex) {
  39776. case DEFAULT:
  39777. c.material = c.originalMaterial;
  39778. c.material.side = 2;
  39779. c.receiveShadow = false;
  39780. c.castShadow = false;
  39781. break;
  39782. case GRADIENT:
  39783. c.material = new _three.ShaderMaterial(gradientShader);
  39784. c.material.side = 2;
  39785. c.receiveShadow = false;
  39786. c.castShadow = false;
  39787. break;
  39788. case TOPOGRAPHIC_LINES:
  39789. c.material = new _three.ShaderMaterial(topoShader);
  39790. c.material.side = 2;
  39791. c.material.flatShading = true;
  39792. c.receiveShadow = false;
  39793. c.castShadow = false;
  39794. break;
  39795. case LIGHTING:
  39796. c.material = new _three.MeshStandardMaterial();
  39797. c.material.side = 2;
  39798. c.receiveShadow = true;
  39799. c.castShadow = true;
  39800. }
  39801. }
  39802. });
  39803. }
  39804. function onLoadModel(scene) {
  39805. scene.traverse(function (c) {
  39806. if (c.isMesh) {
  39807. c.originalMaterial = c.material;
  39808. }
  39809. });
  39810. updateMaterial(scene);
  39811. }
  39812. function onDisposeModel(scene) {
  39813. scene.traverse(function (c) {
  39814. if (c.isMesh) {
  39815. c.material.dispose();
  39816. }
  39817. });
  39818. }
  39819. function initTiles() {
  39820. if (tiles) {
  39821. tiles.group.parent.remove(tiles.group);
  39822. tiles.dispose();
  39823. }
  39824. var url = window.location.hash.replace(/^#/, '') || '../data/tileset.json';
  39825. tiles = new _index.TilesRenderer(url);
  39826. tiles.errorTarget = 2;
  39827. tiles.onLoadModel = onLoadModel;
  39828. tiles.onDisposeModel = onDisposeModel;
  39829. offsetParent.add(tiles.group);
  39830. }
  39831. function init() {
  39832. scene = new _three.Scene(); // primary camera view
  39833. renderer = new _three.WebGLRenderer({
  39834. antialias: true
  39835. });
  39836. renderer.setPixelRatio(window.devicePixelRatio);
  39837. renderer.setSize(window.innerWidth, window.innerHeight);
  39838. renderer.setClearColor(0x151c1f);
  39839. renderer.shadowMap.enabled = true;
  39840. renderer.shadowMap.type = _three.PCFSoftShadowMap;
  39841. renderer.outputEncoding = _three.sRGBEncoding;
  39842. document.body.appendChild(renderer.domElement);
  39843. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  39844. camera.position.set(400, 400, 400);
  39845. orthoCamera = new _three.OrthographicCamera(); // controls
  39846. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  39847. controls.screenSpacePanning = false;
  39848. controls.minDistance = 1;
  39849. controls.maxDistance = 2000; // lights
  39850. dirLight = new _three.DirectionalLight(0xffffff, 1.25);
  39851. dirLight.position.set(1, 2, 3).multiplyScalar(40);
  39852. dirLight.castShadow = true;
  39853. dirLight.shadow.bias = -0.01;
  39854. dirLight.shadow.mapSize.setScalar(2048);
  39855. var shadowCam = dirLight.shadow.camera;
  39856. shadowCam.left = -200;
  39857. shadowCam.bottom = -200;
  39858. shadowCam.right = 200;
  39859. shadowCam.top = 200;
  39860. shadowCam.updateProjectionMatrix();
  39861. scene.add(dirLight);
  39862. var ambLight = new _three.AmbientLight(0xffffff, 0.05);
  39863. scene.add(ambLight);
  39864. box = new _three.Box3();
  39865. offsetParent = new _three.Group();
  39866. scene.add(offsetParent);
  39867. initTiles();
  39868. onWindowResize();
  39869. window.addEventListener('resize', onWindowResize, false); // GUI
  39870. var gui = new dat.GUI();
  39871. gui.width = 300;
  39872. gui.add(params, 'orthographic');
  39873. gui.add(params, 'material', {
  39874. DEFAULT: DEFAULT,
  39875. GRADIENT: GRADIENT,
  39876. TOPOGRAPHIC_LINES: TOPOGRAPHIC_LINES,
  39877. LIGHTING: LIGHTING
  39878. }).onChange(function () {
  39879. tiles.forEachLoadedModel(updateMaterial);
  39880. });
  39881. gui.add(params, 'rebuild');
  39882. gui.open(); // Stats
  39883. stats = new _statsModule.default();
  39884. stats.showPanel(0);
  39885. document.body.appendChild(stats.dom);
  39886. statsContainer = document.createElement('div');
  39887. statsContainer.style.position = 'absolute';
  39888. statsContainer.style.top = 0;
  39889. statsContainer.style.left = 0;
  39890. statsContainer.style.color = 'white';
  39891. statsContainer.style.width = '100%';
  39892. statsContainer.style.textAlign = 'center';
  39893. statsContainer.style.padding = '5px';
  39894. statsContainer.style.pointerEvents = 'none';
  39895. statsContainer.style.lineHeight = '1.5em';
  39896. document.body.appendChild(statsContainer);
  39897. }
  39898. function onWindowResize() {
  39899. camera.aspect = window.innerWidth / window.innerHeight;
  39900. renderer.setPixelRatio(window.devicePixelRatio);
  39901. renderer.setSize(window.innerWidth, window.innerHeight);
  39902. camera.updateProjectionMatrix();
  39903. updateOrthoCamera();
  39904. }
  39905. function updateOrthoCamera() {
  39906. orthoCamera.position.copy(camera.position);
  39907. orthoCamera.rotation.copy(camera.rotation);
  39908. var scale = camera.position.distanceTo(controls.target) / 2.0;
  39909. var aspect = window.innerWidth / window.innerHeight;
  39910. orthoCamera.left = -aspect * scale;
  39911. orthoCamera.right = aspect * scale;
  39912. orthoCamera.bottom = -scale;
  39913. orthoCamera.top = scale;
  39914. orthoCamera.near = camera.near;
  39915. orthoCamera.far = camera.far;
  39916. orthoCamera.updateProjectionMatrix();
  39917. }
  39918. function animate() {
  39919. requestAnimationFrame(animate);
  39920. if (params.orthographic) {
  39921. tiles.deleteCamera(camera);
  39922. tiles.setCamera(orthoCamera);
  39923. tiles.setResolutionFromRenderer(orthoCamera, renderer);
  39924. } else {
  39925. tiles.deleteCamera(orthoCamera);
  39926. tiles.setCamera(camera);
  39927. tiles.setResolutionFromRenderer(camera, renderer);
  39928. }
  39929. offsetParent.rotation.set(0, 0, 0);
  39930. if (params.up === '-Z') {
  39931. offsetParent.rotation.x = Math.PI / 2;
  39932. }
  39933. offsetParent.updateMatrixWorld(true); // update tiles center
  39934. if (tiles.getBounds(box)) {
  39935. box.getCenter(tiles.group.position);
  39936. tiles.group.position.multiplyScalar(-1);
  39937. } // update tiles
  39938. window.tiles = tiles;
  39939. camera.updateMatrixWorld();
  39940. orthoCamera.updateMatrixWorld();
  39941. tiles.update();
  39942. render();
  39943. stats.update();
  39944. }
  39945. function render() {
  39946. updateOrthoCamera();
  39947. statsContainer.innerText = "Geometries: ".concat(renderer.info.memory.geometries, " ") + "Textures: ".concat(renderer.info.memory.textures, " ") + "Programs: ".concat(renderer.info.programs.length, " ");
  39948. renderer.render(scene, params.orthographic ? orthoCamera : camera);
  39949. }
  39950. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  39951. var global = arguments[3];
  39952. var OVERLAY_ID = '__parcel__error__overlay__';
  39953. var OldModule = module.bundle.Module;
  39954. function Module(moduleName) {
  39955. OldModule.call(this, moduleName);
  39956. this.hot = {
  39957. data: module.bundle.hotData,
  39958. _acceptCallbacks: [],
  39959. _disposeCallbacks: [],
  39960. accept: function (fn) {
  39961. this._acceptCallbacks.push(fn || function () {});
  39962. },
  39963. dispose: function (fn) {
  39964. this._disposeCallbacks.push(fn);
  39965. }
  39966. };
  39967. module.bundle.hotData = null;
  39968. }
  39969. module.bundle.Module = Module;
  39970. var checkedAssets, assetsToAccept;
  39971. var parent = module.bundle.parent;
  39972. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  39973. var hostname = "" || location.hostname;
  39974. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  39975. var ws = new WebSocket(protocol + '://' + hostname + ':' + "62159" + '/');
  39976. ws.onmessage = function (event) {
  39977. checkedAssets = {};
  39978. assetsToAccept = [];
  39979. var data = JSON.parse(event.data);
  39980. if (data.type === 'update') {
  39981. var handled = false;
  39982. data.assets.forEach(function (asset) {
  39983. if (!asset.isNew) {
  39984. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  39985. if (didAccept) {
  39986. handled = true;
  39987. }
  39988. }
  39989. }); // Enable HMR for CSS by default.
  39990. handled = handled || data.assets.every(function (asset) {
  39991. return asset.type === 'css' && asset.generated.js;
  39992. });
  39993. if (handled) {
  39994. console.clear();
  39995. data.assets.forEach(function (asset) {
  39996. hmrApply(global.parcelRequire, asset);
  39997. });
  39998. assetsToAccept.forEach(function (v) {
  39999. hmrAcceptRun(v[0], v[1]);
  40000. });
  40001. } else if (location.reload) {
  40002. // `location` global exists in a web worker context but lacks `.reload()` function.
  40003. location.reload();
  40004. }
  40005. }
  40006. if (data.type === 'reload') {
  40007. ws.close();
  40008. ws.onclose = function () {
  40009. location.reload();
  40010. };
  40011. }
  40012. if (data.type === 'error-resolved') {
  40013. console.log('[parcel] ✨ Error resolved');
  40014. removeErrorOverlay();
  40015. }
  40016. if (data.type === 'error') {
  40017. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  40018. removeErrorOverlay();
  40019. var overlay = createErrorOverlay(data);
  40020. document.body.appendChild(overlay);
  40021. }
  40022. };
  40023. }
  40024. function removeErrorOverlay() {
  40025. var overlay = document.getElementById(OVERLAY_ID);
  40026. if (overlay) {
  40027. overlay.remove();
  40028. }
  40029. }
  40030. function createErrorOverlay(data) {
  40031. var overlay = document.createElement('div');
  40032. overlay.id = OVERLAY_ID; // html encode message and stack trace
  40033. var message = document.createElement('div');
  40034. var stackTrace = document.createElement('pre');
  40035. message.innerText = data.error.message;
  40036. stackTrace.innerText = data.error.stack;
  40037. overlay.innerHTML = '<div style="background: black; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; opacity: 0.85; font-family: Menlo, Consolas, monospace; z-index: 9999;">' + '<span style="background: red; padding: 2px 4px; border-radius: 2px;">ERROR</span>' + '<span style="top: 2px; margin-left: 5px; position: relative;">🚨</span>' + '<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">' + message.innerHTML + '</div>' + '<pre>' + stackTrace.innerHTML + '</pre>' + '</div>';
  40038. return overlay;
  40039. }
  40040. function getParents(bundle, id) {
  40041. var modules = bundle.modules;
  40042. if (!modules) {
  40043. return [];
  40044. }
  40045. var parents = [];
  40046. var k, d, dep;
  40047. for (k in modules) {
  40048. for (d in modules[k][1]) {
  40049. dep = modules[k][1][d];
  40050. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  40051. parents.push(k);
  40052. }
  40053. }
  40054. }
  40055. if (bundle.parent) {
  40056. parents = parents.concat(getParents(bundle.parent, id));
  40057. }
  40058. return parents;
  40059. }
  40060. function hmrApply(bundle, asset) {
  40061. var modules = bundle.modules;
  40062. if (!modules) {
  40063. return;
  40064. }
  40065. if (modules[asset.id] || !bundle.parent) {
  40066. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  40067. asset.isNew = !modules[asset.id];
  40068. modules[asset.id] = [fn, asset.deps];
  40069. } else if (bundle.parent) {
  40070. hmrApply(bundle.parent, asset);
  40071. }
  40072. }
  40073. function hmrAcceptCheck(bundle, id) {
  40074. var modules = bundle.modules;
  40075. if (!modules) {
  40076. return;
  40077. }
  40078. if (!modules[id] && bundle.parent) {
  40079. return hmrAcceptCheck(bundle.parent, id);
  40080. }
  40081. if (checkedAssets[id]) {
  40082. return;
  40083. }
  40084. checkedAssets[id] = true;
  40085. var cached = bundle.cache[id];
  40086. assetsToAccept.push([bundle, id]);
  40087. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  40088. return true;
  40089. }
  40090. return getParents(global.parcelRequire, id).some(function (id) {
  40091. return hmrAcceptCheck(global.parcelRequire, id);
  40092. });
  40093. }
  40094. function hmrAcceptRun(bundle, id) {
  40095. var cached = bundle.cache[id];
  40096. bundle.hotData = {};
  40097. if (cached) {
  40098. cached.hot.data = bundle.hotData;
  40099. }
  40100. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  40101. cached.hot._disposeCallbacks.forEach(function (cb) {
  40102. cb(bundle.hotData);
  40103. });
  40104. }
  40105. delete bundle.cache[id];
  40106. bundle(id);
  40107. cached = bundle.cache[id];
  40108. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  40109. cached.hot._acceptCallbacks.forEach(function (cb) {
  40110. cb();
  40111. });
  40112. return true;
  40113. }
  40114. }
  40115. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","customMaterial.js"], null)
  40116. //# sourceMappingURL=customMaterial.dd39ecee.js.map