example.e31bb0bc.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754
  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.ArrowHelper = ArrowHelper;
  114. exports.Audio = Audio;
  115. exports.AudioAnalyser = AudioAnalyser;
  116. exports.AudioListener = AudioListener;
  117. exports.AudioLoader = AudioLoader;
  118. exports.AxesHelper = AxesHelper;
  119. exports.AxisHelper = AxisHelper;
  120. exports.BinaryTextureLoader = BinaryTextureLoader;
  121. exports.Bone = Bone;
  122. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  123. exports.BoundingBoxHelper = BoundingBoxHelper;
  124. exports.Box2 = Box2;
  125. exports.Box3 = Box3;
  126. exports.Box3Helper = Box3Helper;
  127. exports.BoxHelper = BoxHelper;
  128. exports.BufferAttribute = BufferAttribute;
  129. exports.BufferGeometry = BufferGeometry;
  130. exports.BufferGeometryLoader = BufferGeometryLoader;
  131. exports.Camera = Camera;
  132. exports.CameraHelper = CameraHelper;
  133. exports.CanvasRenderer = CanvasRenderer;
  134. exports.CanvasTexture = CanvasTexture;
  135. exports.CatmullRomCurve3 = CatmullRomCurve3;
  136. exports.CircleBufferGeometry = CircleBufferGeometry;
  137. exports.CircleGeometry = CircleGeometry;
  138. exports.Clock = Clock;
  139. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  140. exports.Color = Color;
  141. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  142. exports.CompressedTexture = CompressedTexture;
  143. exports.CompressedTextureLoader = CompressedTextureLoader;
  144. exports.ConeBufferGeometry = ConeBufferGeometry;
  145. exports.ConeGeometry = ConeGeometry;
  146. exports.CubeCamera = CubeCamera;
  147. exports.CubeTexture = CubeTexture;
  148. exports.CubeTextureLoader = CubeTextureLoader;
  149. exports.CubicBezierCurve = CubicBezierCurve;
  150. exports.CubicBezierCurve3 = CubicBezierCurve3;
  151. exports.CubicInterpolant = CubicInterpolant;
  152. exports.Curve = Curve;
  153. exports.CurvePath = CurvePath;
  154. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  155. exports.CylinderGeometry = CylinderGeometry;
  156. exports.Cylindrical = Cylindrical;
  157. exports.DataTexture = DataTexture;
  158. exports.DataTexture2DArray = DataTexture2DArray;
  159. exports.DataTexture3D = DataTexture3D;
  160. exports.DataTextureLoader = DataTextureLoader;
  161. exports.DepthTexture = DepthTexture;
  162. exports.DirectionalLight = DirectionalLight;
  163. exports.DirectionalLightHelper = DirectionalLightHelper;
  164. exports.DirectionalLightShadow = DirectionalLightShadow;
  165. exports.DiscreteInterpolant = DiscreteInterpolant;
  166. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  167. exports.DodecahedronGeometry = DodecahedronGeometry;
  168. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  169. exports.EdgesGeometry = EdgesGeometry;
  170. exports.EdgesHelper = EdgesHelper;
  171. exports.EllipseCurve = EllipseCurve;
  172. exports.Euler = Euler;
  173. exports.EventDispatcher = EventDispatcher;
  174. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  175. exports.ExtrudeGeometry = ExtrudeGeometry;
  176. exports.Face3 = Face3;
  177. exports.Face4 = Face4;
  178. exports.FileLoader = FileLoader;
  179. exports.Float32Attribute = Float32Attribute;
  180. exports.Float32BufferAttribute = Float32BufferAttribute;
  181. exports.Float64Attribute = Float64Attribute;
  182. exports.Float64BufferAttribute = Float64BufferAttribute;
  183. exports.Fog = Fog;
  184. exports.FogExp2 = FogExp2;
  185. exports.Font = Font;
  186. exports.FontLoader = FontLoader;
  187. exports.Frustum = Frustum;
  188. exports.Geometry = Geometry;
  189. exports.GridHelper = GridHelper;
  190. exports.Group = Group;
  191. exports.HemisphereLight = HemisphereLight;
  192. exports.HemisphereLightHelper = HemisphereLightHelper;
  193. exports.HemisphereLightProbe = HemisphereLightProbe;
  194. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  195. exports.IcosahedronGeometry = IcosahedronGeometry;
  196. exports.ImageBitmapLoader = ImageBitmapLoader;
  197. exports.ImageLoader = ImageLoader;
  198. exports.ImmediateRenderObject = ImmediateRenderObject;
  199. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  200. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  201. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  202. exports.InstancedMesh = InstancedMesh;
  203. exports.Int16Attribute = Int16Attribute;
  204. exports.Int16BufferAttribute = Int16BufferAttribute;
  205. exports.Int32Attribute = Int32Attribute;
  206. exports.Int32BufferAttribute = Int32BufferAttribute;
  207. exports.Int8Attribute = Int8Attribute;
  208. exports.Int8BufferAttribute = Int8BufferAttribute;
  209. exports.InterleavedBuffer = InterleavedBuffer;
  210. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  211. exports.Interpolant = Interpolant;
  212. exports.JSONLoader = JSONLoader;
  213. exports.KeyframeTrack = KeyframeTrack;
  214. exports.LOD = LOD;
  215. exports.LatheBufferGeometry = LatheBufferGeometry;
  216. exports.LatheGeometry = LatheGeometry;
  217. exports.Layers = Layers;
  218. exports.LensFlare = LensFlare;
  219. exports.Light = Light;
  220. exports.LightProbe = LightProbe;
  221. exports.LightShadow = LightShadow;
  222. exports.Line = Line;
  223. exports.Line3 = Line3;
  224. exports.LineBasicMaterial = LineBasicMaterial;
  225. exports.LineCurve = LineCurve;
  226. exports.LineCurve3 = LineCurve3;
  227. exports.LineDashedMaterial = LineDashedMaterial;
  228. exports.LineLoop = LineLoop;
  229. exports.LineSegments = LineSegments;
  230. exports.LinearInterpolant = LinearInterpolant;
  231. exports.Loader = Loader;
  232. exports.LoadingManager = LoadingManager;
  233. exports.Material = Material;
  234. exports.MaterialLoader = MaterialLoader;
  235. exports.Matrix3 = Matrix3;
  236. exports.Matrix4 = Matrix4;
  237. exports.Mesh = Mesh;
  238. exports.MeshBasicMaterial = MeshBasicMaterial;
  239. exports.MeshDepthMaterial = MeshDepthMaterial;
  240. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  241. exports.MeshFaceMaterial = MeshFaceMaterial;
  242. exports.MeshLambertMaterial = MeshLambertMaterial;
  243. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  244. exports.MeshNormalMaterial = MeshNormalMaterial;
  245. exports.MeshPhongMaterial = MeshPhongMaterial;
  246. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  247. exports.MeshStandardMaterial = MeshStandardMaterial;
  248. exports.MeshToonMaterial = MeshToonMaterial;
  249. exports.MultiMaterial = MultiMaterial;
  250. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  251. exports.Object3D = Object3D;
  252. exports.ObjectLoader = ObjectLoader;
  253. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  254. exports.OctahedronGeometry = OctahedronGeometry;
  255. exports.OrthographicCamera = OrthographicCamera;
  256. exports.PMREMGenerator = PMREMGenerator;
  257. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  258. exports.ParametricGeometry = ParametricGeometry;
  259. exports.Particle = Particle;
  260. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  261. exports.ParticleSystem = ParticleSystem;
  262. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  263. exports.Path = Path;
  264. exports.PerspectiveCamera = PerspectiveCamera;
  265. exports.Plane = Plane;
  266. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  267. exports.PlaneGeometry = PlaneGeometry;
  268. exports.PlaneHelper = PlaneHelper;
  269. exports.PointCloud = PointCloud;
  270. exports.PointCloudMaterial = PointCloudMaterial;
  271. exports.PointLight = PointLight;
  272. exports.PointLightHelper = PointLightHelper;
  273. exports.Points = Points;
  274. exports.PointsMaterial = PointsMaterial;
  275. exports.PolarGridHelper = PolarGridHelper;
  276. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  277. exports.PolyhedronGeometry = PolyhedronGeometry;
  278. exports.PositionalAudio = PositionalAudio;
  279. exports.PropertyBinding = PropertyBinding;
  280. exports.PropertyMixer = PropertyMixer;
  281. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  282. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  283. exports.Quaternion = Quaternion;
  284. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  285. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  286. exports.RawShaderMaterial = RawShaderMaterial;
  287. exports.Ray = Ray;
  288. exports.Raycaster = Raycaster;
  289. exports.RectAreaLight = RectAreaLight;
  290. exports.RingBufferGeometry = RingBufferGeometry;
  291. exports.RingGeometry = RingGeometry;
  292. exports.Scene = Scene;
  293. exports.ShaderMaterial = ShaderMaterial;
  294. exports.ShadowMaterial = ShadowMaterial;
  295. exports.Shape = Shape;
  296. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  297. exports.ShapeGeometry = ShapeGeometry;
  298. exports.ShapePath = ShapePath;
  299. exports.Skeleton = Skeleton;
  300. exports.SkeletonHelper = SkeletonHelper;
  301. exports.SkinnedMesh = SkinnedMesh;
  302. exports.Sphere = Sphere;
  303. exports.SphereBufferGeometry = SphereBufferGeometry;
  304. exports.SphereGeometry = SphereGeometry;
  305. exports.Spherical = Spherical;
  306. exports.SphericalHarmonics3 = SphericalHarmonics3;
  307. exports.Spline = Spline;
  308. exports.SplineCurve = SplineCurve;
  309. exports.SplineCurve3 = SplineCurve3;
  310. exports.SpotLight = SpotLight;
  311. exports.SpotLightHelper = SpotLightHelper;
  312. exports.SpotLightShadow = SpotLightShadow;
  313. exports.Sprite = Sprite;
  314. exports.SpriteMaterial = SpriteMaterial;
  315. exports.StereoCamera = StereoCamera;
  316. exports.StringKeyframeTrack = StringKeyframeTrack;
  317. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  318. exports.TetrahedronGeometry = TetrahedronGeometry;
  319. exports.TextBufferGeometry = TextBufferGeometry;
  320. exports.TextGeometry = TextGeometry;
  321. exports.Texture = Texture;
  322. exports.TextureLoader = TextureLoader;
  323. exports.TorusBufferGeometry = TorusBufferGeometry;
  324. exports.TorusGeometry = TorusGeometry;
  325. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  326. exports.TorusKnotGeometry = TorusKnotGeometry;
  327. exports.Triangle = Triangle;
  328. exports.TubeBufferGeometry = TubeBufferGeometry;
  329. exports.TubeGeometry = TubeGeometry;
  330. exports.Uint16Attribute = Uint16Attribute;
  331. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  332. exports.Uint32Attribute = Uint32Attribute;
  333. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  334. exports.Uint8Attribute = Uint8Attribute;
  335. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  336. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  337. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  338. exports.Uniform = Uniform;
  339. exports.Vector2 = Vector2;
  340. exports.Vector3 = Vector3;
  341. exports.Vector4 = Vector4;
  342. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  343. exports.Vertex = Vertex;
  344. exports.VideoTexture = VideoTexture;
  345. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  346. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  347. exports.WebGLRenderTarget = WebGLRenderTarget;
  348. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  349. exports.WebGLRenderer = WebGLRenderer;
  350. exports.WebGLUtils = WebGLUtils;
  351. exports.WireframeGeometry = WireframeGeometry;
  352. exports.WireframeHelper = WireframeHelper;
  353. exports.XHRLoader = XHRLoader;
  354. 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.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.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.KeepStencilOp = exports.InvertStencilOp = exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.HalfFloatType = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.FrontSide = exports.FrontFaceDirectionCW = exports.FrontFaceDirectionCCW = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.DynamicReadUsage = exports.DynamicDrawUsage = exports.DynamicCopyUsage = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ClampToEdgeWrapping = exports.CineonToneMapping = exports.Cache = exports.ByteType = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AudioContext = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  355. exports.UniformsLib = exports.Uncharted2ToneMapping = exports.UVMapping = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = 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.SphericalReflectionMapping = exports.SmoothShading = exports.ShortType = exports.ShapeUtils = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = 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.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedIntegerFormat = exports.RedFormat = 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 = 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.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.ObjectSpaceNormalMap = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = void 0;
  356. exports.sRGBEncoding = exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.VertexColors = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = void 0;
  357. // Polyfills
  358. if (Number.EPSILON === undefined) {
  359. Number.EPSILON = Math.pow(2, -52);
  360. }
  361. if (Number.isInteger === undefined) {
  362. // Missing in IE
  363. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  364. Number.isInteger = function (value) {
  365. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  366. };
  367. } //
  368. if (Math.sign === undefined) {
  369. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  370. Math.sign = function (x) {
  371. return x < 0 ? -1 : x > 0 ? 1 : +x;
  372. };
  373. }
  374. if ('name' in Function.prototype === false) {
  375. // Missing in IE
  376. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  377. Object.defineProperty(Function.prototype, 'name', {
  378. get: function () {
  379. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  380. }
  381. });
  382. }
  383. if (Object.assign === undefined) {
  384. // Missing in IE
  385. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  386. Object.assign = function (target) {
  387. if (target === undefined || target === null) {
  388. throw new TypeError('Cannot convert undefined or null to object');
  389. }
  390. var output = Object(target);
  391. for (var index = 1; index < arguments.length; index++) {
  392. var source = arguments[index];
  393. if (source !== undefined && source !== null) {
  394. for (var nextKey in source) {
  395. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  396. output[nextKey] = source[nextKey];
  397. }
  398. }
  399. }
  400. }
  401. return output;
  402. };
  403. }
  404. var REVISION = '115';
  405. exports.REVISION = REVISION;
  406. var MOUSE = {
  407. LEFT: 0,
  408. MIDDLE: 1,
  409. RIGHT: 2,
  410. ROTATE: 0,
  411. DOLLY: 1,
  412. PAN: 2
  413. };
  414. exports.MOUSE = MOUSE;
  415. var TOUCH = {
  416. ROTATE: 0,
  417. PAN: 1,
  418. DOLLY_PAN: 2,
  419. DOLLY_ROTATE: 3
  420. };
  421. exports.TOUCH = TOUCH;
  422. var CullFaceNone = 0;
  423. exports.CullFaceNone = CullFaceNone;
  424. var CullFaceBack = 1;
  425. exports.CullFaceBack = CullFaceBack;
  426. var CullFaceFront = 2;
  427. exports.CullFaceFront = CullFaceFront;
  428. var CullFaceFrontBack = 3;
  429. exports.CullFaceFrontBack = CullFaceFrontBack;
  430. var FrontFaceDirectionCW = 0;
  431. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  432. var FrontFaceDirectionCCW = 1;
  433. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  434. var BasicShadowMap = 0;
  435. exports.BasicShadowMap = BasicShadowMap;
  436. var PCFShadowMap = 1;
  437. exports.PCFShadowMap = PCFShadowMap;
  438. var PCFSoftShadowMap = 2;
  439. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  440. var VSMShadowMap = 3;
  441. exports.VSMShadowMap = VSMShadowMap;
  442. var FrontSide = 0;
  443. exports.FrontSide = FrontSide;
  444. var BackSide = 1;
  445. exports.BackSide = BackSide;
  446. var DoubleSide = 2;
  447. exports.DoubleSide = DoubleSide;
  448. var FlatShading = 1;
  449. exports.FlatShading = FlatShading;
  450. var SmoothShading = 2;
  451. exports.SmoothShading = SmoothShading;
  452. var NoBlending = 0;
  453. exports.NoBlending = NoBlending;
  454. var NormalBlending = 1;
  455. exports.NormalBlending = NormalBlending;
  456. var AdditiveBlending = 2;
  457. exports.AdditiveBlending = AdditiveBlending;
  458. var SubtractiveBlending = 3;
  459. exports.SubtractiveBlending = SubtractiveBlending;
  460. var MultiplyBlending = 4;
  461. exports.MultiplyBlending = MultiplyBlending;
  462. var CustomBlending = 5;
  463. exports.CustomBlending = CustomBlending;
  464. var AddEquation = 100;
  465. exports.AddEquation = AddEquation;
  466. var SubtractEquation = 101;
  467. exports.SubtractEquation = SubtractEquation;
  468. var ReverseSubtractEquation = 102;
  469. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  470. var MinEquation = 103;
  471. exports.MinEquation = MinEquation;
  472. var MaxEquation = 104;
  473. exports.MaxEquation = MaxEquation;
  474. var ZeroFactor = 200;
  475. exports.ZeroFactor = ZeroFactor;
  476. var OneFactor = 201;
  477. exports.OneFactor = OneFactor;
  478. var SrcColorFactor = 202;
  479. exports.SrcColorFactor = SrcColorFactor;
  480. var OneMinusSrcColorFactor = 203;
  481. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  482. var SrcAlphaFactor = 204;
  483. exports.SrcAlphaFactor = SrcAlphaFactor;
  484. var OneMinusSrcAlphaFactor = 205;
  485. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  486. var DstAlphaFactor = 206;
  487. exports.DstAlphaFactor = DstAlphaFactor;
  488. var OneMinusDstAlphaFactor = 207;
  489. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  490. var DstColorFactor = 208;
  491. exports.DstColorFactor = DstColorFactor;
  492. var OneMinusDstColorFactor = 209;
  493. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  494. var SrcAlphaSaturateFactor = 210;
  495. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  496. var NeverDepth = 0;
  497. exports.NeverDepth = NeverDepth;
  498. var AlwaysDepth = 1;
  499. exports.AlwaysDepth = AlwaysDepth;
  500. var LessDepth = 2;
  501. exports.LessDepth = LessDepth;
  502. var LessEqualDepth = 3;
  503. exports.LessEqualDepth = LessEqualDepth;
  504. var EqualDepth = 4;
  505. exports.EqualDepth = EqualDepth;
  506. var GreaterEqualDepth = 5;
  507. exports.GreaterEqualDepth = GreaterEqualDepth;
  508. var GreaterDepth = 6;
  509. exports.GreaterDepth = GreaterDepth;
  510. var NotEqualDepth = 7;
  511. exports.NotEqualDepth = NotEqualDepth;
  512. var MultiplyOperation = 0;
  513. exports.MultiplyOperation = MultiplyOperation;
  514. var MixOperation = 1;
  515. exports.MixOperation = MixOperation;
  516. var AddOperation = 2;
  517. exports.AddOperation = AddOperation;
  518. var NoToneMapping = 0;
  519. exports.NoToneMapping = NoToneMapping;
  520. var LinearToneMapping = 1;
  521. exports.LinearToneMapping = LinearToneMapping;
  522. var ReinhardToneMapping = 2;
  523. exports.ReinhardToneMapping = ReinhardToneMapping;
  524. var Uncharted2ToneMapping = 3;
  525. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  526. var CineonToneMapping = 4;
  527. exports.CineonToneMapping = CineonToneMapping;
  528. var ACESFilmicToneMapping = 5;
  529. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  530. var UVMapping = 300;
  531. exports.UVMapping = UVMapping;
  532. var CubeReflectionMapping = 301;
  533. exports.CubeReflectionMapping = CubeReflectionMapping;
  534. var CubeRefractionMapping = 302;
  535. exports.CubeRefractionMapping = CubeRefractionMapping;
  536. var EquirectangularReflectionMapping = 303;
  537. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  538. var EquirectangularRefractionMapping = 304;
  539. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  540. var SphericalReflectionMapping = 305;
  541. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  542. var CubeUVReflectionMapping = 306;
  543. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  544. var CubeUVRefractionMapping = 307;
  545. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  546. var RepeatWrapping = 1000;
  547. exports.RepeatWrapping = RepeatWrapping;
  548. var ClampToEdgeWrapping = 1001;
  549. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  550. var MirroredRepeatWrapping = 1002;
  551. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  552. var NearestFilter = 1003;
  553. exports.NearestFilter = NearestFilter;
  554. var NearestMipmapNearestFilter = 1004;
  555. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  556. var NearestMipMapNearestFilter = 1004;
  557. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  558. var NearestMipmapLinearFilter = 1005;
  559. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  560. var NearestMipMapLinearFilter = 1005;
  561. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  562. var LinearFilter = 1006;
  563. exports.LinearFilter = LinearFilter;
  564. var LinearMipmapNearestFilter = 1007;
  565. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  566. var LinearMipMapNearestFilter = 1007;
  567. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  568. var LinearMipmapLinearFilter = 1008;
  569. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  570. var LinearMipMapLinearFilter = 1008;
  571. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  572. var UnsignedByteType = 1009;
  573. exports.UnsignedByteType = UnsignedByteType;
  574. var ByteType = 1010;
  575. exports.ByteType = ByteType;
  576. var ShortType = 1011;
  577. exports.ShortType = ShortType;
  578. var UnsignedShortType = 1012;
  579. exports.UnsignedShortType = UnsignedShortType;
  580. var IntType = 1013;
  581. exports.IntType = IntType;
  582. var UnsignedIntType = 1014;
  583. exports.UnsignedIntType = UnsignedIntType;
  584. var FloatType = 1015;
  585. exports.FloatType = FloatType;
  586. var HalfFloatType = 1016;
  587. exports.HalfFloatType = HalfFloatType;
  588. var UnsignedShort4444Type = 1017;
  589. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  590. var UnsignedShort5551Type = 1018;
  591. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  592. var UnsignedShort565Type = 1019;
  593. exports.UnsignedShort565Type = UnsignedShort565Type;
  594. var UnsignedInt248Type = 1020;
  595. exports.UnsignedInt248Type = UnsignedInt248Type;
  596. var AlphaFormat = 1021;
  597. exports.AlphaFormat = AlphaFormat;
  598. var RGBFormat = 1022;
  599. exports.RGBFormat = RGBFormat;
  600. var RGBAFormat = 1023;
  601. exports.RGBAFormat = RGBAFormat;
  602. var LuminanceFormat = 1024;
  603. exports.LuminanceFormat = LuminanceFormat;
  604. var LuminanceAlphaFormat = 1025;
  605. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  606. var RGBEFormat = RGBAFormat;
  607. exports.RGBEFormat = RGBEFormat;
  608. var DepthFormat = 1026;
  609. exports.DepthFormat = DepthFormat;
  610. var DepthStencilFormat = 1027;
  611. exports.DepthStencilFormat = DepthStencilFormat;
  612. var RedFormat = 1028;
  613. exports.RedFormat = RedFormat;
  614. var RedIntegerFormat = 1029;
  615. exports.RedIntegerFormat = RedIntegerFormat;
  616. var RGFormat = 1030;
  617. exports.RGFormat = RGFormat;
  618. var RGIntegerFormat = 1031;
  619. exports.RGIntegerFormat = RGIntegerFormat;
  620. var RGBIntegerFormat = 1032;
  621. exports.RGBIntegerFormat = RGBIntegerFormat;
  622. var RGBAIntegerFormat = 1033;
  623. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  624. var RGB_S3TC_DXT1_Format = 33776;
  625. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  626. var RGBA_S3TC_DXT1_Format = 33777;
  627. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  628. var RGBA_S3TC_DXT3_Format = 33778;
  629. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  630. var RGBA_S3TC_DXT5_Format = 33779;
  631. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  632. var RGB_PVRTC_4BPPV1_Format = 35840;
  633. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  634. var RGB_PVRTC_2BPPV1_Format = 35841;
  635. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  636. var RGBA_PVRTC_4BPPV1_Format = 35842;
  637. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  638. var RGBA_PVRTC_2BPPV1_Format = 35843;
  639. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  640. var RGB_ETC1_Format = 36196;
  641. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  642. var RGB_ETC2_Format = 37492;
  643. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  644. var RGBA_ETC2_EAC_Format = 37496;
  645. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  646. var RGBA_ASTC_4x4_Format = 37808;
  647. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  648. var RGBA_ASTC_5x4_Format = 37809;
  649. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  650. var RGBA_ASTC_5x5_Format = 37810;
  651. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  652. var RGBA_ASTC_6x5_Format = 37811;
  653. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  654. var RGBA_ASTC_6x6_Format = 37812;
  655. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  656. var RGBA_ASTC_8x5_Format = 37813;
  657. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  658. var RGBA_ASTC_8x6_Format = 37814;
  659. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  660. var RGBA_ASTC_8x8_Format = 37815;
  661. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  662. var RGBA_ASTC_10x5_Format = 37816;
  663. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  664. var RGBA_ASTC_10x6_Format = 37817;
  665. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  666. var RGBA_ASTC_10x8_Format = 37818;
  667. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  668. var RGBA_ASTC_10x10_Format = 37819;
  669. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  670. var RGBA_ASTC_12x10_Format = 37820;
  671. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  672. var RGBA_ASTC_12x12_Format = 37821;
  673. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  674. var RGBA_BPTC_Format = 36492;
  675. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  676. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  677. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  678. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  679. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  680. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  681. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  682. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  683. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  684. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  685. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  686. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  687. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  688. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  689. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  690. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  691. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  692. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  693. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  694. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  695. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  696. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  697. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  698. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  699. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  700. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  701. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  702. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  703. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  704. var LoopOnce = 2200;
  705. exports.LoopOnce = LoopOnce;
  706. var LoopRepeat = 2201;
  707. exports.LoopRepeat = LoopRepeat;
  708. var LoopPingPong = 2202;
  709. exports.LoopPingPong = LoopPingPong;
  710. var InterpolateDiscrete = 2300;
  711. exports.InterpolateDiscrete = InterpolateDiscrete;
  712. var InterpolateLinear = 2301;
  713. exports.InterpolateLinear = InterpolateLinear;
  714. var InterpolateSmooth = 2302;
  715. exports.InterpolateSmooth = InterpolateSmooth;
  716. var ZeroCurvatureEnding = 2400;
  717. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  718. var ZeroSlopeEnding = 2401;
  719. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  720. var WrapAroundEnding = 2402;
  721. exports.WrapAroundEnding = WrapAroundEnding;
  722. var TrianglesDrawMode = 0;
  723. exports.TrianglesDrawMode = TrianglesDrawMode;
  724. var TriangleStripDrawMode = 1;
  725. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  726. var TriangleFanDrawMode = 2;
  727. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  728. var LinearEncoding = 3000;
  729. exports.LinearEncoding = LinearEncoding;
  730. var sRGBEncoding = 3001;
  731. exports.sRGBEncoding = sRGBEncoding;
  732. var GammaEncoding = 3007;
  733. exports.GammaEncoding = GammaEncoding;
  734. var RGBEEncoding = 3002;
  735. exports.RGBEEncoding = RGBEEncoding;
  736. var LogLuvEncoding = 3003;
  737. exports.LogLuvEncoding = LogLuvEncoding;
  738. var RGBM7Encoding = 3004;
  739. exports.RGBM7Encoding = RGBM7Encoding;
  740. var RGBM16Encoding = 3005;
  741. exports.RGBM16Encoding = RGBM16Encoding;
  742. var RGBDEncoding = 3006;
  743. exports.RGBDEncoding = RGBDEncoding;
  744. var BasicDepthPacking = 3200;
  745. exports.BasicDepthPacking = BasicDepthPacking;
  746. var RGBADepthPacking = 3201;
  747. exports.RGBADepthPacking = RGBADepthPacking;
  748. var TangentSpaceNormalMap = 0;
  749. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  750. var ObjectSpaceNormalMap = 1;
  751. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  752. var ZeroStencilOp = 0;
  753. exports.ZeroStencilOp = ZeroStencilOp;
  754. var KeepStencilOp = 7680;
  755. exports.KeepStencilOp = KeepStencilOp;
  756. var ReplaceStencilOp = 7681;
  757. exports.ReplaceStencilOp = ReplaceStencilOp;
  758. var IncrementStencilOp = 7682;
  759. exports.IncrementStencilOp = IncrementStencilOp;
  760. var DecrementStencilOp = 7683;
  761. exports.DecrementStencilOp = DecrementStencilOp;
  762. var IncrementWrapStencilOp = 34055;
  763. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  764. var DecrementWrapStencilOp = 34056;
  765. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  766. var InvertStencilOp = 5386;
  767. exports.InvertStencilOp = InvertStencilOp;
  768. var NeverStencilFunc = 512;
  769. exports.NeverStencilFunc = NeverStencilFunc;
  770. var LessStencilFunc = 513;
  771. exports.LessStencilFunc = LessStencilFunc;
  772. var EqualStencilFunc = 514;
  773. exports.EqualStencilFunc = EqualStencilFunc;
  774. var LessEqualStencilFunc = 515;
  775. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  776. var GreaterStencilFunc = 516;
  777. exports.GreaterStencilFunc = GreaterStencilFunc;
  778. var NotEqualStencilFunc = 517;
  779. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  780. var GreaterEqualStencilFunc = 518;
  781. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  782. var AlwaysStencilFunc = 519;
  783. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  784. var StaticDrawUsage = 35044;
  785. exports.StaticDrawUsage = StaticDrawUsage;
  786. var DynamicDrawUsage = 35048;
  787. exports.DynamicDrawUsage = DynamicDrawUsage;
  788. var StreamDrawUsage = 35040;
  789. exports.StreamDrawUsage = StreamDrawUsage;
  790. var StaticReadUsage = 35045;
  791. exports.StaticReadUsage = StaticReadUsage;
  792. var DynamicReadUsage = 35049;
  793. exports.DynamicReadUsage = DynamicReadUsage;
  794. var StreamReadUsage = 35041;
  795. exports.StreamReadUsage = StreamReadUsage;
  796. var StaticCopyUsage = 35046;
  797. exports.StaticCopyUsage = StaticCopyUsage;
  798. var DynamicCopyUsage = 35050;
  799. exports.DynamicCopyUsage = DynamicCopyUsage;
  800. var StreamCopyUsage = 35042;
  801. /**
  802. * https://github.com/mrdoob/eventdispatcher.js/
  803. */
  804. exports.StreamCopyUsage = StreamCopyUsage;
  805. function EventDispatcher() {}
  806. Object.assign(EventDispatcher.prototype, {
  807. addEventListener: function (type, listener) {
  808. if (this._listeners === undefined) this._listeners = {};
  809. var listeners = this._listeners;
  810. if (listeners[type] === undefined) {
  811. listeners[type] = [];
  812. }
  813. if (listeners[type].indexOf(listener) === -1) {
  814. listeners[type].push(listener);
  815. }
  816. },
  817. hasEventListener: function (type, listener) {
  818. if (this._listeners === undefined) return false;
  819. var listeners = this._listeners;
  820. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  821. },
  822. removeEventListener: function (type, listener) {
  823. if (this._listeners === undefined) return;
  824. var listeners = this._listeners;
  825. var listenerArray = listeners[type];
  826. if (listenerArray !== undefined) {
  827. var index = listenerArray.indexOf(listener);
  828. if (index !== -1) {
  829. listenerArray.splice(index, 1);
  830. }
  831. }
  832. },
  833. dispatchEvent: function (event) {
  834. if (this._listeners === undefined) return;
  835. var listeners = this._listeners;
  836. var listenerArray = listeners[event.type];
  837. if (listenerArray !== undefined) {
  838. event.target = this; // Make a copy, in case listeners are removed while iterating.
  839. var array = listenerArray.slice(0);
  840. for (var i = 0, l = array.length; i < l; i++) {
  841. array[i].call(this, event);
  842. }
  843. }
  844. }
  845. });
  846. /**
  847. * @author alteredq / http://alteredqualia.com/
  848. * @author mrdoob / http://mrdoob.com/
  849. * @author WestLangley / http://github.com/WestLangley
  850. * @author thezwap
  851. */
  852. var _lut = [];
  853. for (var i = 0; i < 256; i++) {
  854. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  855. }
  856. var MathUtils = {
  857. DEG2RAD: Math.PI / 180,
  858. RAD2DEG: 180 / Math.PI,
  859. generateUUID: function () {
  860. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  861. var d0 = Math.random() * 0xffffffff | 0;
  862. var d1 = Math.random() * 0xffffffff | 0;
  863. var d2 = Math.random() * 0xffffffff | 0;
  864. var d3 = Math.random() * 0xffffffff | 0;
  865. var 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.
  866. return uuid.toUpperCase();
  867. },
  868. clamp: function (value, min, max) {
  869. return Math.max(min, Math.min(max, value));
  870. },
  871. // compute euclidian modulo of m % n
  872. // https://en.wikipedia.org/wiki/Modulo_operation
  873. euclideanModulo: function (n, m) {
  874. return (n % m + m) % m;
  875. },
  876. // Linear mapping from range <a1, a2> to range <b1, b2>
  877. mapLinear: function (x, a1, a2, b1, b2) {
  878. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  879. },
  880. // https://en.wikipedia.org/wiki/Linear_interpolation
  881. lerp: function (x, y, t) {
  882. return (1 - t) * x + t * y;
  883. },
  884. // http://en.wikipedia.org/wiki/Smoothstep
  885. smoothstep: function (x, min, max) {
  886. if (x <= min) return 0;
  887. if (x >= max) return 1;
  888. x = (x - min) / (max - min);
  889. return x * x * (3 - 2 * x);
  890. },
  891. smootherstep: function (x, min, max) {
  892. if (x <= min) return 0;
  893. if (x >= max) return 1;
  894. x = (x - min) / (max - min);
  895. return x * x * x * (x * (x * 6 - 15) + 10);
  896. },
  897. // Random integer from <low, high> interval
  898. randInt: function (low, high) {
  899. return low + Math.floor(Math.random() * (high - low + 1));
  900. },
  901. // Random float from <low, high> interval
  902. randFloat: function (low, high) {
  903. return low + Math.random() * (high - low);
  904. },
  905. // Random float from <-range/2, range/2> interval
  906. randFloatSpread: function (range) {
  907. return range * (0.5 - Math.random());
  908. },
  909. degToRad: function (degrees) {
  910. return degrees * MathUtils.DEG2RAD;
  911. },
  912. radToDeg: function (radians) {
  913. return radians * MathUtils.RAD2DEG;
  914. },
  915. isPowerOfTwo: function (value) {
  916. return (value & value - 1) === 0 && value !== 0;
  917. },
  918. ceilPowerOfTwo: function (value) {
  919. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  920. },
  921. floorPowerOfTwo: function (value) {
  922. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  923. },
  924. setQuaternionFromProperEuler: function (q, a, b, c, order) {
  925. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  926. // rotations are applied to the axes in the order specified by 'order'
  927. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  928. // angles are in radians
  929. var cos = Math.cos;
  930. var sin = Math.sin;
  931. var c2 = cos(b / 2);
  932. var s2 = sin(b / 2);
  933. var c13 = cos((a + c) / 2);
  934. var s13 = sin((a + c) / 2);
  935. var c1_3 = cos((a - c) / 2);
  936. var s1_3 = sin((a - c) / 2);
  937. var c3_1 = cos((c - a) / 2);
  938. var s3_1 = sin((c - a) / 2);
  939. if (order === 'XYX') {
  940. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  941. } else if (order === 'YZY') {
  942. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  943. } else if (order === 'ZXZ') {
  944. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  945. } else if (order === 'XZX') {
  946. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  947. } else if (order === 'YXY') {
  948. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  949. } else if (order === 'ZYZ') {
  950. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  951. } else {
  952. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.');
  953. }
  954. }
  955. };
  956. /**
  957. * @author mrdoob / http://mrdoob.com/
  958. * @author philogb / http://blog.thejit.org/
  959. * @author egraether / http://egraether.com/
  960. * @author zz85 / http://www.lab4games.net/zz85/blog
  961. */
  962. exports.MathUtils = exports.Math = MathUtils;
  963. function Vector2(x, y) {
  964. this.x = x || 0;
  965. this.y = y || 0;
  966. }
  967. Object.defineProperties(Vector2.prototype, {
  968. "width": {
  969. get: function () {
  970. return this.x;
  971. },
  972. set: function (value) {
  973. this.x = value;
  974. }
  975. },
  976. "height": {
  977. get: function () {
  978. return this.y;
  979. },
  980. set: function (value) {
  981. this.y = value;
  982. }
  983. }
  984. });
  985. Object.assign(Vector2.prototype, {
  986. isVector2: true,
  987. set: function (x, y) {
  988. this.x = x;
  989. this.y = y;
  990. return this;
  991. },
  992. setScalar: function (scalar) {
  993. this.x = scalar;
  994. this.y = scalar;
  995. return this;
  996. },
  997. setX: function (x) {
  998. this.x = x;
  999. return this;
  1000. },
  1001. setY: function (y) {
  1002. this.y = y;
  1003. return this;
  1004. },
  1005. setComponent: function (index, value) {
  1006. switch (index) {
  1007. case 0:
  1008. this.x = value;
  1009. break;
  1010. case 1:
  1011. this.y = value;
  1012. break;
  1013. default:
  1014. throw new Error('index is out of range: ' + index);
  1015. }
  1016. return this;
  1017. },
  1018. getComponent: function (index) {
  1019. switch (index) {
  1020. case 0:
  1021. return this.x;
  1022. case 1:
  1023. return this.y;
  1024. default:
  1025. throw new Error('index is out of range: ' + index);
  1026. }
  1027. },
  1028. clone: function () {
  1029. return new this.constructor(this.x, this.y);
  1030. },
  1031. copy: function (v) {
  1032. this.x = v.x;
  1033. this.y = v.y;
  1034. return this;
  1035. },
  1036. add: function (v, w) {
  1037. if (w !== undefined) {
  1038. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1039. return this.addVectors(v, w);
  1040. }
  1041. this.x += v.x;
  1042. this.y += v.y;
  1043. return this;
  1044. },
  1045. addScalar: function (s) {
  1046. this.x += s;
  1047. this.y += s;
  1048. return this;
  1049. },
  1050. addVectors: function (a, b) {
  1051. this.x = a.x + b.x;
  1052. this.y = a.y + b.y;
  1053. return this;
  1054. },
  1055. addScaledVector: function (v, s) {
  1056. this.x += v.x * s;
  1057. this.y += v.y * s;
  1058. return this;
  1059. },
  1060. sub: function (v, w) {
  1061. if (w !== undefined) {
  1062. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1063. return this.subVectors(v, w);
  1064. }
  1065. this.x -= v.x;
  1066. this.y -= v.y;
  1067. return this;
  1068. },
  1069. subScalar: function (s) {
  1070. this.x -= s;
  1071. this.y -= s;
  1072. return this;
  1073. },
  1074. subVectors: function (a, b) {
  1075. this.x = a.x - b.x;
  1076. this.y = a.y - b.y;
  1077. return this;
  1078. },
  1079. multiply: function (v) {
  1080. this.x *= v.x;
  1081. this.y *= v.y;
  1082. return this;
  1083. },
  1084. multiplyScalar: function (scalar) {
  1085. this.x *= scalar;
  1086. this.y *= scalar;
  1087. return this;
  1088. },
  1089. divide: function (v) {
  1090. this.x /= v.x;
  1091. this.y /= v.y;
  1092. return this;
  1093. },
  1094. divideScalar: function (scalar) {
  1095. return this.multiplyScalar(1 / scalar);
  1096. },
  1097. applyMatrix3: function (m) {
  1098. var x = this.x,
  1099. y = this.y;
  1100. var e = m.elements;
  1101. this.x = e[0] * x + e[3] * y + e[6];
  1102. this.y = e[1] * x + e[4] * y + e[7];
  1103. return this;
  1104. },
  1105. min: function (v) {
  1106. this.x = Math.min(this.x, v.x);
  1107. this.y = Math.min(this.y, v.y);
  1108. return this;
  1109. },
  1110. max: function (v) {
  1111. this.x = Math.max(this.x, v.x);
  1112. this.y = Math.max(this.y, v.y);
  1113. return this;
  1114. },
  1115. clamp: function (min, max) {
  1116. // assumes min < max, componentwise
  1117. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1118. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1119. return this;
  1120. },
  1121. clampScalar: function (minVal, maxVal) {
  1122. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1123. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1124. return this;
  1125. },
  1126. clampLength: function (min, max) {
  1127. var length = this.length();
  1128. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1129. },
  1130. floor: function () {
  1131. this.x = Math.floor(this.x);
  1132. this.y = Math.floor(this.y);
  1133. return this;
  1134. },
  1135. ceil: function () {
  1136. this.x = Math.ceil(this.x);
  1137. this.y = Math.ceil(this.y);
  1138. return this;
  1139. },
  1140. round: function () {
  1141. this.x = Math.round(this.x);
  1142. this.y = Math.round(this.y);
  1143. return this;
  1144. },
  1145. roundToZero: function () {
  1146. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1147. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1148. return this;
  1149. },
  1150. negate: function () {
  1151. this.x = -this.x;
  1152. this.y = -this.y;
  1153. return this;
  1154. },
  1155. dot: function (v) {
  1156. return this.x * v.x + this.y * v.y;
  1157. },
  1158. cross: function (v) {
  1159. return this.x * v.y - this.y * v.x;
  1160. },
  1161. lengthSq: function () {
  1162. return this.x * this.x + this.y * this.y;
  1163. },
  1164. length: function () {
  1165. return Math.sqrt(this.x * this.x + this.y * this.y);
  1166. },
  1167. manhattanLength: function () {
  1168. return Math.abs(this.x) + Math.abs(this.y);
  1169. },
  1170. normalize: function () {
  1171. return this.divideScalar(this.length() || 1);
  1172. },
  1173. angle: function () {
  1174. // computes the angle in radians with respect to the positive x-axis
  1175. var angle = Math.atan2(-this.y, -this.x) + Math.PI;
  1176. return angle;
  1177. },
  1178. distanceTo: function (v) {
  1179. return Math.sqrt(this.distanceToSquared(v));
  1180. },
  1181. distanceToSquared: function (v) {
  1182. var dx = this.x - v.x,
  1183. dy = this.y - v.y;
  1184. return dx * dx + dy * dy;
  1185. },
  1186. manhattanDistanceTo: function (v) {
  1187. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1188. },
  1189. setLength: function (length) {
  1190. return this.normalize().multiplyScalar(length);
  1191. },
  1192. lerp: function (v, alpha) {
  1193. this.x += (v.x - this.x) * alpha;
  1194. this.y += (v.y - this.y) * alpha;
  1195. return this;
  1196. },
  1197. lerpVectors: function (v1, v2, alpha) {
  1198. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1199. },
  1200. equals: function (v) {
  1201. return v.x === this.x && v.y === this.y;
  1202. },
  1203. fromArray: function (array, offset) {
  1204. if (offset === undefined) offset = 0;
  1205. this.x = array[offset];
  1206. this.y = array[offset + 1];
  1207. return this;
  1208. },
  1209. toArray: function (array, offset) {
  1210. if (array === undefined) array = [];
  1211. if (offset === undefined) offset = 0;
  1212. array[offset] = this.x;
  1213. array[offset + 1] = this.y;
  1214. return array;
  1215. },
  1216. fromBufferAttribute: function (attribute, index, offset) {
  1217. if (offset !== undefined) {
  1218. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1219. }
  1220. this.x = attribute.getX(index);
  1221. this.y = attribute.getY(index);
  1222. return this;
  1223. },
  1224. rotateAround: function (center, angle) {
  1225. var c = Math.cos(angle),
  1226. s = Math.sin(angle);
  1227. var x = this.x - center.x;
  1228. var y = this.y - center.y;
  1229. this.x = x * c - y * s + center.x;
  1230. this.y = x * s + y * c + center.y;
  1231. return this;
  1232. }
  1233. });
  1234. /**
  1235. * @author alteredq / http://alteredqualia.com/
  1236. * @author WestLangley / http://github.com/WestLangley
  1237. * @author bhouston / http://clara.io
  1238. * @author tschw
  1239. */
  1240. function Matrix3() {
  1241. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1242. if (arguments.length > 0) {
  1243. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1244. }
  1245. }
  1246. Object.assign(Matrix3.prototype, {
  1247. isMatrix3: true,
  1248. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1249. var te = this.elements;
  1250. te[0] = n11;
  1251. te[1] = n21;
  1252. te[2] = n31;
  1253. te[3] = n12;
  1254. te[4] = n22;
  1255. te[5] = n32;
  1256. te[6] = n13;
  1257. te[7] = n23;
  1258. te[8] = n33;
  1259. return this;
  1260. },
  1261. identity: function () {
  1262. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  1263. return this;
  1264. },
  1265. clone: function () {
  1266. return new this.constructor().fromArray(this.elements);
  1267. },
  1268. copy: function (m) {
  1269. var te = this.elements;
  1270. var me = m.elements;
  1271. te[0] = me[0];
  1272. te[1] = me[1];
  1273. te[2] = me[2];
  1274. te[3] = me[3];
  1275. te[4] = me[4];
  1276. te[5] = me[5];
  1277. te[6] = me[6];
  1278. te[7] = me[7];
  1279. te[8] = me[8];
  1280. return this;
  1281. },
  1282. extractBasis: function (xAxis, yAxis, zAxis) {
  1283. xAxis.setFromMatrix3Column(this, 0);
  1284. yAxis.setFromMatrix3Column(this, 1);
  1285. zAxis.setFromMatrix3Column(this, 2);
  1286. return this;
  1287. },
  1288. setFromMatrix4: function (m) {
  1289. var me = m.elements;
  1290. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  1291. return this;
  1292. },
  1293. multiply: function (m) {
  1294. return this.multiplyMatrices(this, m);
  1295. },
  1296. premultiply: function (m) {
  1297. return this.multiplyMatrices(m, this);
  1298. },
  1299. multiplyMatrices: function (a, b) {
  1300. var ae = a.elements;
  1301. var be = b.elements;
  1302. var te = this.elements;
  1303. var a11 = ae[0],
  1304. a12 = ae[3],
  1305. a13 = ae[6];
  1306. var a21 = ae[1],
  1307. a22 = ae[4],
  1308. a23 = ae[7];
  1309. var a31 = ae[2],
  1310. a32 = ae[5],
  1311. a33 = ae[8];
  1312. var b11 = be[0],
  1313. b12 = be[3],
  1314. b13 = be[6];
  1315. var b21 = be[1],
  1316. b22 = be[4],
  1317. b23 = be[7];
  1318. var b31 = be[2],
  1319. b32 = be[5],
  1320. b33 = be[8];
  1321. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  1322. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  1323. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  1324. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  1325. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  1326. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  1327. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  1328. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  1329. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  1330. return this;
  1331. },
  1332. multiplyScalar: function (s) {
  1333. var te = this.elements;
  1334. te[0] *= s;
  1335. te[3] *= s;
  1336. te[6] *= s;
  1337. te[1] *= s;
  1338. te[4] *= s;
  1339. te[7] *= s;
  1340. te[2] *= s;
  1341. te[5] *= s;
  1342. te[8] *= s;
  1343. return this;
  1344. },
  1345. determinant: function () {
  1346. var te = this.elements;
  1347. var a = te[0],
  1348. b = te[1],
  1349. c = te[2],
  1350. d = te[3],
  1351. e = te[4],
  1352. f = te[5],
  1353. g = te[6],
  1354. h = te[7],
  1355. i = te[8];
  1356. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1357. },
  1358. getInverse: function (matrix, throwOnDegenerate) {
  1359. if (throwOnDegenerate !== undefined) {
  1360. console.warn("THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate.");
  1361. }
  1362. var me = matrix.elements,
  1363. te = this.elements,
  1364. n11 = me[0],
  1365. n21 = me[1],
  1366. n31 = me[2],
  1367. n12 = me[3],
  1368. n22 = me[4],
  1369. n32 = me[5],
  1370. n13 = me[6],
  1371. n23 = me[7],
  1372. n33 = me[8],
  1373. t11 = n33 * n22 - n32 * n23,
  1374. t12 = n32 * n13 - n33 * n12,
  1375. t13 = n23 * n12 - n22 * n13,
  1376. det = n11 * t11 + n21 * t12 + n31 * t13;
  1377. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  1378. var detInv = 1 / det;
  1379. te[0] = t11 * detInv;
  1380. te[1] = (n31 * n23 - n33 * n21) * detInv;
  1381. te[2] = (n32 * n21 - n31 * n22) * detInv;
  1382. te[3] = t12 * detInv;
  1383. te[4] = (n33 * n11 - n31 * n13) * detInv;
  1384. te[5] = (n31 * n12 - n32 * n11) * detInv;
  1385. te[6] = t13 * detInv;
  1386. te[7] = (n21 * n13 - n23 * n11) * detInv;
  1387. te[8] = (n22 * n11 - n21 * n12) * detInv;
  1388. return this;
  1389. },
  1390. transpose: function () {
  1391. var tmp,
  1392. m = this.elements;
  1393. tmp = m[1];
  1394. m[1] = m[3];
  1395. m[3] = tmp;
  1396. tmp = m[2];
  1397. m[2] = m[6];
  1398. m[6] = tmp;
  1399. tmp = m[5];
  1400. m[5] = m[7];
  1401. m[7] = tmp;
  1402. return this;
  1403. },
  1404. getNormalMatrix: function (matrix4) {
  1405. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  1406. },
  1407. transposeIntoArray: function (r) {
  1408. var m = this.elements;
  1409. r[0] = m[0];
  1410. r[1] = m[3];
  1411. r[2] = m[6];
  1412. r[3] = m[1];
  1413. r[4] = m[4];
  1414. r[5] = m[7];
  1415. r[6] = m[2];
  1416. r[7] = m[5];
  1417. r[8] = m[8];
  1418. return this;
  1419. },
  1420. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  1421. var c = Math.cos(rotation);
  1422. var s = Math.sin(rotation);
  1423. 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);
  1424. },
  1425. scale: function (sx, sy) {
  1426. var te = this.elements;
  1427. te[0] *= sx;
  1428. te[3] *= sx;
  1429. te[6] *= sx;
  1430. te[1] *= sy;
  1431. te[4] *= sy;
  1432. te[7] *= sy;
  1433. return this;
  1434. },
  1435. rotate: function (theta) {
  1436. var c = Math.cos(theta);
  1437. var s = Math.sin(theta);
  1438. var te = this.elements;
  1439. var a11 = te[0],
  1440. a12 = te[3],
  1441. a13 = te[6];
  1442. var a21 = te[1],
  1443. a22 = te[4],
  1444. a23 = te[7];
  1445. te[0] = c * a11 + s * a21;
  1446. te[3] = c * a12 + s * a22;
  1447. te[6] = c * a13 + s * a23;
  1448. te[1] = -s * a11 + c * a21;
  1449. te[4] = -s * a12 + c * a22;
  1450. te[7] = -s * a13 + c * a23;
  1451. return this;
  1452. },
  1453. translate: function (tx, ty) {
  1454. var te = this.elements;
  1455. te[0] += tx * te[2];
  1456. te[3] += tx * te[5];
  1457. te[6] += tx * te[8];
  1458. te[1] += ty * te[2];
  1459. te[4] += ty * te[5];
  1460. te[7] += ty * te[8];
  1461. return this;
  1462. },
  1463. equals: function (matrix) {
  1464. var te = this.elements;
  1465. var me = matrix.elements;
  1466. for (var i = 0; i < 9; i++) {
  1467. if (te[i] !== me[i]) return false;
  1468. }
  1469. return true;
  1470. },
  1471. fromArray: function (array, offset) {
  1472. if (offset === undefined) offset = 0;
  1473. for (var i = 0; i < 9; i++) {
  1474. this.elements[i] = array[i + offset];
  1475. }
  1476. return this;
  1477. },
  1478. toArray: function (array, offset) {
  1479. if (array === undefined) array = [];
  1480. if (offset === undefined) offset = 0;
  1481. var te = this.elements;
  1482. array[offset] = te[0];
  1483. array[offset + 1] = te[1];
  1484. array[offset + 2] = te[2];
  1485. array[offset + 3] = te[3];
  1486. array[offset + 4] = te[4];
  1487. array[offset + 5] = te[5];
  1488. array[offset + 6] = te[6];
  1489. array[offset + 7] = te[7];
  1490. array[offset + 8] = te[8];
  1491. return array;
  1492. }
  1493. });
  1494. /**
  1495. * @author mrdoob / http://mrdoob.com/
  1496. * @author alteredq / http://alteredqualia.com/
  1497. * @author szimek / https://github.com/szimek/
  1498. */
  1499. var _canvas;
  1500. var ImageUtils = {
  1501. getDataURL: function (image) {
  1502. var canvas;
  1503. if (typeof HTMLCanvasElement == 'undefined') {
  1504. return image.src;
  1505. } else if (image instanceof HTMLCanvasElement) {
  1506. canvas = image;
  1507. } else {
  1508. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  1509. _canvas.width = image.width;
  1510. _canvas.height = image.height;
  1511. var context = _canvas.getContext('2d');
  1512. if (image instanceof ImageData) {
  1513. context.putImageData(image, 0, 0);
  1514. } else {
  1515. context.drawImage(image, 0, 0, image.width, image.height);
  1516. }
  1517. canvas = _canvas;
  1518. }
  1519. if (canvas.width > 2048 || canvas.height > 2048) {
  1520. return canvas.toDataURL('image/jpeg', 0.6);
  1521. } else {
  1522. return canvas.toDataURL('image/png');
  1523. }
  1524. }
  1525. };
  1526. /**
  1527. * @author mrdoob / http://mrdoob.com/
  1528. * @author alteredq / http://alteredqualia.com/
  1529. * @author szimek / https://github.com/szimek/
  1530. */
  1531. exports.ImageUtils = ImageUtils;
  1532. var textureId = 0;
  1533. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  1534. Object.defineProperty(this, 'id', {
  1535. value: textureId++
  1536. });
  1537. this.uuid = MathUtils.generateUUID();
  1538. this.name = '';
  1539. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  1540. this.mipmaps = [];
  1541. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  1542. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  1543. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  1544. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  1545. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  1546. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  1547. this.format = format !== undefined ? format : RGBAFormat;
  1548. this.internalFormat = null;
  1549. this.type = type !== undefined ? type : UnsignedByteType;
  1550. this.offset = new Vector2(0, 0);
  1551. this.repeat = new Vector2(1, 1);
  1552. this.center = new Vector2(0, 0);
  1553. this.rotation = 0;
  1554. this.matrixAutoUpdate = true;
  1555. this.matrix = new Matrix3();
  1556. this.generateMipmaps = true;
  1557. this.premultiplyAlpha = false;
  1558. this.flipY = true;
  1559. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1560. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1561. //
  1562. // Also changing the encoding after already used by a Material will not automatically make the Material
  1563. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1564. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  1565. this.version = 0;
  1566. this.onUpdate = null;
  1567. }
  1568. Texture.DEFAULT_IMAGE = undefined;
  1569. Texture.DEFAULT_MAPPING = UVMapping;
  1570. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  1571. constructor: Texture,
  1572. isTexture: true,
  1573. updateMatrix: function () {
  1574. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1575. },
  1576. clone: function () {
  1577. return new this.constructor().copy(this);
  1578. },
  1579. copy: function (source) {
  1580. this.name = source.name;
  1581. this.image = source.image;
  1582. this.mipmaps = source.mipmaps.slice(0);
  1583. this.mapping = source.mapping;
  1584. this.wrapS = source.wrapS;
  1585. this.wrapT = source.wrapT;
  1586. this.magFilter = source.magFilter;
  1587. this.minFilter = source.minFilter;
  1588. this.anisotropy = source.anisotropy;
  1589. this.format = source.format;
  1590. this.internalFormat = source.internalFormat;
  1591. this.type = source.type;
  1592. this.offset.copy(source.offset);
  1593. this.repeat.copy(source.repeat);
  1594. this.center.copy(source.center);
  1595. this.rotation = source.rotation;
  1596. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1597. this.matrix.copy(source.matrix);
  1598. this.generateMipmaps = source.generateMipmaps;
  1599. this.premultiplyAlpha = source.premultiplyAlpha;
  1600. this.flipY = source.flipY;
  1601. this.unpackAlignment = source.unpackAlignment;
  1602. this.encoding = source.encoding;
  1603. return this;
  1604. },
  1605. toJSON: function (meta) {
  1606. var isRootObject = meta === undefined || typeof meta === 'string';
  1607. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1608. return meta.textures[this.uuid];
  1609. }
  1610. var output = {
  1611. metadata: {
  1612. version: 4.5,
  1613. type: 'Texture',
  1614. generator: 'Texture.toJSON'
  1615. },
  1616. uuid: this.uuid,
  1617. name: this.name,
  1618. mapping: this.mapping,
  1619. repeat: [this.repeat.x, this.repeat.y],
  1620. offset: [this.offset.x, this.offset.y],
  1621. center: [this.center.x, this.center.y],
  1622. rotation: this.rotation,
  1623. wrap: [this.wrapS, this.wrapT],
  1624. format: this.format,
  1625. type: this.type,
  1626. encoding: this.encoding,
  1627. minFilter: this.minFilter,
  1628. magFilter: this.magFilter,
  1629. anisotropy: this.anisotropy,
  1630. flipY: this.flipY,
  1631. premultiplyAlpha: this.premultiplyAlpha,
  1632. unpackAlignment: this.unpackAlignment
  1633. };
  1634. if (this.image !== undefined) {
  1635. // TODO: Move to THREE.Image
  1636. var image = this.image;
  1637. if (image.uuid === undefined) {
  1638. image.uuid = MathUtils.generateUUID(); // UGH
  1639. }
  1640. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1641. var url;
  1642. if (Array.isArray(image)) {
  1643. // process array of images e.g. CubeTexture
  1644. url = [];
  1645. for (var i = 0, l = image.length; i < l; i++) {
  1646. url.push(ImageUtils.getDataURL(image[i]));
  1647. }
  1648. } else {
  1649. // process single image
  1650. url = ImageUtils.getDataURL(image);
  1651. }
  1652. meta.images[image.uuid] = {
  1653. uuid: image.uuid,
  1654. url: url
  1655. };
  1656. }
  1657. output.image = image.uuid;
  1658. }
  1659. if (!isRootObject) {
  1660. meta.textures[this.uuid] = output;
  1661. }
  1662. return output;
  1663. },
  1664. dispose: function () {
  1665. this.dispatchEvent({
  1666. type: 'dispose'
  1667. });
  1668. },
  1669. transformUv: function (uv) {
  1670. if (this.mapping !== UVMapping) return uv;
  1671. uv.applyMatrix3(this.matrix);
  1672. if (uv.x < 0 || uv.x > 1) {
  1673. switch (this.wrapS) {
  1674. case RepeatWrapping:
  1675. uv.x = uv.x - Math.floor(uv.x);
  1676. break;
  1677. case ClampToEdgeWrapping:
  1678. uv.x = uv.x < 0 ? 0 : 1;
  1679. break;
  1680. case MirroredRepeatWrapping:
  1681. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1682. uv.x = Math.ceil(uv.x) - uv.x;
  1683. } else {
  1684. uv.x = uv.x - Math.floor(uv.x);
  1685. }
  1686. break;
  1687. }
  1688. }
  1689. if (uv.y < 0 || uv.y > 1) {
  1690. switch (this.wrapT) {
  1691. case RepeatWrapping:
  1692. uv.y = uv.y - Math.floor(uv.y);
  1693. break;
  1694. case ClampToEdgeWrapping:
  1695. uv.y = uv.y < 0 ? 0 : 1;
  1696. break;
  1697. case MirroredRepeatWrapping:
  1698. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1699. uv.y = Math.ceil(uv.y) - uv.y;
  1700. } else {
  1701. uv.y = uv.y - Math.floor(uv.y);
  1702. }
  1703. break;
  1704. }
  1705. }
  1706. if (this.flipY) {
  1707. uv.y = 1 - uv.y;
  1708. }
  1709. return uv;
  1710. }
  1711. });
  1712. Object.defineProperty(Texture.prototype, "needsUpdate", {
  1713. set: function (value) {
  1714. if (value === true) this.version++;
  1715. }
  1716. });
  1717. /**
  1718. * @author supereggbert / http://www.paulbrunt.co.uk/
  1719. * @author philogb / http://blog.thejit.org/
  1720. * @author mikael emtinger / http://gomo.se/
  1721. * @author egraether / http://egraether.com/
  1722. * @author WestLangley / http://github.com/WestLangley
  1723. */
  1724. function Vector4(x, y, z, w) {
  1725. this.x = x || 0;
  1726. this.y = y || 0;
  1727. this.z = z || 0;
  1728. this.w = w !== undefined ? w : 1;
  1729. }
  1730. Object.defineProperties(Vector4.prototype, {
  1731. "width": {
  1732. get: function () {
  1733. return this.z;
  1734. },
  1735. set: function (value) {
  1736. this.z = value;
  1737. }
  1738. },
  1739. "height": {
  1740. get: function () {
  1741. return this.w;
  1742. },
  1743. set: function (value) {
  1744. this.w = value;
  1745. }
  1746. }
  1747. });
  1748. Object.assign(Vector4.prototype, {
  1749. isVector4: true,
  1750. set: function (x, y, z, w) {
  1751. this.x = x;
  1752. this.y = y;
  1753. this.z = z;
  1754. this.w = w;
  1755. return this;
  1756. },
  1757. setScalar: function (scalar) {
  1758. this.x = scalar;
  1759. this.y = scalar;
  1760. this.z = scalar;
  1761. this.w = scalar;
  1762. return this;
  1763. },
  1764. setX: function (x) {
  1765. this.x = x;
  1766. return this;
  1767. },
  1768. setY: function (y) {
  1769. this.y = y;
  1770. return this;
  1771. },
  1772. setZ: function (z) {
  1773. this.z = z;
  1774. return this;
  1775. },
  1776. setW: function (w) {
  1777. this.w = w;
  1778. return this;
  1779. },
  1780. setComponent: function (index, value) {
  1781. switch (index) {
  1782. case 0:
  1783. this.x = value;
  1784. break;
  1785. case 1:
  1786. this.y = value;
  1787. break;
  1788. case 2:
  1789. this.z = value;
  1790. break;
  1791. case 3:
  1792. this.w = value;
  1793. break;
  1794. default:
  1795. throw new Error('index is out of range: ' + index);
  1796. }
  1797. return this;
  1798. },
  1799. getComponent: function (index) {
  1800. switch (index) {
  1801. case 0:
  1802. return this.x;
  1803. case 1:
  1804. return this.y;
  1805. case 2:
  1806. return this.z;
  1807. case 3:
  1808. return this.w;
  1809. default:
  1810. throw new Error('index is out of range: ' + index);
  1811. }
  1812. },
  1813. clone: function () {
  1814. return new this.constructor(this.x, this.y, this.z, this.w);
  1815. },
  1816. copy: function (v) {
  1817. this.x = v.x;
  1818. this.y = v.y;
  1819. this.z = v.z;
  1820. this.w = v.w !== undefined ? v.w : 1;
  1821. return this;
  1822. },
  1823. add: function (v, w) {
  1824. if (w !== undefined) {
  1825. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1826. return this.addVectors(v, w);
  1827. }
  1828. this.x += v.x;
  1829. this.y += v.y;
  1830. this.z += v.z;
  1831. this.w += v.w;
  1832. return this;
  1833. },
  1834. addScalar: function (s) {
  1835. this.x += s;
  1836. this.y += s;
  1837. this.z += s;
  1838. this.w += s;
  1839. return this;
  1840. },
  1841. addVectors: function (a, b) {
  1842. this.x = a.x + b.x;
  1843. this.y = a.y + b.y;
  1844. this.z = a.z + b.z;
  1845. this.w = a.w + b.w;
  1846. return this;
  1847. },
  1848. addScaledVector: function (v, s) {
  1849. this.x += v.x * s;
  1850. this.y += v.y * s;
  1851. this.z += v.z * s;
  1852. this.w += v.w * s;
  1853. return this;
  1854. },
  1855. sub: function (v, w) {
  1856. if (w !== undefined) {
  1857. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1858. return this.subVectors(v, w);
  1859. }
  1860. this.x -= v.x;
  1861. this.y -= v.y;
  1862. this.z -= v.z;
  1863. this.w -= v.w;
  1864. return this;
  1865. },
  1866. subScalar: function (s) {
  1867. this.x -= s;
  1868. this.y -= s;
  1869. this.z -= s;
  1870. this.w -= s;
  1871. return this;
  1872. },
  1873. subVectors: function (a, b) {
  1874. this.x = a.x - b.x;
  1875. this.y = a.y - b.y;
  1876. this.z = a.z - b.z;
  1877. this.w = a.w - b.w;
  1878. return this;
  1879. },
  1880. multiplyScalar: function (scalar) {
  1881. this.x *= scalar;
  1882. this.y *= scalar;
  1883. this.z *= scalar;
  1884. this.w *= scalar;
  1885. return this;
  1886. },
  1887. applyMatrix4: function (m) {
  1888. var x = this.x,
  1889. y = this.y,
  1890. z = this.z,
  1891. w = this.w;
  1892. var e = m.elements;
  1893. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1894. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1895. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1896. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1897. return this;
  1898. },
  1899. divideScalar: function (scalar) {
  1900. return this.multiplyScalar(1 / scalar);
  1901. },
  1902. setAxisAngleFromQuaternion: function (q) {
  1903. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1904. // q is assumed to be normalized
  1905. this.w = 2 * Math.acos(q.w);
  1906. var s = Math.sqrt(1 - q.w * q.w);
  1907. if (s < 0.0001) {
  1908. this.x = 1;
  1909. this.y = 0;
  1910. this.z = 0;
  1911. } else {
  1912. this.x = q.x / s;
  1913. this.y = q.y / s;
  1914. this.z = q.z / s;
  1915. }
  1916. return this;
  1917. },
  1918. setAxisAngleFromRotationMatrix: function (m) {
  1919. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1920. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1921. var angle,
  1922. x,
  1923. y,
  1924. z,
  1925. // variables for result
  1926. epsilon = 0.01,
  1927. // margin to allow for rounding errors
  1928. epsilon2 = 0.1,
  1929. // margin to distinguish between 0 and 180 degrees
  1930. te = m.elements,
  1931. m11 = te[0],
  1932. m12 = te[4],
  1933. m13 = te[8],
  1934. m21 = te[1],
  1935. m22 = te[5],
  1936. m23 = te[9],
  1937. m31 = te[2],
  1938. m32 = te[6],
  1939. m33 = te[10];
  1940. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1941. // singularity found
  1942. // first check for identity matrix which must have +1 for all terms
  1943. // in leading diagonal and zero in other terms
  1944. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1945. // this singularity is identity matrix so angle = 0
  1946. this.set(1, 0, 0, 0);
  1947. return this; // zero angle, arbitrary axis
  1948. } // otherwise this singularity is angle = 180
  1949. angle = Math.PI;
  1950. var xx = (m11 + 1) / 2;
  1951. var yy = (m22 + 1) / 2;
  1952. var zz = (m33 + 1) / 2;
  1953. var xy = (m12 + m21) / 4;
  1954. var xz = (m13 + m31) / 4;
  1955. var yz = (m23 + m32) / 4;
  1956. if (xx > yy && xx > zz) {
  1957. // m11 is the largest diagonal term
  1958. if (xx < epsilon) {
  1959. x = 0;
  1960. y = 0.707106781;
  1961. z = 0.707106781;
  1962. } else {
  1963. x = Math.sqrt(xx);
  1964. y = xy / x;
  1965. z = xz / x;
  1966. }
  1967. } else if (yy > zz) {
  1968. // m22 is the largest diagonal term
  1969. if (yy < epsilon) {
  1970. x = 0.707106781;
  1971. y = 0;
  1972. z = 0.707106781;
  1973. } else {
  1974. y = Math.sqrt(yy);
  1975. x = xy / y;
  1976. z = yz / y;
  1977. }
  1978. } else {
  1979. // m33 is the largest diagonal term so base result on this
  1980. if (zz < epsilon) {
  1981. x = 0.707106781;
  1982. y = 0.707106781;
  1983. z = 0;
  1984. } else {
  1985. z = Math.sqrt(zz);
  1986. x = xz / z;
  1987. y = yz / z;
  1988. }
  1989. }
  1990. this.set(x, y, z, angle);
  1991. return this; // return 180 deg rotation
  1992. } // as we have reached here there are no singularities so we can handle normally
  1993. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1994. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1995. // caught by singularity test above, but I've left it in just in case
  1996. this.x = (m32 - m23) / s;
  1997. this.y = (m13 - m31) / s;
  1998. this.z = (m21 - m12) / s;
  1999. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2000. return this;
  2001. },
  2002. min: function (v) {
  2003. this.x = Math.min(this.x, v.x);
  2004. this.y = Math.min(this.y, v.y);
  2005. this.z = Math.min(this.z, v.z);
  2006. this.w = Math.min(this.w, v.w);
  2007. return this;
  2008. },
  2009. max: function (v) {
  2010. this.x = Math.max(this.x, v.x);
  2011. this.y = Math.max(this.y, v.y);
  2012. this.z = Math.max(this.z, v.z);
  2013. this.w = Math.max(this.w, v.w);
  2014. return this;
  2015. },
  2016. clamp: function (min, max) {
  2017. // assumes min < max, componentwise
  2018. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2019. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2020. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2021. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2022. return this;
  2023. },
  2024. clampScalar: function (minVal, maxVal) {
  2025. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2026. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2027. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2028. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2029. return this;
  2030. },
  2031. clampLength: function (min, max) {
  2032. var length = this.length();
  2033. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2034. },
  2035. floor: function () {
  2036. this.x = Math.floor(this.x);
  2037. this.y = Math.floor(this.y);
  2038. this.z = Math.floor(this.z);
  2039. this.w = Math.floor(this.w);
  2040. return this;
  2041. },
  2042. ceil: function () {
  2043. this.x = Math.ceil(this.x);
  2044. this.y = Math.ceil(this.y);
  2045. this.z = Math.ceil(this.z);
  2046. this.w = Math.ceil(this.w);
  2047. return this;
  2048. },
  2049. round: function () {
  2050. this.x = Math.round(this.x);
  2051. this.y = Math.round(this.y);
  2052. this.z = Math.round(this.z);
  2053. this.w = Math.round(this.w);
  2054. return this;
  2055. },
  2056. roundToZero: function () {
  2057. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2058. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2059. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2060. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2061. return this;
  2062. },
  2063. negate: function () {
  2064. this.x = -this.x;
  2065. this.y = -this.y;
  2066. this.z = -this.z;
  2067. this.w = -this.w;
  2068. return this;
  2069. },
  2070. dot: function (v) {
  2071. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2072. },
  2073. lengthSq: function () {
  2074. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2075. },
  2076. length: function () {
  2077. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2078. },
  2079. manhattanLength: function () {
  2080. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2081. },
  2082. normalize: function () {
  2083. return this.divideScalar(this.length() || 1);
  2084. },
  2085. setLength: function (length) {
  2086. return this.normalize().multiplyScalar(length);
  2087. },
  2088. lerp: function (v, alpha) {
  2089. this.x += (v.x - this.x) * alpha;
  2090. this.y += (v.y - this.y) * alpha;
  2091. this.z += (v.z - this.z) * alpha;
  2092. this.w += (v.w - this.w) * alpha;
  2093. return this;
  2094. },
  2095. lerpVectors: function (v1, v2, alpha) {
  2096. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2097. },
  2098. equals: function (v) {
  2099. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2100. },
  2101. fromArray: function (array, offset) {
  2102. if (offset === undefined) offset = 0;
  2103. this.x = array[offset];
  2104. this.y = array[offset + 1];
  2105. this.z = array[offset + 2];
  2106. this.w = array[offset + 3];
  2107. return this;
  2108. },
  2109. toArray: function (array, offset) {
  2110. if (array === undefined) array = [];
  2111. if (offset === undefined) offset = 0;
  2112. array[offset] = this.x;
  2113. array[offset + 1] = this.y;
  2114. array[offset + 2] = this.z;
  2115. array[offset + 3] = this.w;
  2116. return array;
  2117. },
  2118. fromBufferAttribute: function (attribute, index, offset) {
  2119. if (offset !== undefined) {
  2120. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  2121. }
  2122. this.x = attribute.getX(index);
  2123. this.y = attribute.getY(index);
  2124. this.z = attribute.getZ(index);
  2125. this.w = attribute.getW(index);
  2126. return this;
  2127. }
  2128. });
  2129. /**
  2130. * @author szimek / https://github.com/szimek/
  2131. * @author alteredq / http://alteredqualia.com/
  2132. * @author Marius Kintel / https://github.com/kintel
  2133. */
  2134. /*
  2135. In options, we can specify:
  2136. * Texture parameters for an auto-generated target texture
  2137. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2138. */
  2139. function WebGLRenderTarget(width, height, options) {
  2140. this.width = width;
  2141. this.height = height;
  2142. this.scissor = new Vector4(0, 0, width, height);
  2143. this.scissorTest = false;
  2144. this.viewport = new Vector4(0, 0, width, height);
  2145. options = options || {};
  2146. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2147. this.texture.image = {};
  2148. this.texture.image.width = width;
  2149. this.texture.image.height = height;
  2150. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2151. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2152. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2153. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  2154. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2155. }
  2156. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2157. constructor: WebGLRenderTarget,
  2158. isWebGLRenderTarget: true,
  2159. setSize: function (width, height) {
  2160. if (this.width !== width || this.height !== height) {
  2161. this.width = width;
  2162. this.height = height;
  2163. this.texture.image.width = width;
  2164. this.texture.image.height = height;
  2165. this.dispose();
  2166. }
  2167. this.viewport.set(0, 0, width, height);
  2168. this.scissor.set(0, 0, width, height);
  2169. },
  2170. clone: function () {
  2171. return new this.constructor().copy(this);
  2172. },
  2173. copy: function (source) {
  2174. this.width = source.width;
  2175. this.height = source.height;
  2176. this.viewport.copy(source.viewport);
  2177. this.texture = source.texture.clone();
  2178. this.depthBuffer = source.depthBuffer;
  2179. this.stencilBuffer = source.stencilBuffer;
  2180. this.depthTexture = source.depthTexture;
  2181. return this;
  2182. },
  2183. dispose: function () {
  2184. this.dispatchEvent({
  2185. type: 'dispose'
  2186. });
  2187. }
  2188. });
  2189. /**
  2190. * @author Mugen87 / https://github.com/Mugen87
  2191. * @author Matt DesLauriers / @mattdesl
  2192. */
  2193. function WebGLMultisampleRenderTarget(width, height, options) {
  2194. WebGLRenderTarget.call(this, width, height, options);
  2195. this.samples = 4;
  2196. }
  2197. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2198. constructor: WebGLMultisampleRenderTarget,
  2199. isWebGLMultisampleRenderTarget: true,
  2200. copy: function (source) {
  2201. WebGLRenderTarget.prototype.copy.call(this, source);
  2202. this.samples = source.samples;
  2203. return this;
  2204. }
  2205. });
  2206. /**
  2207. * @author mikael emtinger / http://gomo.se/
  2208. * @author alteredq / http://alteredqualia.com/
  2209. * @author WestLangley / http://github.com/WestLangley
  2210. * @author bhouston / http://clara.io
  2211. */
  2212. function Quaternion(x, y, z, w) {
  2213. this._x = x || 0;
  2214. this._y = y || 0;
  2215. this._z = z || 0;
  2216. this._w = w !== undefined ? w : 1;
  2217. }
  2218. Object.assign(Quaternion, {
  2219. slerp: function (qa, qb, qm, t) {
  2220. return qm.copy(qa).slerp(qb, t);
  2221. },
  2222. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2223. // fuzz-free, array-based Quaternion SLERP operation
  2224. var x0 = src0[srcOffset0 + 0],
  2225. y0 = src0[srcOffset0 + 1],
  2226. z0 = src0[srcOffset0 + 2],
  2227. w0 = src0[srcOffset0 + 3],
  2228. x1 = src1[srcOffset1 + 0],
  2229. y1 = src1[srcOffset1 + 1],
  2230. z1 = src1[srcOffset1 + 2],
  2231. w1 = src1[srcOffset1 + 3];
  2232. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2233. var s = 1 - t,
  2234. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2235. dir = cos >= 0 ? 1 : -1,
  2236. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2237. if (sqrSin > Number.EPSILON) {
  2238. var sin = Math.sqrt(sqrSin),
  2239. len = Math.atan2(sin, cos * dir);
  2240. s = Math.sin(s * len) / sin;
  2241. t = Math.sin(t * len) / sin;
  2242. }
  2243. var tDir = t * dir;
  2244. x0 = x0 * s + x1 * tDir;
  2245. y0 = y0 * s + y1 * tDir;
  2246. z0 = z0 * s + z1 * tDir;
  2247. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2248. if (s === 1 - t) {
  2249. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2250. x0 *= f;
  2251. y0 *= f;
  2252. z0 *= f;
  2253. w0 *= f;
  2254. }
  2255. }
  2256. dst[dstOffset] = x0;
  2257. dst[dstOffset + 1] = y0;
  2258. dst[dstOffset + 2] = z0;
  2259. dst[dstOffset + 3] = w0;
  2260. }
  2261. });
  2262. Object.defineProperties(Quaternion.prototype, {
  2263. x: {
  2264. get: function () {
  2265. return this._x;
  2266. },
  2267. set: function (value) {
  2268. this._x = value;
  2269. this._onChangeCallback();
  2270. }
  2271. },
  2272. y: {
  2273. get: function () {
  2274. return this._y;
  2275. },
  2276. set: function (value) {
  2277. this._y = value;
  2278. this._onChangeCallback();
  2279. }
  2280. },
  2281. z: {
  2282. get: function () {
  2283. return this._z;
  2284. },
  2285. set: function (value) {
  2286. this._z = value;
  2287. this._onChangeCallback();
  2288. }
  2289. },
  2290. w: {
  2291. get: function () {
  2292. return this._w;
  2293. },
  2294. set: function (value) {
  2295. this._w = value;
  2296. this._onChangeCallback();
  2297. }
  2298. }
  2299. });
  2300. Object.assign(Quaternion.prototype, {
  2301. isQuaternion: true,
  2302. set: function (x, y, z, w) {
  2303. this._x = x;
  2304. this._y = y;
  2305. this._z = z;
  2306. this._w = w;
  2307. this._onChangeCallback();
  2308. return this;
  2309. },
  2310. clone: function () {
  2311. return new this.constructor(this._x, this._y, this._z, this._w);
  2312. },
  2313. copy: function (quaternion) {
  2314. this._x = quaternion.x;
  2315. this._y = quaternion.y;
  2316. this._z = quaternion.z;
  2317. this._w = quaternion.w;
  2318. this._onChangeCallback();
  2319. return this;
  2320. },
  2321. setFromEuler: function (euler, update) {
  2322. if (!(euler && euler.isEuler)) {
  2323. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2324. }
  2325. var x = euler._x,
  2326. y = euler._y,
  2327. z = euler._z,
  2328. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2329. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2330. // content/SpinCalc.m
  2331. var cos = Math.cos;
  2332. var sin = Math.sin;
  2333. var c1 = cos(x / 2);
  2334. var c2 = cos(y / 2);
  2335. var c3 = cos(z / 2);
  2336. var s1 = sin(x / 2);
  2337. var s2 = sin(y / 2);
  2338. var s3 = sin(z / 2);
  2339. if (order === 'XYZ') {
  2340. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2341. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2344. } else if (order === 'YXZ') {
  2345. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2346. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2347. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2349. } else if (order === 'ZXY') {
  2350. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2351. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2352. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2353. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2354. } else if (order === 'ZYX') {
  2355. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2356. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2357. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2358. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2359. } else if (order === 'YZX') {
  2360. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2361. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2362. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2363. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2364. } else if (order === 'XZY') {
  2365. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2366. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2367. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2368. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2369. }
  2370. if (update !== false) this._onChangeCallback();
  2371. return this;
  2372. },
  2373. setFromAxisAngle: function (axis, angle) {
  2374. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2375. // assumes axis is normalized
  2376. var halfAngle = angle / 2,
  2377. s = Math.sin(halfAngle);
  2378. this._x = axis.x * s;
  2379. this._y = axis.y * s;
  2380. this._z = axis.z * s;
  2381. this._w = Math.cos(halfAngle);
  2382. this._onChangeCallback();
  2383. return this;
  2384. },
  2385. setFromRotationMatrix: function (m) {
  2386. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2387. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2388. var te = m.elements,
  2389. m11 = te[0],
  2390. m12 = te[4],
  2391. m13 = te[8],
  2392. m21 = te[1],
  2393. m22 = te[5],
  2394. m23 = te[9],
  2395. m31 = te[2],
  2396. m32 = te[6],
  2397. m33 = te[10],
  2398. trace = m11 + m22 + m33,
  2399. s;
  2400. if (trace > 0) {
  2401. s = 0.5 / Math.sqrt(trace + 1.0);
  2402. this._w = 0.25 / s;
  2403. this._x = (m32 - m23) * s;
  2404. this._y = (m13 - m31) * s;
  2405. this._z = (m21 - m12) * s;
  2406. } else if (m11 > m22 && m11 > m33) {
  2407. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2408. this._w = (m32 - m23) / s;
  2409. this._x = 0.25 * s;
  2410. this._y = (m12 + m21) / s;
  2411. this._z = (m13 + m31) / s;
  2412. } else if (m22 > m33) {
  2413. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2414. this._w = (m13 - m31) / s;
  2415. this._x = (m12 + m21) / s;
  2416. this._y = 0.25 * s;
  2417. this._z = (m23 + m32) / s;
  2418. } else {
  2419. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2420. this._w = (m21 - m12) / s;
  2421. this._x = (m13 + m31) / s;
  2422. this._y = (m23 + m32) / s;
  2423. this._z = 0.25 * s;
  2424. }
  2425. this._onChangeCallback();
  2426. return this;
  2427. },
  2428. setFromUnitVectors: function (vFrom, vTo) {
  2429. // assumes direction vectors vFrom and vTo are normalized
  2430. var EPS = 0.000001;
  2431. var r = vFrom.dot(vTo) + 1;
  2432. if (r < EPS) {
  2433. r = 0;
  2434. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2435. this._x = -vFrom.y;
  2436. this._y = vFrom.x;
  2437. this._z = 0;
  2438. this._w = r;
  2439. } else {
  2440. this._x = 0;
  2441. this._y = -vFrom.z;
  2442. this._z = vFrom.y;
  2443. this._w = r;
  2444. }
  2445. } else {
  2446. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2447. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2448. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2449. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2450. this._w = r;
  2451. }
  2452. return this.normalize();
  2453. },
  2454. angleTo: function (q) {
  2455. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  2456. },
  2457. rotateTowards: function (q, step) {
  2458. var angle = this.angleTo(q);
  2459. if (angle === 0) return this;
  2460. var t = Math.min(1, step / angle);
  2461. this.slerp(q, t);
  2462. return this;
  2463. },
  2464. inverse: function () {
  2465. // quaternion is assumed to have unit length
  2466. return this.conjugate();
  2467. },
  2468. conjugate: function () {
  2469. this._x *= -1;
  2470. this._y *= -1;
  2471. this._z *= -1;
  2472. this._onChangeCallback();
  2473. return this;
  2474. },
  2475. dot: function (v) {
  2476. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2477. },
  2478. lengthSq: function () {
  2479. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2480. },
  2481. length: function () {
  2482. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2483. },
  2484. normalize: function () {
  2485. var l = this.length();
  2486. if (l === 0) {
  2487. this._x = 0;
  2488. this._y = 0;
  2489. this._z = 0;
  2490. this._w = 1;
  2491. } else {
  2492. l = 1 / l;
  2493. this._x = this._x * l;
  2494. this._y = this._y * l;
  2495. this._z = this._z * l;
  2496. this._w = this._w * l;
  2497. }
  2498. this._onChangeCallback();
  2499. return this;
  2500. },
  2501. multiply: function (q, p) {
  2502. if (p !== undefined) {
  2503. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2504. return this.multiplyQuaternions(q, p);
  2505. }
  2506. return this.multiplyQuaternions(this, q);
  2507. },
  2508. premultiply: function (q) {
  2509. return this.multiplyQuaternions(q, this);
  2510. },
  2511. multiplyQuaternions: function (a, b) {
  2512. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2513. var qax = a._x,
  2514. qay = a._y,
  2515. qaz = a._z,
  2516. qaw = a._w;
  2517. var qbx = b._x,
  2518. qby = b._y,
  2519. qbz = b._z,
  2520. qbw = b._w;
  2521. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2522. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2523. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2524. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2525. this._onChangeCallback();
  2526. return this;
  2527. },
  2528. slerp: function (qb, t) {
  2529. if (t === 0) return this;
  2530. if (t === 1) return this.copy(qb);
  2531. var x = this._x,
  2532. y = this._y,
  2533. z = this._z,
  2534. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2535. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2536. if (cosHalfTheta < 0) {
  2537. this._w = -qb._w;
  2538. this._x = -qb._x;
  2539. this._y = -qb._y;
  2540. this._z = -qb._z;
  2541. cosHalfTheta = -cosHalfTheta;
  2542. } else {
  2543. this.copy(qb);
  2544. }
  2545. if (cosHalfTheta >= 1.0) {
  2546. this._w = w;
  2547. this._x = x;
  2548. this._y = y;
  2549. this._z = z;
  2550. return this;
  2551. }
  2552. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2553. if (sqrSinHalfTheta <= Number.EPSILON) {
  2554. var s = 1 - t;
  2555. this._w = s * w + t * this._w;
  2556. this._x = s * x + t * this._x;
  2557. this._y = s * y + t * this._y;
  2558. this._z = s * z + t * this._z;
  2559. this.normalize();
  2560. this._onChangeCallback();
  2561. return this;
  2562. }
  2563. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2564. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2565. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2566. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2567. this._w = w * ratioA + this._w * ratioB;
  2568. this._x = x * ratioA + this._x * ratioB;
  2569. this._y = y * ratioA + this._y * ratioB;
  2570. this._z = z * ratioA + this._z * ratioB;
  2571. this._onChangeCallback();
  2572. return this;
  2573. },
  2574. equals: function (quaternion) {
  2575. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2576. },
  2577. fromArray: function (array, offset) {
  2578. if (offset === undefined) offset = 0;
  2579. this._x = array[offset];
  2580. this._y = array[offset + 1];
  2581. this._z = array[offset + 2];
  2582. this._w = array[offset + 3];
  2583. this._onChangeCallback();
  2584. return this;
  2585. },
  2586. toArray: function (array, offset) {
  2587. if (array === undefined) array = [];
  2588. if (offset === undefined) offset = 0;
  2589. array[offset] = this._x;
  2590. array[offset + 1] = this._y;
  2591. array[offset + 2] = this._z;
  2592. array[offset + 3] = this._w;
  2593. return array;
  2594. },
  2595. fromBufferAttribute: function (attribute, index) {
  2596. this._x = attribute.getX(index);
  2597. this._y = attribute.getY(index);
  2598. this._z = attribute.getZ(index);
  2599. this._w = attribute.getW(index);
  2600. return this;
  2601. },
  2602. _onChange: function (callback) {
  2603. this._onChangeCallback = callback;
  2604. return this;
  2605. },
  2606. _onChangeCallback: function () {}
  2607. });
  2608. /**
  2609. * @author mrdoob / http://mrdoob.com/
  2610. * @author kile / http://kile.stravaganza.org/
  2611. * @author philogb / http://blog.thejit.org/
  2612. * @author mikael emtinger / http://gomo.se/
  2613. * @author egraether / http://egraether.com/
  2614. * @author WestLangley / http://github.com/WestLangley
  2615. */
  2616. var _vector = new Vector3();
  2617. var _quaternion = new Quaternion();
  2618. function Vector3(x, y, z) {
  2619. this.x = x || 0;
  2620. this.y = y || 0;
  2621. this.z = z || 0;
  2622. }
  2623. Object.assign(Vector3.prototype, {
  2624. isVector3: true,
  2625. set: function (x, y, z) {
  2626. this.x = x;
  2627. this.y = y;
  2628. this.z = z;
  2629. return this;
  2630. },
  2631. setScalar: function (scalar) {
  2632. this.x = scalar;
  2633. this.y = scalar;
  2634. this.z = scalar;
  2635. return this;
  2636. },
  2637. setX: function (x) {
  2638. this.x = x;
  2639. return this;
  2640. },
  2641. setY: function (y) {
  2642. this.y = y;
  2643. return this;
  2644. },
  2645. setZ: function (z) {
  2646. this.z = z;
  2647. return this;
  2648. },
  2649. setComponent: function (index, value) {
  2650. switch (index) {
  2651. case 0:
  2652. this.x = value;
  2653. break;
  2654. case 1:
  2655. this.y = value;
  2656. break;
  2657. case 2:
  2658. this.z = value;
  2659. break;
  2660. default:
  2661. throw new Error('index is out of range: ' + index);
  2662. }
  2663. return this;
  2664. },
  2665. getComponent: function (index) {
  2666. switch (index) {
  2667. case 0:
  2668. return this.x;
  2669. case 1:
  2670. return this.y;
  2671. case 2:
  2672. return this.z;
  2673. default:
  2674. throw new Error('index is out of range: ' + index);
  2675. }
  2676. },
  2677. clone: function () {
  2678. return new this.constructor(this.x, this.y, this.z);
  2679. },
  2680. copy: function (v) {
  2681. this.x = v.x;
  2682. this.y = v.y;
  2683. this.z = v.z;
  2684. return this;
  2685. },
  2686. add: function (v, w) {
  2687. if (w !== undefined) {
  2688. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2689. return this.addVectors(v, w);
  2690. }
  2691. this.x += v.x;
  2692. this.y += v.y;
  2693. this.z += v.z;
  2694. return this;
  2695. },
  2696. addScalar: function (s) {
  2697. this.x += s;
  2698. this.y += s;
  2699. this.z += s;
  2700. return this;
  2701. },
  2702. addVectors: function (a, b) {
  2703. this.x = a.x + b.x;
  2704. this.y = a.y + b.y;
  2705. this.z = a.z + b.z;
  2706. return this;
  2707. },
  2708. addScaledVector: function (v, s) {
  2709. this.x += v.x * s;
  2710. this.y += v.y * s;
  2711. this.z += v.z * s;
  2712. return this;
  2713. },
  2714. sub: function (v, w) {
  2715. if (w !== undefined) {
  2716. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2717. return this.subVectors(v, w);
  2718. }
  2719. this.x -= v.x;
  2720. this.y -= v.y;
  2721. this.z -= v.z;
  2722. return this;
  2723. },
  2724. subScalar: function (s) {
  2725. this.x -= s;
  2726. this.y -= s;
  2727. this.z -= s;
  2728. return this;
  2729. },
  2730. subVectors: function (a, b) {
  2731. this.x = a.x - b.x;
  2732. this.y = a.y - b.y;
  2733. this.z = a.z - b.z;
  2734. return this;
  2735. },
  2736. multiply: function (v, w) {
  2737. if (w !== undefined) {
  2738. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2739. return this.multiplyVectors(v, w);
  2740. }
  2741. this.x *= v.x;
  2742. this.y *= v.y;
  2743. this.z *= v.z;
  2744. return this;
  2745. },
  2746. multiplyScalar: function (scalar) {
  2747. this.x *= scalar;
  2748. this.y *= scalar;
  2749. this.z *= scalar;
  2750. return this;
  2751. },
  2752. multiplyVectors: function (a, b) {
  2753. this.x = a.x * b.x;
  2754. this.y = a.y * b.y;
  2755. this.z = a.z * b.z;
  2756. return this;
  2757. },
  2758. applyEuler: function (euler) {
  2759. if (!(euler && euler.isEuler)) {
  2760. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2761. }
  2762. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2763. },
  2764. applyAxisAngle: function (axis, angle) {
  2765. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2766. },
  2767. applyMatrix3: function (m) {
  2768. var x = this.x,
  2769. y = this.y,
  2770. z = this.z;
  2771. var e = m.elements;
  2772. this.x = e[0] * x + e[3] * y + e[6] * z;
  2773. this.y = e[1] * x + e[4] * y + e[7] * z;
  2774. this.z = e[2] * x + e[5] * y + e[8] * z;
  2775. return this;
  2776. },
  2777. applyNormalMatrix: function (m) {
  2778. return this.applyMatrix3(m).normalize();
  2779. },
  2780. applyMatrix4: function (m) {
  2781. var x = this.x,
  2782. y = this.y,
  2783. z = this.z;
  2784. var e = m.elements;
  2785. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2786. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2787. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2788. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2789. return this;
  2790. },
  2791. applyQuaternion: function (q) {
  2792. var x = this.x,
  2793. y = this.y,
  2794. z = this.z;
  2795. var qx = q.x,
  2796. qy = q.y,
  2797. qz = q.z,
  2798. qw = q.w; // calculate quat * vector
  2799. var ix = qw * x + qy * z - qz * y;
  2800. var iy = qw * y + qz * x - qx * z;
  2801. var iz = qw * z + qx * y - qy * x;
  2802. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2803. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2804. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2805. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2806. return this;
  2807. },
  2808. project: function (camera) {
  2809. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2810. },
  2811. unproject: function (camera) {
  2812. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2813. },
  2814. transformDirection: function (m) {
  2815. // input: THREE.Matrix4 affine matrix
  2816. // vector interpreted as a direction
  2817. var x = this.x,
  2818. y = this.y,
  2819. z = this.z;
  2820. var e = m.elements;
  2821. this.x = e[0] * x + e[4] * y + e[8] * z;
  2822. this.y = e[1] * x + e[5] * y + e[9] * z;
  2823. this.z = e[2] * x + e[6] * y + e[10] * z;
  2824. return this.normalize();
  2825. },
  2826. divide: function (v) {
  2827. this.x /= v.x;
  2828. this.y /= v.y;
  2829. this.z /= v.z;
  2830. return this;
  2831. },
  2832. divideScalar: function (scalar) {
  2833. return this.multiplyScalar(1 / scalar);
  2834. },
  2835. min: function (v) {
  2836. this.x = Math.min(this.x, v.x);
  2837. this.y = Math.min(this.y, v.y);
  2838. this.z = Math.min(this.z, v.z);
  2839. return this;
  2840. },
  2841. max: function (v) {
  2842. this.x = Math.max(this.x, v.x);
  2843. this.y = Math.max(this.y, v.y);
  2844. this.z = Math.max(this.z, v.z);
  2845. return this;
  2846. },
  2847. clamp: function (min, max) {
  2848. // assumes min < max, componentwise
  2849. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2850. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2851. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2852. return this;
  2853. },
  2854. clampScalar: function (minVal, maxVal) {
  2855. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2856. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2857. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2858. return this;
  2859. },
  2860. clampLength: function (min, max) {
  2861. var length = this.length();
  2862. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2863. },
  2864. floor: function () {
  2865. this.x = Math.floor(this.x);
  2866. this.y = Math.floor(this.y);
  2867. this.z = Math.floor(this.z);
  2868. return this;
  2869. },
  2870. ceil: function () {
  2871. this.x = Math.ceil(this.x);
  2872. this.y = Math.ceil(this.y);
  2873. this.z = Math.ceil(this.z);
  2874. return this;
  2875. },
  2876. round: function () {
  2877. this.x = Math.round(this.x);
  2878. this.y = Math.round(this.y);
  2879. this.z = Math.round(this.z);
  2880. return this;
  2881. },
  2882. roundToZero: function () {
  2883. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2884. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2885. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2886. return this;
  2887. },
  2888. negate: function () {
  2889. this.x = -this.x;
  2890. this.y = -this.y;
  2891. this.z = -this.z;
  2892. return this;
  2893. },
  2894. dot: function (v) {
  2895. return this.x * v.x + this.y * v.y + this.z * v.z;
  2896. },
  2897. // TODO lengthSquared?
  2898. lengthSq: function () {
  2899. return this.x * this.x + this.y * this.y + this.z * this.z;
  2900. },
  2901. length: function () {
  2902. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2903. },
  2904. manhattanLength: function () {
  2905. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2906. },
  2907. normalize: function () {
  2908. return this.divideScalar(this.length() || 1);
  2909. },
  2910. setLength: function (length) {
  2911. return this.normalize().multiplyScalar(length);
  2912. },
  2913. lerp: function (v, alpha) {
  2914. this.x += (v.x - this.x) * alpha;
  2915. this.y += (v.y - this.y) * alpha;
  2916. this.z += (v.z - this.z) * alpha;
  2917. return this;
  2918. },
  2919. lerpVectors: function (v1, v2, alpha) {
  2920. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2921. },
  2922. cross: function (v, w) {
  2923. if (w !== undefined) {
  2924. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2925. return this.crossVectors(v, w);
  2926. }
  2927. return this.crossVectors(this, v);
  2928. },
  2929. crossVectors: function (a, b) {
  2930. var ax = a.x,
  2931. ay = a.y,
  2932. az = a.z;
  2933. var bx = b.x,
  2934. by = b.y,
  2935. bz = b.z;
  2936. this.x = ay * bz - az * by;
  2937. this.y = az * bx - ax * bz;
  2938. this.z = ax * by - ay * bx;
  2939. return this;
  2940. },
  2941. projectOnVector: function (v) {
  2942. var denominator = v.lengthSq();
  2943. if (denominator === 0) return this.set(0, 0, 0);
  2944. var scalar = v.dot(this) / denominator;
  2945. return this.copy(v).multiplyScalar(scalar);
  2946. },
  2947. projectOnPlane: function (planeNormal) {
  2948. _vector.copy(this).projectOnVector(planeNormal);
  2949. return this.sub(_vector);
  2950. },
  2951. reflect: function (normal) {
  2952. // reflect incident vector off plane orthogonal to normal
  2953. // normal is assumed to have unit length
  2954. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2955. },
  2956. angleTo: function (v) {
  2957. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2958. if (denominator === 0) return Math.PI / 2;
  2959. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2960. return Math.acos(MathUtils.clamp(theta, -1, 1));
  2961. },
  2962. distanceTo: function (v) {
  2963. return Math.sqrt(this.distanceToSquared(v));
  2964. },
  2965. distanceToSquared: function (v) {
  2966. var dx = this.x - v.x,
  2967. dy = this.y - v.y,
  2968. dz = this.z - v.z;
  2969. return dx * dx + dy * dy + dz * dz;
  2970. },
  2971. manhattanDistanceTo: function (v) {
  2972. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2973. },
  2974. setFromSpherical: function (s) {
  2975. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2976. },
  2977. setFromSphericalCoords: function (radius, phi, theta) {
  2978. var sinPhiRadius = Math.sin(phi) * radius;
  2979. this.x = sinPhiRadius * Math.sin(theta);
  2980. this.y = Math.cos(phi) * radius;
  2981. this.z = sinPhiRadius * Math.cos(theta);
  2982. return this;
  2983. },
  2984. setFromCylindrical: function (c) {
  2985. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2986. },
  2987. setFromCylindricalCoords: function (radius, theta, y) {
  2988. this.x = radius * Math.sin(theta);
  2989. this.y = y;
  2990. this.z = radius * Math.cos(theta);
  2991. return this;
  2992. },
  2993. setFromMatrixPosition: function (m) {
  2994. var e = m.elements;
  2995. this.x = e[12];
  2996. this.y = e[13];
  2997. this.z = e[14];
  2998. return this;
  2999. },
  3000. setFromMatrixScale: function (m) {
  3001. var sx = this.setFromMatrixColumn(m, 0).length();
  3002. var sy = this.setFromMatrixColumn(m, 1).length();
  3003. var sz = this.setFromMatrixColumn(m, 2).length();
  3004. this.x = sx;
  3005. this.y = sy;
  3006. this.z = sz;
  3007. return this;
  3008. },
  3009. setFromMatrixColumn: function (m, index) {
  3010. return this.fromArray(m.elements, index * 4);
  3011. },
  3012. setFromMatrix3Column: function (m, index) {
  3013. return this.fromArray(m.elements, index * 3);
  3014. },
  3015. equals: function (v) {
  3016. return v.x === this.x && v.y === this.y && v.z === this.z;
  3017. },
  3018. fromArray: function (array, offset) {
  3019. if (offset === undefined) offset = 0;
  3020. this.x = array[offset];
  3021. this.y = array[offset + 1];
  3022. this.z = array[offset + 2];
  3023. return this;
  3024. },
  3025. toArray: function (array, offset) {
  3026. if (array === undefined) array = [];
  3027. if (offset === undefined) offset = 0;
  3028. array[offset] = this.x;
  3029. array[offset + 1] = this.y;
  3030. array[offset + 2] = this.z;
  3031. return array;
  3032. },
  3033. fromBufferAttribute: function (attribute, index, offset) {
  3034. if (offset !== undefined) {
  3035. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3036. }
  3037. this.x = attribute.getX(index);
  3038. this.y = attribute.getY(index);
  3039. this.z = attribute.getZ(index);
  3040. return this;
  3041. }
  3042. });
  3043. var _v1 = new Vector3();
  3044. var _m1 = new Matrix4();
  3045. var _zero = new Vector3(0, 0, 0);
  3046. var _one = new Vector3(1, 1, 1);
  3047. var _x = new Vector3();
  3048. var _y = new Vector3();
  3049. var _z = new Vector3();
  3050. /**
  3051. * @author mrdoob / http://mrdoob.com/
  3052. * @author supereggbert / http://www.paulbrunt.co.uk/
  3053. * @author philogb / http://blog.thejit.org/
  3054. * @author jordi_ros / http://plattsoft.com
  3055. * @author D1plo1d / http://github.com/D1plo1d
  3056. * @author alteredq / http://alteredqualia.com/
  3057. * @author mikael emtinger / http://gomo.se/
  3058. * @author timknip / http://www.floorplanner.com/
  3059. * @author bhouston / http://clara.io
  3060. * @author WestLangley / http://github.com/WestLangley
  3061. */
  3062. function Matrix4() {
  3063. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3064. if (arguments.length > 0) {
  3065. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3066. }
  3067. }
  3068. Object.assign(Matrix4.prototype, {
  3069. isMatrix4: true,
  3070. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3071. var te = this.elements;
  3072. te[0] = n11;
  3073. te[4] = n12;
  3074. te[8] = n13;
  3075. te[12] = n14;
  3076. te[1] = n21;
  3077. te[5] = n22;
  3078. te[9] = n23;
  3079. te[13] = n24;
  3080. te[2] = n31;
  3081. te[6] = n32;
  3082. te[10] = n33;
  3083. te[14] = n34;
  3084. te[3] = n41;
  3085. te[7] = n42;
  3086. te[11] = n43;
  3087. te[15] = n44;
  3088. return this;
  3089. },
  3090. identity: function () {
  3091. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3092. return this;
  3093. },
  3094. clone: function () {
  3095. return new Matrix4().fromArray(this.elements);
  3096. },
  3097. copy: function (m) {
  3098. var te = this.elements;
  3099. var me = m.elements;
  3100. te[0] = me[0];
  3101. te[1] = me[1];
  3102. te[2] = me[2];
  3103. te[3] = me[3];
  3104. te[4] = me[4];
  3105. te[5] = me[5];
  3106. te[6] = me[6];
  3107. te[7] = me[7];
  3108. te[8] = me[8];
  3109. te[9] = me[9];
  3110. te[10] = me[10];
  3111. te[11] = me[11];
  3112. te[12] = me[12];
  3113. te[13] = me[13];
  3114. te[14] = me[14];
  3115. te[15] = me[15];
  3116. return this;
  3117. },
  3118. copyPosition: function (m) {
  3119. var te = this.elements,
  3120. me = m.elements;
  3121. te[12] = me[12];
  3122. te[13] = me[13];
  3123. te[14] = me[14];
  3124. return this;
  3125. },
  3126. extractBasis: function (xAxis, yAxis, zAxis) {
  3127. xAxis.setFromMatrixColumn(this, 0);
  3128. yAxis.setFromMatrixColumn(this, 1);
  3129. zAxis.setFromMatrixColumn(this, 2);
  3130. return this;
  3131. },
  3132. makeBasis: function (xAxis, yAxis, zAxis) {
  3133. 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);
  3134. return this;
  3135. },
  3136. extractRotation: function (m) {
  3137. // this method does not support reflection matrices
  3138. var te = this.elements;
  3139. var me = m.elements;
  3140. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  3141. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  3142. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  3143. te[0] = me[0] * scaleX;
  3144. te[1] = me[1] * scaleX;
  3145. te[2] = me[2] * scaleX;
  3146. te[3] = 0;
  3147. te[4] = me[4] * scaleY;
  3148. te[5] = me[5] * scaleY;
  3149. te[6] = me[6] * scaleY;
  3150. te[7] = 0;
  3151. te[8] = me[8] * scaleZ;
  3152. te[9] = me[9] * scaleZ;
  3153. te[10] = me[10] * scaleZ;
  3154. te[11] = 0;
  3155. te[12] = 0;
  3156. te[13] = 0;
  3157. te[14] = 0;
  3158. te[15] = 1;
  3159. return this;
  3160. },
  3161. makeRotationFromEuler: function (euler) {
  3162. if (!(euler && euler.isEuler)) {
  3163. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3164. }
  3165. var te = this.elements;
  3166. var x = euler.x,
  3167. y = euler.y,
  3168. z = euler.z;
  3169. var a = Math.cos(x),
  3170. b = Math.sin(x);
  3171. var c = Math.cos(y),
  3172. d = Math.sin(y);
  3173. var e = Math.cos(z),
  3174. f = Math.sin(z);
  3175. if (euler.order === 'XYZ') {
  3176. var ae = a * e,
  3177. af = a * f,
  3178. be = b * e,
  3179. bf = b * f;
  3180. te[0] = c * e;
  3181. te[4] = -c * f;
  3182. te[8] = d;
  3183. te[1] = af + be * d;
  3184. te[5] = ae - bf * d;
  3185. te[9] = -b * c;
  3186. te[2] = bf - ae * d;
  3187. te[6] = be + af * d;
  3188. te[10] = a * c;
  3189. } else if (euler.order === 'YXZ') {
  3190. var ce = c * e,
  3191. cf = c * f,
  3192. de = d * e,
  3193. df = d * f;
  3194. te[0] = ce + df * b;
  3195. te[4] = de * b - cf;
  3196. te[8] = a * d;
  3197. te[1] = a * f;
  3198. te[5] = a * e;
  3199. te[9] = -b;
  3200. te[2] = cf * b - de;
  3201. te[6] = df + ce * b;
  3202. te[10] = a * c;
  3203. } else if (euler.order === 'ZXY') {
  3204. var ce = c * e,
  3205. cf = c * f,
  3206. de = d * e,
  3207. df = d * f;
  3208. te[0] = ce - df * b;
  3209. te[4] = -a * f;
  3210. te[8] = de + cf * b;
  3211. te[1] = cf + de * b;
  3212. te[5] = a * e;
  3213. te[9] = df - ce * b;
  3214. te[2] = -a * d;
  3215. te[6] = b;
  3216. te[10] = a * c;
  3217. } else if (euler.order === 'ZYX') {
  3218. var ae = a * e,
  3219. af = a * f,
  3220. be = b * e,
  3221. bf = b * f;
  3222. te[0] = c * e;
  3223. te[4] = be * d - af;
  3224. te[8] = ae * d + bf;
  3225. te[1] = c * f;
  3226. te[5] = bf * d + ae;
  3227. te[9] = af * d - be;
  3228. te[2] = -d;
  3229. te[6] = b * c;
  3230. te[10] = a * c;
  3231. } else if (euler.order === 'YZX') {
  3232. var ac = a * c,
  3233. ad = a * d,
  3234. bc = b * c,
  3235. bd = b * d;
  3236. te[0] = c * e;
  3237. te[4] = bd - ac * f;
  3238. te[8] = bc * f + ad;
  3239. te[1] = f;
  3240. te[5] = a * e;
  3241. te[9] = -b * e;
  3242. te[2] = -d * e;
  3243. te[6] = ad * f + bc;
  3244. te[10] = ac - bd * f;
  3245. } else if (euler.order === 'XZY') {
  3246. var ac = a * c,
  3247. ad = a * d,
  3248. bc = b * c,
  3249. bd = b * d;
  3250. te[0] = c * e;
  3251. te[4] = -f;
  3252. te[8] = d * e;
  3253. te[1] = ac * f + bd;
  3254. te[5] = a * e;
  3255. te[9] = ad * f - bc;
  3256. te[2] = bc * f - ad;
  3257. te[6] = b * e;
  3258. te[10] = bd * f + ac;
  3259. } // bottom row
  3260. te[3] = 0;
  3261. te[7] = 0;
  3262. te[11] = 0; // last column
  3263. te[12] = 0;
  3264. te[13] = 0;
  3265. te[14] = 0;
  3266. te[15] = 1;
  3267. return this;
  3268. },
  3269. makeRotationFromQuaternion: function (q) {
  3270. return this.compose(_zero, q, _one);
  3271. },
  3272. lookAt: function (eye, target, up) {
  3273. var te = this.elements;
  3274. _z.subVectors(eye, target);
  3275. if (_z.lengthSq() === 0) {
  3276. // eye and target are in the same position
  3277. _z.z = 1;
  3278. }
  3279. _z.normalize();
  3280. _x.crossVectors(up, _z);
  3281. if (_x.lengthSq() === 0) {
  3282. // up and z are parallel
  3283. if (Math.abs(up.z) === 1) {
  3284. _z.x += 0.0001;
  3285. } else {
  3286. _z.z += 0.0001;
  3287. }
  3288. _z.normalize();
  3289. _x.crossVectors(up, _z);
  3290. }
  3291. _x.normalize();
  3292. _y.crossVectors(_z, _x);
  3293. te[0] = _x.x;
  3294. te[4] = _y.x;
  3295. te[8] = _z.x;
  3296. te[1] = _x.y;
  3297. te[5] = _y.y;
  3298. te[9] = _z.y;
  3299. te[2] = _x.z;
  3300. te[6] = _y.z;
  3301. te[10] = _z.z;
  3302. return this;
  3303. },
  3304. multiply: function (m, n) {
  3305. if (n !== undefined) {
  3306. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3307. return this.multiplyMatrices(m, n);
  3308. }
  3309. return this.multiplyMatrices(this, m);
  3310. },
  3311. premultiply: function (m) {
  3312. return this.multiplyMatrices(m, this);
  3313. },
  3314. multiplyMatrices: function (a, b) {
  3315. var ae = a.elements;
  3316. var be = b.elements;
  3317. var te = this.elements;
  3318. var a11 = ae[0],
  3319. a12 = ae[4],
  3320. a13 = ae[8],
  3321. a14 = ae[12];
  3322. var a21 = ae[1],
  3323. a22 = ae[5],
  3324. a23 = ae[9],
  3325. a24 = ae[13];
  3326. var a31 = ae[2],
  3327. a32 = ae[6],
  3328. a33 = ae[10],
  3329. a34 = ae[14];
  3330. var a41 = ae[3],
  3331. a42 = ae[7],
  3332. a43 = ae[11],
  3333. a44 = ae[15];
  3334. var b11 = be[0],
  3335. b12 = be[4],
  3336. b13 = be[8],
  3337. b14 = be[12];
  3338. var b21 = be[1],
  3339. b22 = be[5],
  3340. b23 = be[9],
  3341. b24 = be[13];
  3342. var b31 = be[2],
  3343. b32 = be[6],
  3344. b33 = be[10],
  3345. b34 = be[14];
  3346. var b41 = be[3],
  3347. b42 = be[7],
  3348. b43 = be[11],
  3349. b44 = be[15];
  3350. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3351. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3352. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3353. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3354. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3355. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3356. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3357. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3358. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3359. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3360. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3361. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3362. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3363. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3364. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3365. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3366. return this;
  3367. },
  3368. multiplyScalar: function (s) {
  3369. var te = this.elements;
  3370. te[0] *= s;
  3371. te[4] *= s;
  3372. te[8] *= s;
  3373. te[12] *= s;
  3374. te[1] *= s;
  3375. te[5] *= s;
  3376. te[9] *= s;
  3377. te[13] *= s;
  3378. te[2] *= s;
  3379. te[6] *= s;
  3380. te[10] *= s;
  3381. te[14] *= s;
  3382. te[3] *= s;
  3383. te[7] *= s;
  3384. te[11] *= s;
  3385. te[15] *= s;
  3386. return this;
  3387. },
  3388. determinant: function () {
  3389. var te = this.elements;
  3390. var n11 = te[0],
  3391. n12 = te[4],
  3392. n13 = te[8],
  3393. n14 = te[12];
  3394. var n21 = te[1],
  3395. n22 = te[5],
  3396. n23 = te[9],
  3397. n24 = te[13];
  3398. var n31 = te[2],
  3399. n32 = te[6],
  3400. n33 = te[10],
  3401. n34 = te[14];
  3402. var n41 = te[3],
  3403. n42 = te[7],
  3404. n43 = te[11],
  3405. n44 = te[15]; //TODO: make this more efficient
  3406. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3407. 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);
  3408. },
  3409. transpose: function () {
  3410. var te = this.elements;
  3411. var tmp;
  3412. tmp = te[1];
  3413. te[1] = te[4];
  3414. te[4] = tmp;
  3415. tmp = te[2];
  3416. te[2] = te[8];
  3417. te[8] = tmp;
  3418. tmp = te[6];
  3419. te[6] = te[9];
  3420. te[9] = tmp;
  3421. tmp = te[3];
  3422. te[3] = te[12];
  3423. te[12] = tmp;
  3424. tmp = te[7];
  3425. te[7] = te[13];
  3426. te[13] = tmp;
  3427. tmp = te[11];
  3428. te[11] = te[14];
  3429. te[14] = tmp;
  3430. return this;
  3431. },
  3432. setPosition: function (x, y, z) {
  3433. var te = this.elements;
  3434. if (x.isVector3) {
  3435. te[12] = x.x;
  3436. te[13] = x.y;
  3437. te[14] = x.z;
  3438. } else {
  3439. te[12] = x;
  3440. te[13] = y;
  3441. te[14] = z;
  3442. }
  3443. return this;
  3444. },
  3445. getInverse: function (m, throwOnDegenerate) {
  3446. if (throwOnDegenerate !== undefined) {
  3447. console.warn("THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate.");
  3448. } // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3449. var te = this.elements,
  3450. me = m.elements,
  3451. n11 = me[0],
  3452. n21 = me[1],
  3453. n31 = me[2],
  3454. n41 = me[3],
  3455. n12 = me[4],
  3456. n22 = me[5],
  3457. n32 = me[6],
  3458. n42 = me[7],
  3459. n13 = me[8],
  3460. n23 = me[9],
  3461. n33 = me[10],
  3462. n43 = me[11],
  3463. n14 = me[12],
  3464. n24 = me[13],
  3465. n34 = me[14],
  3466. n44 = me[15],
  3467. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3468. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3469. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3470. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3471. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3472. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3473. var detInv = 1 / det;
  3474. te[0] = t11 * detInv;
  3475. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3476. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3477. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3478. te[4] = t12 * detInv;
  3479. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3480. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3481. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3482. te[8] = t13 * detInv;
  3483. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3484. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3485. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3486. te[12] = t14 * detInv;
  3487. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3488. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3489. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3490. return this;
  3491. },
  3492. scale: function (v) {
  3493. var te = this.elements;
  3494. var x = v.x,
  3495. y = v.y,
  3496. z = v.z;
  3497. te[0] *= x;
  3498. te[4] *= y;
  3499. te[8] *= z;
  3500. te[1] *= x;
  3501. te[5] *= y;
  3502. te[9] *= z;
  3503. te[2] *= x;
  3504. te[6] *= y;
  3505. te[10] *= z;
  3506. te[3] *= x;
  3507. te[7] *= y;
  3508. te[11] *= z;
  3509. return this;
  3510. },
  3511. getMaxScaleOnAxis: function () {
  3512. var te = this.elements;
  3513. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3514. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3515. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3516. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3517. },
  3518. makeTranslation: function (x, y, z) {
  3519. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3520. return this;
  3521. },
  3522. makeRotationX: function (theta) {
  3523. var c = Math.cos(theta),
  3524. s = Math.sin(theta);
  3525. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3526. return this;
  3527. },
  3528. makeRotationY: function (theta) {
  3529. var c = Math.cos(theta),
  3530. s = Math.sin(theta);
  3531. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3532. return this;
  3533. },
  3534. makeRotationZ: function (theta) {
  3535. var c = Math.cos(theta),
  3536. s = Math.sin(theta);
  3537. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3538. return this;
  3539. },
  3540. makeRotationAxis: function (axis, angle) {
  3541. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3542. var c = Math.cos(angle);
  3543. var s = Math.sin(angle);
  3544. var t = 1 - c;
  3545. var x = axis.x,
  3546. y = axis.y,
  3547. z = axis.z;
  3548. var tx = t * x,
  3549. ty = t * y;
  3550. 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);
  3551. return this;
  3552. },
  3553. makeScale: function (x, y, z) {
  3554. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3555. return this;
  3556. },
  3557. makeShear: function (x, y, z) {
  3558. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3559. return this;
  3560. },
  3561. compose: function (position, quaternion, scale) {
  3562. var te = this.elements;
  3563. var x = quaternion._x,
  3564. y = quaternion._y,
  3565. z = quaternion._z,
  3566. w = quaternion._w;
  3567. var x2 = x + x,
  3568. y2 = y + y,
  3569. z2 = z + z;
  3570. var xx = x * x2,
  3571. xy = x * y2,
  3572. xz = x * z2;
  3573. var yy = y * y2,
  3574. yz = y * z2,
  3575. zz = z * z2;
  3576. var wx = w * x2,
  3577. wy = w * y2,
  3578. wz = w * z2;
  3579. var sx = scale.x,
  3580. sy = scale.y,
  3581. sz = scale.z;
  3582. te[0] = (1 - (yy + zz)) * sx;
  3583. te[1] = (xy + wz) * sx;
  3584. te[2] = (xz - wy) * sx;
  3585. te[3] = 0;
  3586. te[4] = (xy - wz) * sy;
  3587. te[5] = (1 - (xx + zz)) * sy;
  3588. te[6] = (yz + wx) * sy;
  3589. te[7] = 0;
  3590. te[8] = (xz + wy) * sz;
  3591. te[9] = (yz - wx) * sz;
  3592. te[10] = (1 - (xx + yy)) * sz;
  3593. te[11] = 0;
  3594. te[12] = position.x;
  3595. te[13] = position.y;
  3596. te[14] = position.z;
  3597. te[15] = 1;
  3598. return this;
  3599. },
  3600. decompose: function (position, quaternion, scale) {
  3601. var te = this.elements;
  3602. var sx = _v1.set(te[0], te[1], te[2]).length();
  3603. var sy = _v1.set(te[4], te[5], te[6]).length();
  3604. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3605. var det = this.determinant();
  3606. if (det < 0) sx = -sx;
  3607. position.x = te[12];
  3608. position.y = te[13];
  3609. position.z = te[14]; // scale the rotation part
  3610. _m1.copy(this);
  3611. var invSX = 1 / sx;
  3612. var invSY = 1 / sy;
  3613. var invSZ = 1 / sz;
  3614. _m1.elements[0] *= invSX;
  3615. _m1.elements[1] *= invSX;
  3616. _m1.elements[2] *= invSX;
  3617. _m1.elements[4] *= invSY;
  3618. _m1.elements[5] *= invSY;
  3619. _m1.elements[6] *= invSY;
  3620. _m1.elements[8] *= invSZ;
  3621. _m1.elements[9] *= invSZ;
  3622. _m1.elements[10] *= invSZ;
  3623. quaternion.setFromRotationMatrix(_m1);
  3624. scale.x = sx;
  3625. scale.y = sy;
  3626. scale.z = sz;
  3627. return this;
  3628. },
  3629. makePerspective: function (left, right, top, bottom, near, far) {
  3630. if (far === undefined) {
  3631. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3632. }
  3633. var te = this.elements;
  3634. var x = 2 * near / (right - left);
  3635. var y = 2 * near / (top - bottom);
  3636. var a = (right + left) / (right - left);
  3637. var b = (top + bottom) / (top - bottom);
  3638. var c = -(far + near) / (far - near);
  3639. var d = -2 * far * near / (far - near);
  3640. te[0] = x;
  3641. te[4] = 0;
  3642. te[8] = a;
  3643. te[12] = 0;
  3644. te[1] = 0;
  3645. te[5] = y;
  3646. te[9] = b;
  3647. te[13] = 0;
  3648. te[2] = 0;
  3649. te[6] = 0;
  3650. te[10] = c;
  3651. te[14] = d;
  3652. te[3] = 0;
  3653. te[7] = 0;
  3654. te[11] = -1;
  3655. te[15] = 0;
  3656. return this;
  3657. },
  3658. makeOrthographic: function (left, right, top, bottom, near, far) {
  3659. var te = this.elements;
  3660. var w = 1.0 / (right - left);
  3661. var h = 1.0 / (top - bottom);
  3662. var p = 1.0 / (far - near);
  3663. var x = (right + left) * w;
  3664. var y = (top + bottom) * h;
  3665. var z = (far + near) * p;
  3666. te[0] = 2 * w;
  3667. te[4] = 0;
  3668. te[8] = 0;
  3669. te[12] = -x;
  3670. te[1] = 0;
  3671. te[5] = 2 * h;
  3672. te[9] = 0;
  3673. te[13] = -y;
  3674. te[2] = 0;
  3675. te[6] = 0;
  3676. te[10] = -2 * p;
  3677. te[14] = -z;
  3678. te[3] = 0;
  3679. te[7] = 0;
  3680. te[11] = 0;
  3681. te[15] = 1;
  3682. return this;
  3683. },
  3684. equals: function (matrix) {
  3685. var te = this.elements;
  3686. var me = matrix.elements;
  3687. for (var i = 0; i < 16; i++) {
  3688. if (te[i] !== me[i]) return false;
  3689. }
  3690. return true;
  3691. },
  3692. fromArray: function (array, offset) {
  3693. if (offset === undefined) offset = 0;
  3694. for (var i = 0; i < 16; i++) {
  3695. this.elements[i] = array[i + offset];
  3696. }
  3697. return this;
  3698. },
  3699. toArray: function (array, offset) {
  3700. if (array === undefined) array = [];
  3701. if (offset === undefined) offset = 0;
  3702. var te = this.elements;
  3703. array[offset] = te[0];
  3704. array[offset + 1] = te[1];
  3705. array[offset + 2] = te[2];
  3706. array[offset + 3] = te[3];
  3707. array[offset + 4] = te[4];
  3708. array[offset + 5] = te[5];
  3709. array[offset + 6] = te[6];
  3710. array[offset + 7] = te[7];
  3711. array[offset + 8] = te[8];
  3712. array[offset + 9] = te[9];
  3713. array[offset + 10] = te[10];
  3714. array[offset + 11] = te[11];
  3715. array[offset + 12] = te[12];
  3716. array[offset + 13] = te[13];
  3717. array[offset + 14] = te[14];
  3718. array[offset + 15] = te[15];
  3719. return array;
  3720. }
  3721. });
  3722. /**
  3723. * @author mrdoob / http://mrdoob.com/
  3724. * @author WestLangley / http://github.com/WestLangley
  3725. * @author bhouston / http://clara.io
  3726. */
  3727. var _matrix = new Matrix4();
  3728. var _quaternion$1 = new Quaternion();
  3729. function Euler(x, y, z, order) {
  3730. this._x = x || 0;
  3731. this._y = y || 0;
  3732. this._z = z || 0;
  3733. this._order = order || Euler.DefaultOrder;
  3734. }
  3735. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  3736. Euler.DefaultOrder = 'XYZ';
  3737. Object.defineProperties(Euler.prototype, {
  3738. x: {
  3739. get: function () {
  3740. return this._x;
  3741. },
  3742. set: function (value) {
  3743. this._x = value;
  3744. this._onChangeCallback();
  3745. }
  3746. },
  3747. y: {
  3748. get: function () {
  3749. return this._y;
  3750. },
  3751. set: function (value) {
  3752. this._y = value;
  3753. this._onChangeCallback();
  3754. }
  3755. },
  3756. z: {
  3757. get: function () {
  3758. return this._z;
  3759. },
  3760. set: function (value) {
  3761. this._z = value;
  3762. this._onChangeCallback();
  3763. }
  3764. },
  3765. order: {
  3766. get: function () {
  3767. return this._order;
  3768. },
  3769. set: function (value) {
  3770. this._order = value;
  3771. this._onChangeCallback();
  3772. }
  3773. }
  3774. });
  3775. Object.assign(Euler.prototype, {
  3776. isEuler: true,
  3777. set: function (x, y, z, order) {
  3778. this._x = x;
  3779. this._y = y;
  3780. this._z = z;
  3781. this._order = order || this._order;
  3782. this._onChangeCallback();
  3783. return this;
  3784. },
  3785. clone: function () {
  3786. return new this.constructor(this._x, this._y, this._z, this._order);
  3787. },
  3788. copy: function (euler) {
  3789. this._x = euler._x;
  3790. this._y = euler._y;
  3791. this._z = euler._z;
  3792. this._order = euler._order;
  3793. this._onChangeCallback();
  3794. return this;
  3795. },
  3796. setFromRotationMatrix: function (m, order, update) {
  3797. var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3798. var te = m.elements;
  3799. var m11 = te[0],
  3800. m12 = te[4],
  3801. m13 = te[8];
  3802. var m21 = te[1],
  3803. m22 = te[5],
  3804. m23 = te[9];
  3805. var m31 = te[2],
  3806. m32 = te[6],
  3807. m33 = te[10];
  3808. order = order || this._order;
  3809. if (order === 'XYZ') {
  3810. this._y = Math.asin(clamp(m13, -1, 1));
  3811. if (Math.abs(m13) < 0.9999999) {
  3812. this._x = Math.atan2(-m23, m33);
  3813. this._z = Math.atan2(-m12, m11);
  3814. } else {
  3815. this._x = Math.atan2(m32, m22);
  3816. this._z = 0;
  3817. }
  3818. } else if (order === 'YXZ') {
  3819. this._x = Math.asin(-clamp(m23, -1, 1));
  3820. if (Math.abs(m23) < 0.9999999) {
  3821. this._y = Math.atan2(m13, m33);
  3822. this._z = Math.atan2(m21, m22);
  3823. } else {
  3824. this._y = Math.atan2(-m31, m11);
  3825. this._z = 0;
  3826. }
  3827. } else if (order === 'ZXY') {
  3828. this._x = Math.asin(clamp(m32, -1, 1));
  3829. if (Math.abs(m32) < 0.9999999) {
  3830. this._y = Math.atan2(-m31, m33);
  3831. this._z = Math.atan2(-m12, m22);
  3832. } else {
  3833. this._y = 0;
  3834. this._z = Math.atan2(m21, m11);
  3835. }
  3836. } else if (order === 'ZYX') {
  3837. this._y = Math.asin(-clamp(m31, -1, 1));
  3838. if (Math.abs(m31) < 0.9999999) {
  3839. this._x = Math.atan2(m32, m33);
  3840. this._z = Math.atan2(m21, m11);
  3841. } else {
  3842. this._x = 0;
  3843. this._z = Math.atan2(-m12, m22);
  3844. }
  3845. } else if (order === 'YZX') {
  3846. this._z = Math.asin(clamp(m21, -1, 1));
  3847. if (Math.abs(m21) < 0.9999999) {
  3848. this._x = Math.atan2(-m23, m22);
  3849. this._y = Math.atan2(-m31, m11);
  3850. } else {
  3851. this._x = 0;
  3852. this._y = Math.atan2(m13, m33);
  3853. }
  3854. } else if (order === 'XZY') {
  3855. this._z = Math.asin(-clamp(m12, -1, 1));
  3856. if (Math.abs(m12) < 0.9999999) {
  3857. this._x = Math.atan2(m32, m22);
  3858. this._y = Math.atan2(m13, m11);
  3859. } else {
  3860. this._x = Math.atan2(-m23, m33);
  3861. this._y = 0;
  3862. }
  3863. } else {
  3864. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  3865. }
  3866. this._order = order;
  3867. if (update !== false) this._onChangeCallback();
  3868. return this;
  3869. },
  3870. setFromQuaternion: function (q, order, update) {
  3871. _matrix.makeRotationFromQuaternion(q);
  3872. return this.setFromRotationMatrix(_matrix, order, update);
  3873. },
  3874. setFromVector3: function (v, order) {
  3875. return this.set(v.x, v.y, v.z, order || this._order);
  3876. },
  3877. reorder: function (newOrder) {
  3878. // WARNING: this discards revolution information -bhouston
  3879. _quaternion$1.setFromEuler(this);
  3880. return this.setFromQuaternion(_quaternion$1, newOrder);
  3881. },
  3882. equals: function (euler) {
  3883. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  3884. },
  3885. fromArray: function (array) {
  3886. this._x = array[0];
  3887. this._y = array[1];
  3888. this._z = array[2];
  3889. if (array[3] !== undefined) this._order = array[3];
  3890. this._onChangeCallback();
  3891. return this;
  3892. },
  3893. toArray: function (array, offset) {
  3894. if (array === undefined) array = [];
  3895. if (offset === undefined) offset = 0;
  3896. array[offset] = this._x;
  3897. array[offset + 1] = this._y;
  3898. array[offset + 2] = this._z;
  3899. array[offset + 3] = this._order;
  3900. return array;
  3901. },
  3902. toVector3: function (optionalResult) {
  3903. if (optionalResult) {
  3904. return optionalResult.set(this._x, this._y, this._z);
  3905. } else {
  3906. return new Vector3(this._x, this._y, this._z);
  3907. }
  3908. },
  3909. _onChange: function (callback) {
  3910. this._onChangeCallback = callback;
  3911. return this;
  3912. },
  3913. _onChangeCallback: function () {}
  3914. });
  3915. /**
  3916. * @author mrdoob / http://mrdoob.com/
  3917. */
  3918. function Layers() {
  3919. this.mask = 1 | 0;
  3920. }
  3921. Object.assign(Layers.prototype, {
  3922. set: function (channel) {
  3923. this.mask = 1 << channel | 0;
  3924. },
  3925. enable: function (channel) {
  3926. this.mask |= 1 << channel | 0;
  3927. },
  3928. enableAll: function () {
  3929. this.mask = 0xffffffff | 0;
  3930. },
  3931. toggle: function (channel) {
  3932. this.mask ^= 1 << channel | 0;
  3933. },
  3934. disable: function (channel) {
  3935. this.mask &= ~(1 << channel | 0);
  3936. },
  3937. disableAll: function () {
  3938. this.mask = 0;
  3939. },
  3940. test: function (layers) {
  3941. return (this.mask & layers.mask) !== 0;
  3942. }
  3943. });
  3944. var _object3DId = 0;
  3945. var _v1$1 = new Vector3();
  3946. var _q1 = new Quaternion();
  3947. var _m1$1 = new Matrix4();
  3948. var _target = new Vector3();
  3949. var _position = new Vector3();
  3950. var _scale = new Vector3();
  3951. var _quaternion$2 = new Quaternion();
  3952. var _xAxis = new Vector3(1, 0, 0);
  3953. var _yAxis = new Vector3(0, 1, 0);
  3954. var _zAxis = new Vector3(0, 0, 1);
  3955. var _addedEvent = {
  3956. type: 'added'
  3957. };
  3958. var _removedEvent = {
  3959. type: 'removed'
  3960. };
  3961. /**
  3962. * @author mrdoob / http://mrdoob.com/
  3963. * @author mikael emtinger / http://gomo.se/
  3964. * @author alteredq / http://alteredqualia.com/
  3965. * @author WestLangley / http://github.com/WestLangley
  3966. * @author elephantatwork / www.elephantatwork.ch
  3967. */
  3968. function Object3D() {
  3969. Object.defineProperty(this, 'id', {
  3970. value: _object3DId++
  3971. });
  3972. this.uuid = MathUtils.generateUUID();
  3973. this.name = '';
  3974. this.type = 'Object3D';
  3975. this.parent = null;
  3976. this.children = [];
  3977. this.up = Object3D.DefaultUp.clone();
  3978. var position = new Vector3();
  3979. var rotation = new Euler();
  3980. var quaternion = new Quaternion();
  3981. var scale = new Vector3(1, 1, 1);
  3982. function onRotationChange() {
  3983. quaternion.setFromEuler(rotation, false);
  3984. }
  3985. function onQuaternionChange() {
  3986. rotation.setFromQuaternion(quaternion, undefined, false);
  3987. }
  3988. rotation._onChange(onRotationChange);
  3989. quaternion._onChange(onQuaternionChange);
  3990. Object.defineProperties(this, {
  3991. position: {
  3992. configurable: true,
  3993. enumerable: true,
  3994. value: position
  3995. },
  3996. rotation: {
  3997. configurable: true,
  3998. enumerable: true,
  3999. value: rotation
  4000. },
  4001. quaternion: {
  4002. configurable: true,
  4003. enumerable: true,
  4004. value: quaternion
  4005. },
  4006. scale: {
  4007. configurable: true,
  4008. enumerable: true,
  4009. value: scale
  4010. },
  4011. modelViewMatrix: {
  4012. value: new Matrix4()
  4013. },
  4014. normalMatrix: {
  4015. value: new Matrix3()
  4016. }
  4017. });
  4018. this.matrix = new Matrix4();
  4019. this.matrixWorld = new Matrix4();
  4020. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4021. this.matrixWorldNeedsUpdate = false;
  4022. this.layers = new Layers();
  4023. this.visible = true;
  4024. this.castShadow = false;
  4025. this.receiveShadow = false;
  4026. this.frustumCulled = true;
  4027. this.renderOrder = 0;
  4028. this.userData = {};
  4029. }
  4030. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4031. Object3D.DefaultMatrixAutoUpdate = true;
  4032. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4033. constructor: Object3D,
  4034. isObject3D: true,
  4035. onBeforeRender: function () {},
  4036. onAfterRender: function () {},
  4037. applyMatrix4: function (matrix) {
  4038. if (this.matrixAutoUpdate) this.updateMatrix();
  4039. this.matrix.premultiply(matrix);
  4040. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4041. },
  4042. applyQuaternion: function (q) {
  4043. this.quaternion.premultiply(q);
  4044. return this;
  4045. },
  4046. setRotationFromAxisAngle: function (axis, angle) {
  4047. // assumes axis is normalized
  4048. this.quaternion.setFromAxisAngle(axis, angle);
  4049. },
  4050. setRotationFromEuler: function (euler) {
  4051. this.quaternion.setFromEuler(euler, true);
  4052. },
  4053. setRotationFromMatrix: function (m) {
  4054. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4055. this.quaternion.setFromRotationMatrix(m);
  4056. },
  4057. setRotationFromQuaternion: function (q) {
  4058. // assumes q is normalized
  4059. this.quaternion.copy(q);
  4060. },
  4061. rotateOnAxis: function (axis, angle) {
  4062. // rotate object on axis in object space
  4063. // axis is assumed to be normalized
  4064. _q1.setFromAxisAngle(axis, angle);
  4065. this.quaternion.multiply(_q1);
  4066. return this;
  4067. },
  4068. rotateOnWorldAxis: function (axis, angle) {
  4069. // rotate object on axis in world space
  4070. // axis is assumed to be normalized
  4071. // method assumes no rotated parent
  4072. _q1.setFromAxisAngle(axis, angle);
  4073. this.quaternion.premultiply(_q1);
  4074. return this;
  4075. },
  4076. rotateX: function (angle) {
  4077. return this.rotateOnAxis(_xAxis, angle);
  4078. },
  4079. rotateY: function (angle) {
  4080. return this.rotateOnAxis(_yAxis, angle);
  4081. },
  4082. rotateZ: function (angle) {
  4083. return this.rotateOnAxis(_zAxis, angle);
  4084. },
  4085. translateOnAxis: function (axis, distance) {
  4086. // translate object by distance along axis in object space
  4087. // axis is assumed to be normalized
  4088. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  4089. this.position.add(_v1$1.multiplyScalar(distance));
  4090. return this;
  4091. },
  4092. translateX: function (distance) {
  4093. return this.translateOnAxis(_xAxis, distance);
  4094. },
  4095. translateY: function (distance) {
  4096. return this.translateOnAxis(_yAxis, distance);
  4097. },
  4098. translateZ: function (distance) {
  4099. return this.translateOnAxis(_zAxis, distance);
  4100. },
  4101. localToWorld: function (vector) {
  4102. return vector.applyMatrix4(this.matrixWorld);
  4103. },
  4104. worldToLocal: function (vector) {
  4105. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  4106. },
  4107. lookAt: function (x, y, z) {
  4108. // This method does not support objects having non-uniformly-scaled parent(s)
  4109. if (x.isVector3) {
  4110. _target.copy(x);
  4111. } else {
  4112. _target.set(x, y, z);
  4113. }
  4114. var parent = this.parent;
  4115. this.updateWorldMatrix(true, false);
  4116. _position.setFromMatrixPosition(this.matrixWorld);
  4117. if (this.isCamera || this.isLight) {
  4118. _m1$1.lookAt(_position, _target, this.up);
  4119. } else {
  4120. _m1$1.lookAt(_target, _position, this.up);
  4121. }
  4122. this.quaternion.setFromRotationMatrix(_m1$1);
  4123. if (parent) {
  4124. _m1$1.extractRotation(parent.matrixWorld);
  4125. _q1.setFromRotationMatrix(_m1$1);
  4126. this.quaternion.premultiply(_q1.inverse());
  4127. }
  4128. },
  4129. add: function (object) {
  4130. if (arguments.length > 1) {
  4131. for (var i = 0; i < arguments.length; i++) {
  4132. this.add(arguments[i]);
  4133. }
  4134. return this;
  4135. }
  4136. if (object === this) {
  4137. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4138. return this;
  4139. }
  4140. if (object && object.isObject3D) {
  4141. if (object.parent !== null) {
  4142. object.parent.remove(object);
  4143. }
  4144. object.parent = this;
  4145. this.children.push(object);
  4146. object.dispatchEvent(_addedEvent);
  4147. } else {
  4148. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4149. }
  4150. return this;
  4151. },
  4152. remove: function (object) {
  4153. if (arguments.length > 1) {
  4154. for (var i = 0; i < arguments.length; i++) {
  4155. this.remove(arguments[i]);
  4156. }
  4157. return this;
  4158. }
  4159. var index = this.children.indexOf(object);
  4160. if (index !== -1) {
  4161. object.parent = null;
  4162. this.children.splice(index, 1);
  4163. object.dispatchEvent(_removedEvent);
  4164. }
  4165. return this;
  4166. },
  4167. attach: function (object) {
  4168. // adds object as a child of this, while maintaining the object's world transform
  4169. this.updateWorldMatrix(true, false);
  4170. _m1$1.getInverse(this.matrixWorld);
  4171. if (object.parent !== null) {
  4172. object.parent.updateWorldMatrix(true, false);
  4173. _m1$1.multiply(object.parent.matrixWorld);
  4174. }
  4175. object.applyMatrix4(_m1$1);
  4176. object.updateWorldMatrix(false, false);
  4177. this.add(object);
  4178. return this;
  4179. },
  4180. getObjectById: function (id) {
  4181. return this.getObjectByProperty('id', id);
  4182. },
  4183. getObjectByName: function (name) {
  4184. return this.getObjectByProperty('name', name);
  4185. },
  4186. getObjectByProperty: function (name, value) {
  4187. if (this[name] === value) return this;
  4188. for (var i = 0, l = this.children.length; i < l; i++) {
  4189. var child = this.children[i];
  4190. var object = child.getObjectByProperty(name, value);
  4191. if (object !== undefined) {
  4192. return object;
  4193. }
  4194. }
  4195. return undefined;
  4196. },
  4197. getWorldPosition: function (target) {
  4198. if (target === undefined) {
  4199. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4200. target = new Vector3();
  4201. }
  4202. this.updateMatrixWorld(true);
  4203. return target.setFromMatrixPosition(this.matrixWorld);
  4204. },
  4205. getWorldQuaternion: function (target) {
  4206. if (target === undefined) {
  4207. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4208. target = new Quaternion();
  4209. }
  4210. this.updateMatrixWorld(true);
  4211. this.matrixWorld.decompose(_position, target, _scale);
  4212. return target;
  4213. },
  4214. getWorldScale: function (target) {
  4215. if (target === undefined) {
  4216. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4217. target = new Vector3();
  4218. }
  4219. this.updateMatrixWorld(true);
  4220. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4221. return target;
  4222. },
  4223. getWorldDirection: function (target) {
  4224. if (target === undefined) {
  4225. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4226. target = new Vector3();
  4227. }
  4228. this.updateMatrixWorld(true);
  4229. var e = this.matrixWorld.elements;
  4230. return target.set(e[8], e[9], e[10]).normalize();
  4231. },
  4232. raycast: function () {},
  4233. traverse: function (callback) {
  4234. callback(this);
  4235. var children = this.children;
  4236. for (var i = 0, l = children.length; i < l; i++) {
  4237. children[i].traverse(callback);
  4238. }
  4239. },
  4240. traverseVisible: function (callback) {
  4241. if (this.visible === false) return;
  4242. callback(this);
  4243. var children = this.children;
  4244. for (var i = 0, l = children.length; i < l; i++) {
  4245. children[i].traverseVisible(callback);
  4246. }
  4247. },
  4248. traverseAncestors: function (callback) {
  4249. var parent = this.parent;
  4250. if (parent !== null) {
  4251. callback(parent);
  4252. parent.traverseAncestors(callback);
  4253. }
  4254. },
  4255. updateMatrix: function () {
  4256. this.matrix.compose(this.position, this.quaternion, this.scale);
  4257. this.matrixWorldNeedsUpdate = true;
  4258. },
  4259. updateMatrixWorld: function (force) {
  4260. if (this.matrixAutoUpdate) this.updateMatrix();
  4261. if (this.matrixWorldNeedsUpdate || force) {
  4262. if (this.parent === null) {
  4263. this.matrixWorld.copy(this.matrix);
  4264. } else {
  4265. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4266. }
  4267. this.matrixWorldNeedsUpdate = false;
  4268. force = true;
  4269. } // update children
  4270. var children = this.children;
  4271. for (var i = 0, l = children.length; i < l; i++) {
  4272. children[i].updateMatrixWorld(force);
  4273. }
  4274. },
  4275. updateWorldMatrix: function (updateParents, updateChildren) {
  4276. var parent = this.parent;
  4277. if (updateParents === true && parent !== null) {
  4278. parent.updateWorldMatrix(true, false);
  4279. }
  4280. if (this.matrixAutoUpdate) this.updateMatrix();
  4281. if (this.parent === null) {
  4282. this.matrixWorld.copy(this.matrix);
  4283. } else {
  4284. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4285. } // update children
  4286. if (updateChildren === true) {
  4287. var children = this.children;
  4288. for (var i = 0, l = children.length; i < l; i++) {
  4289. children[i].updateWorldMatrix(false, true);
  4290. }
  4291. }
  4292. },
  4293. toJSON: function (meta) {
  4294. // meta is a string when called from JSON.stringify
  4295. var isRootObject = meta === undefined || typeof meta === 'string';
  4296. var output = {}; // meta is a hash used to collect geometries, materials.
  4297. // not providing it implies that this is the root object
  4298. // being serialized.
  4299. if (isRootObject) {
  4300. // initialize meta obj
  4301. meta = {
  4302. geometries: {},
  4303. materials: {},
  4304. textures: {},
  4305. images: {},
  4306. shapes: {}
  4307. };
  4308. output.metadata = {
  4309. version: 4.5,
  4310. type: 'Object',
  4311. generator: 'Object3D.toJSON'
  4312. };
  4313. } // standard Object3D serialization
  4314. var object = {};
  4315. object.uuid = this.uuid;
  4316. object.type = this.type;
  4317. if (this.name !== '') object.name = this.name;
  4318. if (this.castShadow === true) object.castShadow = true;
  4319. if (this.receiveShadow === true) object.receiveShadow = true;
  4320. if (this.visible === false) object.visible = false;
  4321. if (this.frustumCulled === false) object.frustumCulled = false;
  4322. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4323. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4324. object.layers = this.layers.mask;
  4325. object.matrix = this.matrix.toArray();
  4326. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4327. if (this.isInstancedMesh) {
  4328. object.type = 'InstancedMesh';
  4329. object.count = this.count;
  4330. object.instanceMatrix = this.instanceMatrix.toJSON();
  4331. } //
  4332. function serialize(library, element) {
  4333. if (library[element.uuid] === undefined) {
  4334. library[element.uuid] = element.toJSON(meta);
  4335. }
  4336. return element.uuid;
  4337. }
  4338. if (this.isMesh || this.isLine || this.isPoints) {
  4339. object.geometry = serialize(meta.geometries, this.geometry);
  4340. var parameters = this.geometry.parameters;
  4341. if (parameters !== undefined && parameters.shapes !== undefined) {
  4342. var shapes = parameters.shapes;
  4343. if (Array.isArray(shapes)) {
  4344. for (var i = 0, l = shapes.length; i < l; i++) {
  4345. var shape = shapes[i];
  4346. serialize(meta.shapes, shape);
  4347. }
  4348. } else {
  4349. serialize(meta.shapes, shapes);
  4350. }
  4351. }
  4352. }
  4353. if (this.material !== undefined) {
  4354. if (Array.isArray(this.material)) {
  4355. var uuids = [];
  4356. for (var i = 0, l = this.material.length; i < l; i++) {
  4357. uuids.push(serialize(meta.materials, this.material[i]));
  4358. }
  4359. object.material = uuids;
  4360. } else {
  4361. object.material = serialize(meta.materials, this.material);
  4362. }
  4363. } //
  4364. if (this.children.length > 0) {
  4365. object.children = [];
  4366. for (var i = 0; i < this.children.length; i++) {
  4367. object.children.push(this.children[i].toJSON(meta).object);
  4368. }
  4369. }
  4370. if (isRootObject) {
  4371. var geometries = extractFromCache(meta.geometries);
  4372. var materials = extractFromCache(meta.materials);
  4373. var textures = extractFromCache(meta.textures);
  4374. var images = extractFromCache(meta.images);
  4375. var shapes = extractFromCache(meta.shapes);
  4376. if (geometries.length > 0) output.geometries = geometries;
  4377. if (materials.length > 0) output.materials = materials;
  4378. if (textures.length > 0) output.textures = textures;
  4379. if (images.length > 0) output.images = images;
  4380. if (shapes.length > 0) output.shapes = shapes;
  4381. }
  4382. output.object = object;
  4383. return output; // extract data from the cache hash
  4384. // remove metadata on each item
  4385. // and return as array
  4386. function extractFromCache(cache) {
  4387. var values = [];
  4388. for (var key in cache) {
  4389. var data = cache[key];
  4390. delete data.metadata;
  4391. values.push(data);
  4392. }
  4393. return values;
  4394. }
  4395. },
  4396. clone: function (recursive) {
  4397. return new this.constructor().copy(this, recursive);
  4398. },
  4399. copy: function (source, recursive) {
  4400. if (recursive === undefined) recursive = true;
  4401. this.name = source.name;
  4402. this.up.copy(source.up);
  4403. this.position.copy(source.position);
  4404. this.quaternion.copy(source.quaternion);
  4405. this.scale.copy(source.scale);
  4406. this.matrix.copy(source.matrix);
  4407. this.matrixWorld.copy(source.matrixWorld);
  4408. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4409. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4410. this.layers.mask = source.layers.mask;
  4411. this.visible = source.visible;
  4412. this.castShadow = source.castShadow;
  4413. this.receiveShadow = source.receiveShadow;
  4414. this.frustumCulled = source.frustumCulled;
  4415. this.renderOrder = source.renderOrder;
  4416. this.userData = JSON.parse(JSON.stringify(source.userData));
  4417. if (recursive === true) {
  4418. for (var i = 0; i < source.children.length; i++) {
  4419. var child = source.children[i];
  4420. this.add(child.clone());
  4421. }
  4422. }
  4423. return this;
  4424. }
  4425. });
  4426. /**
  4427. * @author mrdoob / http://mrdoob.com/
  4428. */
  4429. function Scene() {
  4430. Object3D.call(this);
  4431. this.type = 'Scene';
  4432. this.background = null;
  4433. this.environment = null;
  4434. this.fog = null;
  4435. this.overrideMaterial = null;
  4436. this.autoUpdate = true; // checked by the renderer
  4437. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  4438. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  4439. detail: this
  4440. })); // eslint-disable-line no-undef
  4441. }
  4442. }
  4443. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  4444. constructor: Scene,
  4445. isScene: true,
  4446. copy: function (source, recursive) {
  4447. Object3D.prototype.copy.call(this, source, recursive);
  4448. if (source.background !== null) this.background = source.background.clone();
  4449. if (source.environment !== null) this.environment = source.environment.clone();
  4450. if (source.fog !== null) this.fog = source.fog.clone();
  4451. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  4452. this.autoUpdate = source.autoUpdate;
  4453. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4454. return this;
  4455. },
  4456. toJSON: function (meta) {
  4457. var data = Object3D.prototype.toJSON.call(this, meta);
  4458. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  4459. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  4460. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  4461. return data;
  4462. },
  4463. dispose: function () {
  4464. this.dispatchEvent({
  4465. type: 'dispose'
  4466. });
  4467. }
  4468. });
  4469. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  4470. var _vector$1 = new Vector3();
  4471. var _box = new Box3(); // triangle centered vertices
  4472. var _v0 = new Vector3();
  4473. var _v1$2 = new Vector3();
  4474. var _v2 = new Vector3(); // triangle edge vectors
  4475. var _f0 = new Vector3();
  4476. var _f1 = new Vector3();
  4477. var _f2 = new Vector3();
  4478. var _center = new Vector3();
  4479. var _extents = new Vector3();
  4480. var _triangleNormal = new Vector3();
  4481. var _testAxis = new Vector3();
  4482. /**
  4483. * @author bhouston / http://clara.io
  4484. * @author WestLangley / http://github.com/WestLangley
  4485. */
  4486. function Box3(min, max) {
  4487. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  4488. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  4489. }
  4490. Object.assign(Box3.prototype, {
  4491. isBox3: true,
  4492. set: function (min, max) {
  4493. this.min.copy(min);
  4494. this.max.copy(max);
  4495. return this;
  4496. },
  4497. setFromArray: function (array) {
  4498. var minX = +Infinity;
  4499. var minY = +Infinity;
  4500. var minZ = +Infinity;
  4501. var maxX = -Infinity;
  4502. var maxY = -Infinity;
  4503. var maxZ = -Infinity;
  4504. for (var i = 0, l = array.length; i < l; i += 3) {
  4505. var x = array[i];
  4506. var y = array[i + 1];
  4507. var z = array[i + 2];
  4508. if (x < minX) minX = x;
  4509. if (y < minY) minY = y;
  4510. if (z < minZ) minZ = z;
  4511. if (x > maxX) maxX = x;
  4512. if (y > maxY) maxY = y;
  4513. if (z > maxZ) maxZ = z;
  4514. }
  4515. this.min.set(minX, minY, minZ);
  4516. this.max.set(maxX, maxY, maxZ);
  4517. return this;
  4518. },
  4519. setFromBufferAttribute: function (attribute) {
  4520. var minX = +Infinity;
  4521. var minY = +Infinity;
  4522. var minZ = +Infinity;
  4523. var maxX = -Infinity;
  4524. var maxY = -Infinity;
  4525. var maxZ = -Infinity;
  4526. for (var i = 0, l = attribute.count; i < l; i++) {
  4527. var x = attribute.getX(i);
  4528. var y = attribute.getY(i);
  4529. var z = attribute.getZ(i);
  4530. if (x < minX) minX = x;
  4531. if (y < minY) minY = y;
  4532. if (z < minZ) minZ = z;
  4533. if (x > maxX) maxX = x;
  4534. if (y > maxY) maxY = y;
  4535. if (z > maxZ) maxZ = z;
  4536. }
  4537. this.min.set(minX, minY, minZ);
  4538. this.max.set(maxX, maxY, maxZ);
  4539. return this;
  4540. },
  4541. setFromPoints: function (points) {
  4542. this.makeEmpty();
  4543. for (var i = 0, il = points.length; i < il; i++) {
  4544. this.expandByPoint(points[i]);
  4545. }
  4546. return this;
  4547. },
  4548. setFromCenterAndSize: function (center, size) {
  4549. var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  4550. this.min.copy(center).sub(halfSize);
  4551. this.max.copy(center).add(halfSize);
  4552. return this;
  4553. },
  4554. setFromObject: function (object) {
  4555. this.makeEmpty();
  4556. return this.expandByObject(object);
  4557. },
  4558. clone: function () {
  4559. return new this.constructor().copy(this);
  4560. },
  4561. copy: function (box) {
  4562. this.min.copy(box.min);
  4563. this.max.copy(box.max);
  4564. return this;
  4565. },
  4566. makeEmpty: function () {
  4567. this.min.x = this.min.y = this.min.z = +Infinity;
  4568. this.max.x = this.max.y = this.max.z = -Infinity;
  4569. return this;
  4570. },
  4571. isEmpty: function () {
  4572. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4573. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  4574. },
  4575. getCenter: function (target) {
  4576. if (target === undefined) {
  4577. console.warn('THREE.Box3: .getCenter() target is now required');
  4578. target = new Vector3();
  4579. }
  4580. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  4581. },
  4582. getSize: function (target) {
  4583. if (target === undefined) {
  4584. console.warn('THREE.Box3: .getSize() target is now required');
  4585. target = new Vector3();
  4586. }
  4587. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  4588. },
  4589. expandByPoint: function (point) {
  4590. this.min.min(point);
  4591. this.max.max(point);
  4592. return this;
  4593. },
  4594. expandByVector: function (vector) {
  4595. this.min.sub(vector);
  4596. this.max.add(vector);
  4597. return this;
  4598. },
  4599. expandByScalar: function (scalar) {
  4600. this.min.addScalar(-scalar);
  4601. this.max.addScalar(scalar);
  4602. return this;
  4603. },
  4604. expandByObject: function (object) {
  4605. // Computes the world-axis-aligned bounding box of an object (including its children),
  4606. // accounting for both the object's, and children's, world transforms
  4607. object.updateWorldMatrix(false, false);
  4608. var geometry = object.geometry;
  4609. if (geometry !== undefined) {
  4610. if (geometry.boundingBox === null) {
  4611. geometry.computeBoundingBox();
  4612. }
  4613. _box.copy(geometry.boundingBox);
  4614. _box.applyMatrix4(object.matrixWorld);
  4615. this.union(_box);
  4616. }
  4617. var children = object.children;
  4618. for (var i = 0, l = children.length; i < l; i++) {
  4619. this.expandByObject(children[i]);
  4620. }
  4621. return this;
  4622. },
  4623. containsPoint: function (point) {
  4624. 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;
  4625. },
  4626. containsBox: function (box) {
  4627. 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;
  4628. },
  4629. getParameter: function (point, target) {
  4630. // This can potentially have a divide by zero if the box
  4631. // has a size dimension of 0.
  4632. if (target === undefined) {
  4633. console.warn('THREE.Box3: .getParameter() target is now required');
  4634. target = new Vector3();
  4635. }
  4636. 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));
  4637. },
  4638. intersectsBox: function (box) {
  4639. // using 6 splitting planes to rule out intersections.
  4640. 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;
  4641. },
  4642. intersectsSphere: function (sphere) {
  4643. // Find the point on the AABB closest to the sphere center.
  4644. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  4645. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  4646. },
  4647. intersectsPlane: function (plane) {
  4648. // We compute the minimum and maximum dot product values. If those values
  4649. // are on the same side (back or front) of the plane, then there is no intersection.
  4650. var min, max;
  4651. if (plane.normal.x > 0) {
  4652. min = plane.normal.x * this.min.x;
  4653. max = plane.normal.x * this.max.x;
  4654. } else {
  4655. min = plane.normal.x * this.max.x;
  4656. max = plane.normal.x * this.min.x;
  4657. }
  4658. if (plane.normal.y > 0) {
  4659. min += plane.normal.y * this.min.y;
  4660. max += plane.normal.y * this.max.y;
  4661. } else {
  4662. min += plane.normal.y * this.max.y;
  4663. max += plane.normal.y * this.min.y;
  4664. }
  4665. if (plane.normal.z > 0) {
  4666. min += plane.normal.z * this.min.z;
  4667. max += plane.normal.z * this.max.z;
  4668. } else {
  4669. min += plane.normal.z * this.max.z;
  4670. max += plane.normal.z * this.min.z;
  4671. }
  4672. return min <= -plane.constant && max >= -plane.constant;
  4673. },
  4674. intersectsTriangle: function (triangle) {
  4675. if (this.isEmpty()) {
  4676. return false;
  4677. } // compute box center and extents
  4678. this.getCenter(_center);
  4679. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  4680. _v0.subVectors(triangle.a, _center);
  4681. _v1$2.subVectors(triangle.b, _center);
  4682. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  4683. _f0.subVectors(_v1$2, _v0);
  4684. _f1.subVectors(_v2, _v1$2);
  4685. _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
  4686. // 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
  4687. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  4688. var 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];
  4689. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4690. return false;
  4691. } // test 3 face normals from the aabb
  4692. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  4693. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4694. return false;
  4695. } // finally testing the face normal of the triangle
  4696. // use already existing triangle edge vectors here
  4697. _triangleNormal.crossVectors(_f0, _f1);
  4698. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  4699. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  4700. },
  4701. clampPoint: function (point, target) {
  4702. if (target === undefined) {
  4703. console.warn('THREE.Box3: .clampPoint() target is now required');
  4704. target = new Vector3();
  4705. }
  4706. return target.copy(point).clamp(this.min, this.max);
  4707. },
  4708. distanceToPoint: function (point) {
  4709. var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  4710. return clampedPoint.sub(point).length();
  4711. },
  4712. getBoundingSphere: function (target) {
  4713. if (target === undefined) {
  4714. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  4715. }
  4716. this.getCenter(target.center);
  4717. target.radius = this.getSize(_vector$1).length() * 0.5;
  4718. return target;
  4719. },
  4720. intersect: function (box) {
  4721. this.min.max(box.min);
  4722. 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.
  4723. if (this.isEmpty()) this.makeEmpty();
  4724. return this;
  4725. },
  4726. union: function (box) {
  4727. this.min.min(box.min);
  4728. this.max.max(box.max);
  4729. return this;
  4730. },
  4731. applyMatrix4: function (matrix) {
  4732. // transform of empty box is an empty box.
  4733. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4734. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  4735. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  4736. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  4737. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  4738. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  4739. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  4740. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  4741. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  4742. this.setFromPoints(_points);
  4743. return this;
  4744. },
  4745. translate: function (offset) {
  4746. this.min.add(offset);
  4747. this.max.add(offset);
  4748. return this;
  4749. },
  4750. equals: function (box) {
  4751. return box.min.equals(this.min) && box.max.equals(this.max);
  4752. }
  4753. });
  4754. function satForAxes(axes, v0, v1, v2, extents) {
  4755. var i, j;
  4756. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  4757. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  4758. var 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
  4759. var p0 = v0.dot(_testAxis);
  4760. var p1 = v1.dot(_testAxis);
  4761. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  4762. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  4763. // points of the projected triangle are outside the projected half-length of the aabb
  4764. // the axis is seperating and we can exit
  4765. return false;
  4766. }
  4767. }
  4768. return true;
  4769. }
  4770. var _box$1 = new Box3();
  4771. /**
  4772. * @author bhouston / http://clara.io
  4773. * @author mrdoob / http://mrdoob.com/
  4774. */
  4775. function Sphere(center, radius) {
  4776. this.center = center !== undefined ? center : new Vector3();
  4777. this.radius = radius !== undefined ? radius : 0;
  4778. }
  4779. Object.assign(Sphere.prototype, {
  4780. set: function (center, radius) {
  4781. this.center.copy(center);
  4782. this.radius = radius;
  4783. return this;
  4784. },
  4785. setFromPoints: function (points, optionalCenter) {
  4786. var center = this.center;
  4787. if (optionalCenter !== undefined) {
  4788. center.copy(optionalCenter);
  4789. } else {
  4790. _box$1.setFromPoints(points).getCenter(center);
  4791. }
  4792. var maxRadiusSq = 0;
  4793. for (var i = 0, il = points.length; i < il; i++) {
  4794. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  4795. }
  4796. this.radius = Math.sqrt(maxRadiusSq);
  4797. return this;
  4798. },
  4799. clone: function () {
  4800. return new this.constructor().copy(this);
  4801. },
  4802. copy: function (sphere) {
  4803. this.center.copy(sphere.center);
  4804. this.radius = sphere.radius;
  4805. return this;
  4806. },
  4807. empty: function () {
  4808. return this.radius <= 0;
  4809. },
  4810. containsPoint: function (point) {
  4811. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  4812. },
  4813. distanceToPoint: function (point) {
  4814. return point.distanceTo(this.center) - this.radius;
  4815. },
  4816. intersectsSphere: function (sphere) {
  4817. var radiusSum = this.radius + sphere.radius;
  4818. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  4819. },
  4820. intersectsBox: function (box) {
  4821. return box.intersectsSphere(this);
  4822. },
  4823. intersectsPlane: function (plane) {
  4824. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  4825. },
  4826. clampPoint: function (point, target) {
  4827. var deltaLengthSq = this.center.distanceToSquared(point);
  4828. if (target === undefined) {
  4829. console.warn('THREE.Sphere: .clampPoint() target is now required');
  4830. target = new Vector3();
  4831. }
  4832. target.copy(point);
  4833. if (deltaLengthSq > this.radius * this.radius) {
  4834. target.sub(this.center).normalize();
  4835. target.multiplyScalar(this.radius).add(this.center);
  4836. }
  4837. return target;
  4838. },
  4839. getBoundingBox: function (target) {
  4840. if (target === undefined) {
  4841. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  4842. target = new Box3();
  4843. }
  4844. target.set(this.center, this.center);
  4845. target.expandByScalar(this.radius);
  4846. return target;
  4847. },
  4848. applyMatrix4: function (matrix) {
  4849. this.center.applyMatrix4(matrix);
  4850. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4851. return this;
  4852. },
  4853. translate: function (offset) {
  4854. this.center.add(offset);
  4855. return this;
  4856. },
  4857. equals: function (sphere) {
  4858. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  4859. }
  4860. });
  4861. var _vector$2 = new Vector3();
  4862. var _segCenter = new Vector3();
  4863. var _segDir = new Vector3();
  4864. var _diff = new Vector3();
  4865. var _edge1 = new Vector3();
  4866. var _edge2 = new Vector3();
  4867. var _normal = new Vector3();
  4868. /**
  4869. * @author bhouston / http://clara.io
  4870. */
  4871. function Ray(origin, direction) {
  4872. this.origin = origin !== undefined ? origin : new Vector3();
  4873. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  4874. }
  4875. Object.assign(Ray.prototype, {
  4876. set: function (origin, direction) {
  4877. this.origin.copy(origin);
  4878. this.direction.copy(direction);
  4879. return this;
  4880. },
  4881. clone: function () {
  4882. return new this.constructor().copy(this);
  4883. },
  4884. copy: function (ray) {
  4885. this.origin.copy(ray.origin);
  4886. this.direction.copy(ray.direction);
  4887. return this;
  4888. },
  4889. at: function (t, target) {
  4890. if (target === undefined) {
  4891. console.warn('THREE.Ray: .at() target is now required');
  4892. target = new Vector3();
  4893. }
  4894. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  4895. },
  4896. lookAt: function (v) {
  4897. this.direction.copy(v).sub(this.origin).normalize();
  4898. return this;
  4899. },
  4900. recast: function (t) {
  4901. this.origin.copy(this.at(t, _vector$2));
  4902. return this;
  4903. },
  4904. closestPointToPoint: function (point, target) {
  4905. if (target === undefined) {
  4906. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  4907. target = new Vector3();
  4908. }
  4909. target.subVectors(point, this.origin);
  4910. var directionDistance = target.dot(this.direction);
  4911. if (directionDistance < 0) {
  4912. return target.copy(this.origin);
  4913. }
  4914. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4915. },
  4916. distanceToPoint: function (point) {
  4917. return Math.sqrt(this.distanceSqToPoint(point));
  4918. },
  4919. distanceSqToPoint: function (point) {
  4920. var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  4921. if (directionDistance < 0) {
  4922. return this.origin.distanceToSquared(point);
  4923. }
  4924. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4925. return _vector$2.distanceToSquared(point);
  4926. },
  4927. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  4928. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4929. // It returns the min distance between the ray and the segment
  4930. // defined by v0 and v1
  4931. // It can also set two optional targets :
  4932. // - The closest point on the ray
  4933. // - The closest point on the segment
  4934. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  4935. _segDir.copy(v1).sub(v0).normalize();
  4936. _diff.copy(this.origin).sub(_segCenter);
  4937. var segExtent = v0.distanceTo(v1) * 0.5;
  4938. var a01 = -this.direction.dot(_segDir);
  4939. var b0 = _diff.dot(this.direction);
  4940. var b1 = -_diff.dot(_segDir);
  4941. var c = _diff.lengthSq();
  4942. var det = Math.abs(1 - a01 * a01);
  4943. var s0, s1, sqrDist, extDet;
  4944. if (det > 0) {
  4945. // The ray and segment are not parallel.
  4946. s0 = a01 * b1 - b0;
  4947. s1 = a01 * b0 - b1;
  4948. extDet = segExtent * det;
  4949. if (s0 >= 0) {
  4950. if (s1 >= -extDet) {
  4951. if (s1 <= extDet) {
  4952. // region 0
  4953. // Minimum at interior points of ray and segment.
  4954. var invDet = 1 / det;
  4955. s0 *= invDet;
  4956. s1 *= invDet;
  4957. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  4958. } else {
  4959. // region 1
  4960. s1 = segExtent;
  4961. s0 = Math.max(0, -(a01 * s1 + b0));
  4962. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4963. }
  4964. } else {
  4965. // region 5
  4966. s1 = -segExtent;
  4967. s0 = Math.max(0, -(a01 * s1 + b0));
  4968. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4969. }
  4970. } else {
  4971. if (s1 <= -extDet) {
  4972. // region 4
  4973. s0 = Math.max(0, -(-a01 * segExtent + b0));
  4974. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4975. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4976. } else if (s1 <= extDet) {
  4977. // region 3
  4978. s0 = 0;
  4979. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  4980. sqrDist = s1 * (s1 + 2 * b1) + c;
  4981. } else {
  4982. // region 2
  4983. s0 = Math.max(0, -(a01 * segExtent + b0));
  4984. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4985. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4986. }
  4987. }
  4988. } else {
  4989. // Ray and segment are parallel.
  4990. s1 = a01 > 0 ? -segExtent : segExtent;
  4991. s0 = Math.max(0, -(a01 * s1 + b0));
  4992. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4993. }
  4994. if (optionalPointOnRay) {
  4995. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  4996. }
  4997. if (optionalPointOnSegment) {
  4998. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  4999. }
  5000. return sqrDist;
  5001. },
  5002. intersectSphere: function (sphere, target) {
  5003. _vector$2.subVectors(sphere.center, this.origin);
  5004. var tca = _vector$2.dot(this.direction);
  5005. var d2 = _vector$2.dot(_vector$2) - tca * tca;
  5006. var radius2 = sphere.radius * sphere.radius;
  5007. if (d2 > radius2) return null;
  5008. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  5009. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  5010. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  5011. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  5012. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5013. // in order to always return an intersect point that is in front of the ray.
  5014. 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
  5015. return this.at(t0, target);
  5016. },
  5017. intersectsSphere: function (sphere) {
  5018. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  5019. },
  5020. distanceToPlane: function (plane) {
  5021. var denominator = plane.normal.dot(this.direction);
  5022. if (denominator === 0) {
  5023. // line is coplanar, return origin
  5024. if (plane.distanceToPoint(this.origin) === 0) {
  5025. return 0;
  5026. } // Null is preferable to undefined since undefined means.... it is undefined
  5027. return null;
  5028. }
  5029. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  5030. return t >= 0 ? t : null;
  5031. },
  5032. intersectPlane: function (plane, target) {
  5033. var t = this.distanceToPlane(plane);
  5034. if (t === null) {
  5035. return null;
  5036. }
  5037. return this.at(t, target);
  5038. },
  5039. intersectsPlane: function (plane) {
  5040. // check if the ray lies on the plane first
  5041. var distToPoint = plane.distanceToPoint(this.origin);
  5042. if (distToPoint === 0) {
  5043. return true;
  5044. }
  5045. var denominator = plane.normal.dot(this.direction);
  5046. if (denominator * distToPoint < 0) {
  5047. return true;
  5048. } // ray origin is behind the plane (and is pointing behind it)
  5049. return false;
  5050. },
  5051. intersectBox: function (box, target) {
  5052. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  5053. var invdirx = 1 / this.direction.x,
  5054. invdiry = 1 / this.direction.y,
  5055. invdirz = 1 / this.direction.z;
  5056. var origin = this.origin;
  5057. if (invdirx >= 0) {
  5058. tmin = (box.min.x - origin.x) * invdirx;
  5059. tmax = (box.max.x - origin.x) * invdirx;
  5060. } else {
  5061. tmin = (box.max.x - origin.x) * invdirx;
  5062. tmax = (box.min.x - origin.x) * invdirx;
  5063. }
  5064. if (invdiry >= 0) {
  5065. tymin = (box.min.y - origin.y) * invdiry;
  5066. tymax = (box.max.y - origin.y) * invdiry;
  5067. } else {
  5068. tymin = (box.max.y - origin.y) * invdiry;
  5069. tymax = (box.min.y - origin.y) * invdiry;
  5070. }
  5071. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  5072. // (result of 0 * Infinity). x !== x returns true if x is NaN
  5073. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  5074. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  5075. if (invdirz >= 0) {
  5076. tzmin = (box.min.z - origin.z) * invdirz;
  5077. tzmax = (box.max.z - origin.z) * invdirz;
  5078. } else {
  5079. tzmin = (box.max.z - origin.z) * invdirz;
  5080. tzmax = (box.min.z - origin.z) * invdirz;
  5081. }
  5082. if (tmin > tzmax || tzmin > tmax) return null;
  5083. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  5084. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  5085. if (tmax < 0) return null;
  5086. return this.at(tmin >= 0 ? tmin : tmax, target);
  5087. },
  5088. intersectsBox: function (box) {
  5089. return this.intersectBox(box, _vector$2) !== null;
  5090. },
  5091. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  5092. // Compute the offset origin, edges, and normal.
  5093. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  5094. _edge1.subVectors(b, a);
  5095. _edge2.subVectors(c, a);
  5096. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  5097. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  5098. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  5099. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  5100. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  5101. var DdN = this.direction.dot(_normal);
  5102. var sign;
  5103. if (DdN > 0) {
  5104. if (backfaceCulling) return null;
  5105. sign = 1;
  5106. } else if (DdN < 0) {
  5107. sign = -1;
  5108. DdN = -DdN;
  5109. } else {
  5110. return null;
  5111. }
  5112. _diff.subVectors(this.origin, a);
  5113. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  5114. if (DdQxE2 < 0) {
  5115. return null;
  5116. }
  5117. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  5118. if (DdE1xQ < 0) {
  5119. return null;
  5120. } // b1+b2 > 1, no intersection
  5121. if (DdQxE2 + DdE1xQ > DdN) {
  5122. return null;
  5123. } // Line intersects triangle, check if ray does.
  5124. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  5125. if (QdN < 0) {
  5126. return null;
  5127. } // Ray intersects triangle.
  5128. return this.at(QdN / DdN, target);
  5129. },
  5130. applyMatrix4: function (matrix4) {
  5131. this.origin.applyMatrix4(matrix4);
  5132. this.direction.transformDirection(matrix4);
  5133. return this;
  5134. },
  5135. equals: function (ray) {
  5136. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  5137. }
  5138. });
  5139. /**
  5140. * @author bhouston / http://clara.io
  5141. */
  5142. var _vector1 = new Vector3();
  5143. var _vector2 = new Vector3();
  5144. var _normalMatrix = new Matrix3();
  5145. function Plane(normal, constant) {
  5146. // normal is assumed to be normalized
  5147. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  5148. this.constant = constant !== undefined ? constant : 0;
  5149. }
  5150. Object.assign(Plane.prototype, {
  5151. isPlane: true,
  5152. set: function (normal, constant) {
  5153. this.normal.copy(normal);
  5154. this.constant = constant;
  5155. return this;
  5156. },
  5157. setComponents: function (x, y, z, w) {
  5158. this.normal.set(x, y, z);
  5159. this.constant = w;
  5160. return this;
  5161. },
  5162. setFromNormalAndCoplanarPoint: function (normal, point) {
  5163. this.normal.copy(normal);
  5164. this.constant = -point.dot(this.normal);
  5165. return this;
  5166. },
  5167. setFromCoplanarPoints: function (a, b, c) {
  5168. var 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)?
  5169. this.setFromNormalAndCoplanarPoint(normal, a);
  5170. return this;
  5171. },
  5172. clone: function () {
  5173. return new this.constructor().copy(this);
  5174. },
  5175. copy: function (plane) {
  5176. this.normal.copy(plane.normal);
  5177. this.constant = plane.constant;
  5178. return this;
  5179. },
  5180. normalize: function () {
  5181. // Note: will lead to a divide by zero if the plane is invalid.
  5182. var inverseNormalLength = 1.0 / this.normal.length();
  5183. this.normal.multiplyScalar(inverseNormalLength);
  5184. this.constant *= inverseNormalLength;
  5185. return this;
  5186. },
  5187. negate: function () {
  5188. this.constant *= -1;
  5189. this.normal.negate();
  5190. return this;
  5191. },
  5192. distanceToPoint: function (point) {
  5193. return this.normal.dot(point) + this.constant;
  5194. },
  5195. distanceToSphere: function (sphere) {
  5196. return this.distanceToPoint(sphere.center) - sphere.radius;
  5197. },
  5198. projectPoint: function (point, target) {
  5199. if (target === undefined) {
  5200. console.warn('THREE.Plane: .projectPoint() target is now required');
  5201. target = new Vector3();
  5202. }
  5203. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  5204. },
  5205. intersectLine: function (line, target) {
  5206. if (target === undefined) {
  5207. console.warn('THREE.Plane: .intersectLine() target is now required');
  5208. target = new Vector3();
  5209. }
  5210. var direction = line.delta(_vector1);
  5211. var denominator = this.normal.dot(direction);
  5212. if (denominator === 0) {
  5213. // line is coplanar, return origin
  5214. if (this.distanceToPoint(line.start) === 0) {
  5215. return target.copy(line.start);
  5216. } // Unsure if this is the correct method to handle this case.
  5217. return undefined;
  5218. }
  5219. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  5220. if (t < 0 || t > 1) {
  5221. return undefined;
  5222. }
  5223. return target.copy(direction).multiplyScalar(t).add(line.start);
  5224. },
  5225. intersectsLine: function (line) {
  5226. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5227. var startSign = this.distanceToPoint(line.start);
  5228. var endSign = this.distanceToPoint(line.end);
  5229. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  5230. },
  5231. intersectsBox: function (box) {
  5232. return box.intersectsPlane(this);
  5233. },
  5234. intersectsSphere: function (sphere) {
  5235. return sphere.intersectsPlane(this);
  5236. },
  5237. coplanarPoint: function (target) {
  5238. if (target === undefined) {
  5239. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  5240. target = new Vector3();
  5241. }
  5242. return target.copy(this.normal).multiplyScalar(-this.constant);
  5243. },
  5244. applyMatrix4: function (matrix, optionalNormalMatrix) {
  5245. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  5246. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  5247. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  5248. this.constant = -referencePoint.dot(normal);
  5249. return this;
  5250. },
  5251. translate: function (offset) {
  5252. this.constant -= offset.dot(this.normal);
  5253. return this;
  5254. },
  5255. equals: function (plane) {
  5256. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  5257. }
  5258. });
  5259. /**
  5260. * @author bhouston / http://clara.io
  5261. * @author mrdoob / http://mrdoob.com/
  5262. */
  5263. var _v0$1 = new Vector3();
  5264. var _v1$3 = new Vector3();
  5265. var _v2$1 = new Vector3();
  5266. var _v3 = new Vector3();
  5267. var _vab = new Vector3();
  5268. var _vac = new Vector3();
  5269. var _vbc = new Vector3();
  5270. var _vap = new Vector3();
  5271. var _vbp = new Vector3();
  5272. var _vcp = new Vector3();
  5273. function Triangle(a, b, c) {
  5274. this.a = a !== undefined ? a : new Vector3();
  5275. this.b = b !== undefined ? b : new Vector3();
  5276. this.c = c !== undefined ? c : new Vector3();
  5277. }
  5278. Object.assign(Triangle, {
  5279. getNormal: function (a, b, c, target) {
  5280. if (target === undefined) {
  5281. console.warn('THREE.Triangle: .getNormal() target is now required');
  5282. target = new Vector3();
  5283. }
  5284. target.subVectors(c, b);
  5285. _v0$1.subVectors(a, b);
  5286. target.cross(_v0$1);
  5287. var targetLengthSq = target.lengthSq();
  5288. if (targetLengthSq > 0) {
  5289. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5290. }
  5291. return target.set(0, 0, 0);
  5292. },
  5293. // static/instance method to calculate barycentric coordinates
  5294. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5295. getBarycoord: function (point, a, b, c, target) {
  5296. _v0$1.subVectors(c, a);
  5297. _v1$3.subVectors(b, a);
  5298. _v2$1.subVectors(point, a);
  5299. var dot00 = _v0$1.dot(_v0$1);
  5300. var dot01 = _v0$1.dot(_v1$3);
  5301. var dot02 = _v0$1.dot(_v2$1);
  5302. var dot11 = _v1$3.dot(_v1$3);
  5303. var dot12 = _v1$3.dot(_v2$1);
  5304. var denom = dot00 * dot11 - dot01 * dot01;
  5305. if (target === undefined) {
  5306. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5307. target = new Vector3();
  5308. } // collinear or singular triangle
  5309. if (denom === 0) {
  5310. // arbitrary location outside of triangle?
  5311. // not sure if this is the best idea, maybe should be returning undefined
  5312. return target.set(-2, -1, -1);
  5313. }
  5314. var invDenom = 1 / denom;
  5315. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5316. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5317. return target.set(1 - u - v, v, u);
  5318. },
  5319. containsPoint: function (point, a, b, c) {
  5320. Triangle.getBarycoord(point, a, b, c, _v3);
  5321. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5322. },
  5323. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  5324. this.getBarycoord(point, p1, p2, p3, _v3);
  5325. target.set(0, 0);
  5326. target.addScaledVector(uv1, _v3.x);
  5327. target.addScaledVector(uv2, _v3.y);
  5328. target.addScaledVector(uv3, _v3.z);
  5329. return target;
  5330. },
  5331. isFrontFacing: function (a, b, c, direction) {
  5332. _v0$1.subVectors(c, b);
  5333. _v1$3.subVectors(a, b); // strictly front facing
  5334. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5335. }
  5336. });
  5337. Object.assign(Triangle.prototype, {
  5338. set: function (a, b, c) {
  5339. this.a.copy(a);
  5340. this.b.copy(b);
  5341. this.c.copy(c);
  5342. return this;
  5343. },
  5344. setFromPointsAndIndices: function (points, i0, i1, i2) {
  5345. this.a.copy(points[i0]);
  5346. this.b.copy(points[i1]);
  5347. this.c.copy(points[i2]);
  5348. return this;
  5349. },
  5350. clone: function () {
  5351. return new this.constructor().copy(this);
  5352. },
  5353. copy: function (triangle) {
  5354. this.a.copy(triangle.a);
  5355. this.b.copy(triangle.b);
  5356. this.c.copy(triangle.c);
  5357. return this;
  5358. },
  5359. getArea: function () {
  5360. _v0$1.subVectors(this.c, this.b);
  5361. _v1$3.subVectors(this.a, this.b);
  5362. return _v0$1.cross(_v1$3).length() * 0.5;
  5363. },
  5364. getMidpoint: function (target) {
  5365. if (target === undefined) {
  5366. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5367. target = new Vector3();
  5368. }
  5369. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5370. },
  5371. getNormal: function (target) {
  5372. return Triangle.getNormal(this.a, this.b, this.c, target);
  5373. },
  5374. getPlane: function (target) {
  5375. if (target === undefined) {
  5376. console.warn('THREE.Triangle: .getPlane() target is now required');
  5377. target = new Plane();
  5378. }
  5379. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5380. },
  5381. getBarycoord: function (point, target) {
  5382. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5383. },
  5384. getUV: function (point, uv1, uv2, uv3, target) {
  5385. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5386. },
  5387. containsPoint: function (point) {
  5388. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5389. },
  5390. isFrontFacing: function (direction) {
  5391. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5392. },
  5393. intersectsBox: function (box) {
  5394. return box.intersectsTriangle(this);
  5395. },
  5396. closestPointToPoint: function (p, target) {
  5397. if (target === undefined) {
  5398. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5399. target = new Vector3();
  5400. }
  5401. var a = this.a,
  5402. b = this.b,
  5403. c = this.c;
  5404. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5405. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5406. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5407. // basically, we're distinguishing which of the voronoi regions of the triangle
  5408. // the point lies in with the minimum amount of redundant computation.
  5409. _vab.subVectors(b, a);
  5410. _vac.subVectors(c, a);
  5411. _vap.subVectors(p, a);
  5412. var d1 = _vab.dot(_vap);
  5413. var d2 = _vac.dot(_vap);
  5414. if (d1 <= 0 && d2 <= 0) {
  5415. // vertex region of A; barycentric coords (1, 0, 0)
  5416. return target.copy(a);
  5417. }
  5418. _vbp.subVectors(p, b);
  5419. var d3 = _vab.dot(_vbp);
  5420. var d4 = _vac.dot(_vbp);
  5421. if (d3 >= 0 && d4 <= d3) {
  5422. // vertex region of B; barycentric coords (0, 1, 0)
  5423. return target.copy(b);
  5424. }
  5425. var vc = d1 * d4 - d3 * d2;
  5426. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5427. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5428. return target.copy(a).addScaledVector(_vab, v);
  5429. }
  5430. _vcp.subVectors(p, c);
  5431. var d5 = _vab.dot(_vcp);
  5432. var d6 = _vac.dot(_vcp);
  5433. if (d6 >= 0 && d5 <= d6) {
  5434. // vertex region of C; barycentric coords (0, 0, 1)
  5435. return target.copy(c);
  5436. }
  5437. var vb = d5 * d2 - d1 * d6;
  5438. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5439. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5440. return target.copy(a).addScaledVector(_vac, w);
  5441. }
  5442. var va = d3 * d6 - d5 * d4;
  5443. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5444. _vbc.subVectors(c, b);
  5445. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5446. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5447. } // face region
  5448. var denom = 1 / (va + vb + vc); // u = va * denom
  5449. v = vb * denom;
  5450. w = vc * denom;
  5451. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5452. },
  5453. equals: function (triangle) {
  5454. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5455. }
  5456. });
  5457. /**
  5458. * @author mrdoob / http://mrdoob.com/
  5459. */
  5460. var _colorKeywords = {
  5461. 'aliceblue': 0xF0F8FF,
  5462. 'antiquewhite': 0xFAEBD7,
  5463. 'aqua': 0x00FFFF,
  5464. 'aquamarine': 0x7FFFD4,
  5465. 'azure': 0xF0FFFF,
  5466. 'beige': 0xF5F5DC,
  5467. 'bisque': 0xFFE4C4,
  5468. 'black': 0x000000,
  5469. 'blanchedalmond': 0xFFEBCD,
  5470. 'blue': 0x0000FF,
  5471. 'blueviolet': 0x8A2BE2,
  5472. 'brown': 0xA52A2A,
  5473. 'burlywood': 0xDEB887,
  5474. 'cadetblue': 0x5F9EA0,
  5475. 'chartreuse': 0x7FFF00,
  5476. 'chocolate': 0xD2691E,
  5477. 'coral': 0xFF7F50,
  5478. 'cornflowerblue': 0x6495ED,
  5479. 'cornsilk': 0xFFF8DC,
  5480. 'crimson': 0xDC143C,
  5481. 'cyan': 0x00FFFF,
  5482. 'darkblue': 0x00008B,
  5483. 'darkcyan': 0x008B8B,
  5484. 'darkgoldenrod': 0xB8860B,
  5485. 'darkgray': 0xA9A9A9,
  5486. 'darkgreen': 0x006400,
  5487. 'darkgrey': 0xA9A9A9,
  5488. 'darkkhaki': 0xBDB76B,
  5489. 'darkmagenta': 0x8B008B,
  5490. 'darkolivegreen': 0x556B2F,
  5491. 'darkorange': 0xFF8C00,
  5492. 'darkorchid': 0x9932CC,
  5493. 'darkred': 0x8B0000,
  5494. 'darksalmon': 0xE9967A,
  5495. 'darkseagreen': 0x8FBC8F,
  5496. 'darkslateblue': 0x483D8B,
  5497. 'darkslategray': 0x2F4F4F,
  5498. 'darkslategrey': 0x2F4F4F,
  5499. 'darkturquoise': 0x00CED1,
  5500. 'darkviolet': 0x9400D3,
  5501. 'deeppink': 0xFF1493,
  5502. 'deepskyblue': 0x00BFFF,
  5503. 'dimgray': 0x696969,
  5504. 'dimgrey': 0x696969,
  5505. 'dodgerblue': 0x1E90FF,
  5506. 'firebrick': 0xB22222,
  5507. 'floralwhite': 0xFFFAF0,
  5508. 'forestgreen': 0x228B22,
  5509. 'fuchsia': 0xFF00FF,
  5510. 'gainsboro': 0xDCDCDC,
  5511. 'ghostwhite': 0xF8F8FF,
  5512. 'gold': 0xFFD700,
  5513. 'goldenrod': 0xDAA520,
  5514. 'gray': 0x808080,
  5515. 'green': 0x008000,
  5516. 'greenyellow': 0xADFF2F,
  5517. 'grey': 0x808080,
  5518. 'honeydew': 0xF0FFF0,
  5519. 'hotpink': 0xFF69B4,
  5520. 'indianred': 0xCD5C5C,
  5521. 'indigo': 0x4B0082,
  5522. 'ivory': 0xFFFFF0,
  5523. 'khaki': 0xF0E68C,
  5524. 'lavender': 0xE6E6FA,
  5525. 'lavenderblush': 0xFFF0F5,
  5526. 'lawngreen': 0x7CFC00,
  5527. 'lemonchiffon': 0xFFFACD,
  5528. 'lightblue': 0xADD8E6,
  5529. 'lightcoral': 0xF08080,
  5530. 'lightcyan': 0xE0FFFF,
  5531. 'lightgoldenrodyellow': 0xFAFAD2,
  5532. 'lightgray': 0xD3D3D3,
  5533. 'lightgreen': 0x90EE90,
  5534. 'lightgrey': 0xD3D3D3,
  5535. 'lightpink': 0xFFB6C1,
  5536. 'lightsalmon': 0xFFA07A,
  5537. 'lightseagreen': 0x20B2AA,
  5538. 'lightskyblue': 0x87CEFA,
  5539. 'lightslategray': 0x778899,
  5540. 'lightslategrey': 0x778899,
  5541. 'lightsteelblue': 0xB0C4DE,
  5542. 'lightyellow': 0xFFFFE0,
  5543. 'lime': 0x00FF00,
  5544. 'limegreen': 0x32CD32,
  5545. 'linen': 0xFAF0E6,
  5546. 'magenta': 0xFF00FF,
  5547. 'maroon': 0x800000,
  5548. 'mediumaquamarine': 0x66CDAA,
  5549. 'mediumblue': 0x0000CD,
  5550. 'mediumorchid': 0xBA55D3,
  5551. 'mediumpurple': 0x9370DB,
  5552. 'mediumseagreen': 0x3CB371,
  5553. 'mediumslateblue': 0x7B68EE,
  5554. 'mediumspringgreen': 0x00FA9A,
  5555. 'mediumturquoise': 0x48D1CC,
  5556. 'mediumvioletred': 0xC71585,
  5557. 'midnightblue': 0x191970,
  5558. 'mintcream': 0xF5FFFA,
  5559. 'mistyrose': 0xFFE4E1,
  5560. 'moccasin': 0xFFE4B5,
  5561. 'navajowhite': 0xFFDEAD,
  5562. 'navy': 0x000080,
  5563. 'oldlace': 0xFDF5E6,
  5564. 'olive': 0x808000,
  5565. 'olivedrab': 0x6B8E23,
  5566. 'orange': 0xFFA500,
  5567. 'orangered': 0xFF4500,
  5568. 'orchid': 0xDA70D6,
  5569. 'palegoldenrod': 0xEEE8AA,
  5570. 'palegreen': 0x98FB98,
  5571. 'paleturquoise': 0xAFEEEE,
  5572. 'palevioletred': 0xDB7093,
  5573. 'papayawhip': 0xFFEFD5,
  5574. 'peachpuff': 0xFFDAB9,
  5575. 'peru': 0xCD853F,
  5576. 'pink': 0xFFC0CB,
  5577. 'plum': 0xDDA0DD,
  5578. 'powderblue': 0xB0E0E6,
  5579. 'purple': 0x800080,
  5580. 'rebeccapurple': 0x663399,
  5581. 'red': 0xFF0000,
  5582. 'rosybrown': 0xBC8F8F,
  5583. 'royalblue': 0x4169E1,
  5584. 'saddlebrown': 0x8B4513,
  5585. 'salmon': 0xFA8072,
  5586. 'sandybrown': 0xF4A460,
  5587. 'seagreen': 0x2E8B57,
  5588. 'seashell': 0xFFF5EE,
  5589. 'sienna': 0xA0522D,
  5590. 'silver': 0xC0C0C0,
  5591. 'skyblue': 0x87CEEB,
  5592. 'slateblue': 0x6A5ACD,
  5593. 'slategray': 0x708090,
  5594. 'slategrey': 0x708090,
  5595. 'snow': 0xFFFAFA,
  5596. 'springgreen': 0x00FF7F,
  5597. 'steelblue': 0x4682B4,
  5598. 'tan': 0xD2B48C,
  5599. 'teal': 0x008080,
  5600. 'thistle': 0xD8BFD8,
  5601. 'tomato': 0xFF6347,
  5602. 'turquoise': 0x40E0D0,
  5603. 'violet': 0xEE82EE,
  5604. 'wheat': 0xF5DEB3,
  5605. 'white': 0xFFFFFF,
  5606. 'whitesmoke': 0xF5F5F5,
  5607. 'yellow': 0xFFFF00,
  5608. 'yellowgreen': 0x9ACD32
  5609. };
  5610. var _hslA = {
  5611. h: 0,
  5612. s: 0,
  5613. l: 0
  5614. };
  5615. var _hslB = {
  5616. h: 0,
  5617. s: 0,
  5618. l: 0
  5619. };
  5620. function Color(r, g, b) {
  5621. if (g === undefined && b === undefined) {
  5622. // r is THREE.Color, hex or string
  5623. return this.set(r);
  5624. }
  5625. return this.setRGB(r, g, b);
  5626. }
  5627. function hue2rgb(p, q, t) {
  5628. if (t < 0) t += 1;
  5629. if (t > 1) t -= 1;
  5630. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5631. if (t < 1 / 2) return q;
  5632. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5633. return p;
  5634. }
  5635. function SRGBToLinear(c) {
  5636. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5637. }
  5638. function LinearToSRGB(c) {
  5639. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5640. }
  5641. Object.assign(Color.prototype, {
  5642. isColor: true,
  5643. r: 1,
  5644. g: 1,
  5645. b: 1,
  5646. set: function (value) {
  5647. if (value && value.isColor) {
  5648. this.copy(value);
  5649. } else if (typeof value === 'number') {
  5650. this.setHex(value);
  5651. } else if (typeof value === 'string') {
  5652. this.setStyle(value);
  5653. }
  5654. return this;
  5655. },
  5656. setScalar: function (scalar) {
  5657. this.r = scalar;
  5658. this.g = scalar;
  5659. this.b = scalar;
  5660. return this;
  5661. },
  5662. setHex: function (hex) {
  5663. hex = Math.floor(hex);
  5664. this.r = (hex >> 16 & 255) / 255;
  5665. this.g = (hex >> 8 & 255) / 255;
  5666. this.b = (hex & 255) / 255;
  5667. return this;
  5668. },
  5669. setRGB: function (r, g, b) {
  5670. this.r = r;
  5671. this.g = g;
  5672. this.b = b;
  5673. return this;
  5674. },
  5675. setHSL: function (h, s, l) {
  5676. // h,s,l ranges are in 0.0 - 1.0
  5677. h = MathUtils.euclideanModulo(h, 1);
  5678. s = MathUtils.clamp(s, 0, 1);
  5679. l = MathUtils.clamp(l, 0, 1);
  5680. if (s === 0) {
  5681. this.r = this.g = this.b = l;
  5682. } else {
  5683. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5684. var q = 2 * l - p;
  5685. this.r = hue2rgb(q, p, h + 1 / 3);
  5686. this.g = hue2rgb(q, p, h);
  5687. this.b = hue2rgb(q, p, h - 1 / 3);
  5688. }
  5689. return this;
  5690. },
  5691. setStyle: function (style) {
  5692. function handleAlpha(string) {
  5693. if (string === undefined) return;
  5694. if (parseFloat(string) < 1) {
  5695. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5696. }
  5697. }
  5698. var m;
  5699. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5700. // rgb / hsl
  5701. var color;
  5702. var name = m[1];
  5703. var components = m[2];
  5704. switch (name) {
  5705. case 'rgb':
  5706. case 'rgba':
  5707. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5708. // rgb(255,0,0) rgba(255,0,0,0.5)
  5709. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5710. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5711. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5712. handleAlpha(color[5]);
  5713. return this;
  5714. }
  5715. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5716. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5717. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5718. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5719. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5720. handleAlpha(color[5]);
  5721. return this;
  5722. }
  5723. break;
  5724. case 'hsl':
  5725. case 'hsla':
  5726. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5727. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5728. var h = parseFloat(color[1]) / 360;
  5729. var s = parseInt(color[2], 10) / 100;
  5730. var l = parseInt(color[3], 10) / 100;
  5731. handleAlpha(color[5]);
  5732. return this.setHSL(h, s, l);
  5733. }
  5734. break;
  5735. }
  5736. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5737. // hex color
  5738. var hex = m[1];
  5739. var size = hex.length;
  5740. if (size === 3) {
  5741. // #ff0
  5742. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5743. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5744. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5745. return this;
  5746. } else if (size === 6) {
  5747. // #ff0000
  5748. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5749. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5750. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5751. return this;
  5752. }
  5753. }
  5754. if (style && style.length > 0) {
  5755. return this.setColorName(style);
  5756. }
  5757. return this;
  5758. },
  5759. setColorName: function (style) {
  5760. // color keywords
  5761. var hex = _colorKeywords[style];
  5762. if (hex !== undefined) {
  5763. // red
  5764. this.setHex(hex);
  5765. } else {
  5766. // unknown color
  5767. console.warn('THREE.Color: Unknown color ' + style);
  5768. }
  5769. return this;
  5770. },
  5771. clone: function () {
  5772. return new this.constructor(this.r, this.g, this.b);
  5773. },
  5774. copy: function (color) {
  5775. this.r = color.r;
  5776. this.g = color.g;
  5777. this.b = color.b;
  5778. return this;
  5779. },
  5780. copyGammaToLinear: function (color, gammaFactor) {
  5781. if (gammaFactor === undefined) gammaFactor = 2.0;
  5782. this.r = Math.pow(color.r, gammaFactor);
  5783. this.g = Math.pow(color.g, gammaFactor);
  5784. this.b = Math.pow(color.b, gammaFactor);
  5785. return this;
  5786. },
  5787. copyLinearToGamma: function (color, gammaFactor) {
  5788. if (gammaFactor === undefined) gammaFactor = 2.0;
  5789. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5790. this.r = Math.pow(color.r, safeInverse);
  5791. this.g = Math.pow(color.g, safeInverse);
  5792. this.b = Math.pow(color.b, safeInverse);
  5793. return this;
  5794. },
  5795. convertGammaToLinear: function (gammaFactor) {
  5796. this.copyGammaToLinear(this, gammaFactor);
  5797. return this;
  5798. },
  5799. convertLinearToGamma: function (gammaFactor) {
  5800. this.copyLinearToGamma(this, gammaFactor);
  5801. return this;
  5802. },
  5803. copySRGBToLinear: function (color) {
  5804. this.r = SRGBToLinear(color.r);
  5805. this.g = SRGBToLinear(color.g);
  5806. this.b = SRGBToLinear(color.b);
  5807. return this;
  5808. },
  5809. copyLinearToSRGB: function (color) {
  5810. this.r = LinearToSRGB(color.r);
  5811. this.g = LinearToSRGB(color.g);
  5812. this.b = LinearToSRGB(color.b);
  5813. return this;
  5814. },
  5815. convertSRGBToLinear: function () {
  5816. this.copySRGBToLinear(this);
  5817. return this;
  5818. },
  5819. convertLinearToSRGB: function () {
  5820. this.copyLinearToSRGB(this);
  5821. return this;
  5822. },
  5823. getHex: function () {
  5824. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5825. },
  5826. getHexString: function () {
  5827. return ('000000' + this.getHex().toString(16)).slice(-6);
  5828. },
  5829. getHSL: function (target) {
  5830. // h,s,l ranges are in 0.0 - 1.0
  5831. if (target === undefined) {
  5832. console.warn('THREE.Color: .getHSL() target is now required');
  5833. target = {
  5834. h: 0,
  5835. s: 0,
  5836. l: 0
  5837. };
  5838. }
  5839. var r = this.r,
  5840. g = this.g,
  5841. b = this.b;
  5842. var max = Math.max(r, g, b);
  5843. var min = Math.min(r, g, b);
  5844. var hue, saturation;
  5845. var lightness = (min + max) / 2.0;
  5846. if (min === max) {
  5847. hue = 0;
  5848. saturation = 0;
  5849. } else {
  5850. var delta = max - min;
  5851. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5852. switch (max) {
  5853. case r:
  5854. hue = (g - b) / delta + (g < b ? 6 : 0);
  5855. break;
  5856. case g:
  5857. hue = (b - r) / delta + 2;
  5858. break;
  5859. case b:
  5860. hue = (r - g) / delta + 4;
  5861. break;
  5862. }
  5863. hue /= 6;
  5864. }
  5865. target.h = hue;
  5866. target.s = saturation;
  5867. target.l = lightness;
  5868. return target;
  5869. },
  5870. getStyle: function () {
  5871. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5872. },
  5873. offsetHSL: function (h, s, l) {
  5874. this.getHSL(_hslA);
  5875. _hslA.h += h;
  5876. _hslA.s += s;
  5877. _hslA.l += l;
  5878. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5879. return this;
  5880. },
  5881. add: function (color) {
  5882. this.r += color.r;
  5883. this.g += color.g;
  5884. this.b += color.b;
  5885. return this;
  5886. },
  5887. addColors: function (color1, color2) {
  5888. this.r = color1.r + color2.r;
  5889. this.g = color1.g + color2.g;
  5890. this.b = color1.b + color2.b;
  5891. return this;
  5892. },
  5893. addScalar: function (s) {
  5894. this.r += s;
  5895. this.g += s;
  5896. this.b += s;
  5897. return this;
  5898. },
  5899. sub: function (color) {
  5900. this.r = Math.max(0, this.r - color.r);
  5901. this.g = Math.max(0, this.g - color.g);
  5902. this.b = Math.max(0, this.b - color.b);
  5903. return this;
  5904. },
  5905. multiply: function (color) {
  5906. this.r *= color.r;
  5907. this.g *= color.g;
  5908. this.b *= color.b;
  5909. return this;
  5910. },
  5911. multiplyScalar: function (s) {
  5912. this.r *= s;
  5913. this.g *= s;
  5914. this.b *= s;
  5915. return this;
  5916. },
  5917. lerp: function (color, alpha) {
  5918. this.r += (color.r - this.r) * alpha;
  5919. this.g += (color.g - this.g) * alpha;
  5920. this.b += (color.b - this.b) * alpha;
  5921. return this;
  5922. },
  5923. lerpHSL: function (color, alpha) {
  5924. this.getHSL(_hslA);
  5925. color.getHSL(_hslB);
  5926. var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  5927. var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  5928. var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  5929. this.setHSL(h, s, l);
  5930. return this;
  5931. },
  5932. equals: function (c) {
  5933. return c.r === this.r && c.g === this.g && c.b === this.b;
  5934. },
  5935. fromArray: function (array, offset) {
  5936. if (offset === undefined) offset = 0;
  5937. this.r = array[offset];
  5938. this.g = array[offset + 1];
  5939. this.b = array[offset + 2];
  5940. return this;
  5941. },
  5942. toArray: function (array, offset) {
  5943. if (array === undefined) array = [];
  5944. if (offset === undefined) offset = 0;
  5945. array[offset] = this.r;
  5946. array[offset + 1] = this.g;
  5947. array[offset + 2] = this.b;
  5948. return array;
  5949. },
  5950. toJSON: function () {
  5951. return this.getHex();
  5952. }
  5953. });
  5954. Color.NAMES = _colorKeywords;
  5955. /**
  5956. * @author mrdoob / http://mrdoob.com/
  5957. * @author alteredq / http://alteredqualia.com/
  5958. */
  5959. function Face3(a, b, c, normal, color, materialIndex) {
  5960. this.a = a;
  5961. this.b = b;
  5962. this.c = c;
  5963. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5964. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5965. this.color = color && color.isColor ? color : new Color();
  5966. this.vertexColors = Array.isArray(color) ? color : [];
  5967. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5968. }
  5969. Object.assign(Face3.prototype, {
  5970. clone: function () {
  5971. return new this.constructor().copy(this);
  5972. },
  5973. copy: function (source) {
  5974. this.a = source.a;
  5975. this.b = source.b;
  5976. this.c = source.c;
  5977. this.normal.copy(source.normal);
  5978. this.color.copy(source.color);
  5979. this.materialIndex = source.materialIndex;
  5980. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  5981. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5982. }
  5983. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  5984. this.vertexColors[i] = source.vertexColors[i].clone();
  5985. }
  5986. return this;
  5987. }
  5988. });
  5989. /**
  5990. * @author mrdoob / http://mrdoob.com/
  5991. * @author alteredq / http://alteredqualia.com/
  5992. */
  5993. var materialId = 0;
  5994. function Material() {
  5995. Object.defineProperty(this, 'id', {
  5996. value: materialId++
  5997. });
  5998. this.uuid = MathUtils.generateUUID();
  5999. this.name = '';
  6000. this.type = 'Material';
  6001. this.fog = true;
  6002. this.blending = NormalBlending;
  6003. this.side = FrontSide;
  6004. this.flatShading = false;
  6005. this.vertexColors = false;
  6006. this.opacity = 1;
  6007. this.transparent = false;
  6008. this.blendSrc = SrcAlphaFactor;
  6009. this.blendDst = OneMinusSrcAlphaFactor;
  6010. this.blendEquation = AddEquation;
  6011. this.blendSrcAlpha = null;
  6012. this.blendDstAlpha = null;
  6013. this.blendEquationAlpha = null;
  6014. this.depthFunc = LessEqualDepth;
  6015. this.depthTest = true;
  6016. this.depthWrite = true;
  6017. this.stencilWriteMask = 0xff;
  6018. this.stencilFunc = AlwaysStencilFunc;
  6019. this.stencilRef = 0;
  6020. this.stencilFuncMask = 0xff;
  6021. this.stencilFail = KeepStencilOp;
  6022. this.stencilZFail = KeepStencilOp;
  6023. this.stencilZPass = KeepStencilOp;
  6024. this.stencilWrite = false;
  6025. this.clippingPlanes = null;
  6026. this.clipIntersection = false;
  6027. this.clipShadows = false;
  6028. this.shadowSide = null;
  6029. this.colorWrite = true;
  6030. this.precision = null; // override the renderer's default precision for this material
  6031. this.polygonOffset = false;
  6032. this.polygonOffsetFactor = 0;
  6033. this.polygonOffsetUnits = 0;
  6034. this.dithering = false;
  6035. this.alphaTest = 0;
  6036. this.premultipliedAlpha = false;
  6037. this.visible = true;
  6038. this.toneMapped = true;
  6039. this.userData = {};
  6040. this.version = 0;
  6041. }
  6042. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6043. constructor: Material,
  6044. isMaterial: true,
  6045. onBeforeCompile: function () {},
  6046. setValues: function (values) {
  6047. if (values === undefined) return;
  6048. for (var key in values) {
  6049. var newValue = values[key];
  6050. if (newValue === undefined) {
  6051. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6052. continue;
  6053. } // for backward compatability if shading is set in the constructor
  6054. if (key === 'shading') {
  6055. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6056. this.flatShading = newValue === FlatShading ? true : false;
  6057. continue;
  6058. }
  6059. var currentValue = this[key];
  6060. if (currentValue === undefined) {
  6061. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6062. continue;
  6063. }
  6064. if (currentValue && currentValue.isColor) {
  6065. currentValue.set(newValue);
  6066. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6067. currentValue.copy(newValue);
  6068. } else {
  6069. this[key] = newValue;
  6070. }
  6071. }
  6072. },
  6073. toJSON: function (meta) {
  6074. var isRoot = meta === undefined || typeof meta === 'string';
  6075. if (isRoot) {
  6076. meta = {
  6077. textures: {},
  6078. images: {}
  6079. };
  6080. }
  6081. var data = {
  6082. metadata: {
  6083. version: 4.5,
  6084. type: 'Material',
  6085. generator: 'Material.toJSON'
  6086. }
  6087. }; // standard Material serialization
  6088. data.uuid = this.uuid;
  6089. data.type = this.type;
  6090. if (this.name !== '') data.name = this.name;
  6091. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6092. if (this.roughness !== undefined) data.roughness = this.roughness;
  6093. if (this.metalness !== undefined) data.metalness = this.metalness;
  6094. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6095. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6096. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6097. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6098. if (this.shininess !== undefined) data.shininess = this.shininess;
  6099. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6100. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6101. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  6102. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  6103. }
  6104. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  6105. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  6106. }
  6107. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6108. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  6109. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6110. }
  6111. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  6112. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  6113. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  6114. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  6115. if (this.aoMap && this.aoMap.isTexture) {
  6116. data.aoMap = this.aoMap.toJSON(meta).uuid;
  6117. data.aoMapIntensity = this.aoMapIntensity;
  6118. }
  6119. if (this.bumpMap && this.bumpMap.isTexture) {
  6120. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  6121. data.bumpScale = this.bumpScale;
  6122. }
  6123. if (this.normalMap && this.normalMap.isTexture) {
  6124. data.normalMap = this.normalMap.toJSON(meta).uuid;
  6125. data.normalMapType = this.normalMapType;
  6126. data.normalScale = this.normalScale.toArray();
  6127. }
  6128. if (this.displacementMap && this.displacementMap.isTexture) {
  6129. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  6130. data.displacementScale = this.displacementScale;
  6131. data.displacementBias = this.displacementBias;
  6132. }
  6133. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  6134. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  6135. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  6136. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  6137. if (this.envMap && this.envMap.isTexture) {
  6138. data.envMap = this.envMap.toJSON(meta).uuid;
  6139. data.reflectivity = this.reflectivity; // Scale behind envMap
  6140. data.refractionRatio = this.refractionRatio;
  6141. if (this.combine !== undefined) data.combine = this.combine;
  6142. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  6143. }
  6144. if (this.gradientMap && this.gradientMap.isTexture) {
  6145. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  6146. }
  6147. if (this.size !== undefined) data.size = this.size;
  6148. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  6149. if (this.blending !== NormalBlending) data.blending = this.blending;
  6150. if (this.flatShading === true) data.flatShading = this.flatShading;
  6151. if (this.side !== FrontSide) data.side = this.side;
  6152. if (this.vertexColors) data.vertexColors = true;
  6153. if (this.opacity < 1) data.opacity = this.opacity;
  6154. if (this.transparent === true) data.transparent = this.transparent;
  6155. data.depthFunc = this.depthFunc;
  6156. data.depthTest = this.depthTest;
  6157. data.depthWrite = this.depthWrite;
  6158. data.stencilWrite = this.stencilWrite;
  6159. data.stencilWriteMask = this.stencilWriteMask;
  6160. data.stencilFunc = this.stencilFunc;
  6161. data.stencilRef = this.stencilRef;
  6162. data.stencilFuncMask = this.stencilFuncMask;
  6163. data.stencilFail = this.stencilFail;
  6164. data.stencilZFail = this.stencilZFail;
  6165. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  6166. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  6167. if (this.polygonOffset === true) data.polygonOffset = true;
  6168. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6169. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6170. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  6171. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  6172. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  6173. if (this.scale !== undefined) data.scale = this.scale;
  6174. if (this.dithering === true) data.dithering = true;
  6175. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  6176. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  6177. if (this.wireframe === true) data.wireframe = this.wireframe;
  6178. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  6179. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  6180. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  6181. if (this.morphTargets === true) data.morphTargets = true;
  6182. if (this.morphNormals === true) data.morphNormals = true;
  6183. if (this.skinning === true) data.skinning = true;
  6184. if (this.visible === false) data.visible = false;
  6185. if (this.toneMapped === false) data.toneMapped = false;
  6186. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  6187. function extractFromCache(cache) {
  6188. var values = [];
  6189. for (var key in cache) {
  6190. var data = cache[key];
  6191. delete data.metadata;
  6192. values.push(data);
  6193. }
  6194. return values;
  6195. }
  6196. if (isRoot) {
  6197. var textures = extractFromCache(meta.textures);
  6198. var images = extractFromCache(meta.images);
  6199. if (textures.length > 0) data.textures = textures;
  6200. if (images.length > 0) data.images = images;
  6201. }
  6202. return data;
  6203. },
  6204. clone: function () {
  6205. return new this.constructor().copy(this);
  6206. },
  6207. copy: function (source) {
  6208. this.name = source.name;
  6209. this.fog = source.fog;
  6210. this.blending = source.blending;
  6211. this.side = source.side;
  6212. this.flatShading = source.flatShading;
  6213. this.vertexColors = source.vertexColors;
  6214. this.opacity = source.opacity;
  6215. this.transparent = source.transparent;
  6216. this.blendSrc = source.blendSrc;
  6217. this.blendDst = source.blendDst;
  6218. this.blendEquation = source.blendEquation;
  6219. this.blendSrcAlpha = source.blendSrcAlpha;
  6220. this.blendDstAlpha = source.blendDstAlpha;
  6221. this.blendEquationAlpha = source.blendEquationAlpha;
  6222. this.depthFunc = source.depthFunc;
  6223. this.depthTest = source.depthTest;
  6224. this.depthWrite = source.depthWrite;
  6225. this.stencilWriteMask = source.stencilWriteMask;
  6226. this.stencilFunc = source.stencilFunc;
  6227. this.stencilRef = source.stencilRef;
  6228. this.stencilFuncMask = source.stencilFuncMask;
  6229. this.stencilFail = source.stencilFail;
  6230. this.stencilZFail = source.stencilZFail;
  6231. this.stencilZPass = source.stencilZPass;
  6232. this.stencilWrite = source.stencilWrite;
  6233. var srcPlanes = source.clippingPlanes,
  6234. dstPlanes = null;
  6235. if (srcPlanes !== null) {
  6236. var n = srcPlanes.length;
  6237. dstPlanes = new Array(n);
  6238. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  6239. }
  6240. this.clippingPlanes = dstPlanes;
  6241. this.clipIntersection = source.clipIntersection;
  6242. this.clipShadows = source.clipShadows;
  6243. this.shadowSide = source.shadowSide;
  6244. this.colorWrite = source.colorWrite;
  6245. this.precision = source.precision;
  6246. this.polygonOffset = source.polygonOffset;
  6247. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6248. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6249. this.dithering = source.dithering;
  6250. this.alphaTest = source.alphaTest;
  6251. this.premultipliedAlpha = source.premultipliedAlpha;
  6252. this.visible = source.visible;
  6253. this.toneMapped = source.toneMapped;
  6254. this.userData = JSON.parse(JSON.stringify(source.userData));
  6255. return this;
  6256. },
  6257. dispose: function () {
  6258. this.dispatchEvent({
  6259. type: 'dispose'
  6260. });
  6261. }
  6262. });
  6263. Object.defineProperty(Material.prototype, 'needsUpdate', {
  6264. set: function (value) {
  6265. if (value === true) this.version++;
  6266. }
  6267. });
  6268. /**
  6269. * @author mrdoob / http://mrdoob.com/
  6270. * @author alteredq / http://alteredqualia.com/
  6271. *
  6272. * parameters = {
  6273. * color: <hex>,
  6274. * opacity: <float>,
  6275. * map: new THREE.Texture( <Image> ),
  6276. *
  6277. * lightMap: new THREE.Texture( <Image> ),
  6278. * lightMapIntensity: <float>
  6279. *
  6280. * aoMap: new THREE.Texture( <Image> ),
  6281. * aoMapIntensity: <float>
  6282. *
  6283. * specularMap: new THREE.Texture( <Image> ),
  6284. *
  6285. * alphaMap: new THREE.Texture( <Image> ),
  6286. *
  6287. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6288. * combine: THREE.Multiply,
  6289. * reflectivity: <float>,
  6290. * refractionRatio: <float>,
  6291. *
  6292. * depthTest: <bool>,
  6293. * depthWrite: <bool>,
  6294. *
  6295. * wireframe: <boolean>,
  6296. * wireframeLinewidth: <float>,
  6297. *
  6298. * skinning: <bool>,
  6299. * morphTargets: <bool>
  6300. * }
  6301. */
  6302. function MeshBasicMaterial(parameters) {
  6303. Material.call(this);
  6304. this.type = 'MeshBasicMaterial';
  6305. this.color = new Color(0xffffff); // emissive
  6306. this.map = null;
  6307. this.lightMap = null;
  6308. this.lightMapIntensity = 1.0;
  6309. this.aoMap = null;
  6310. this.aoMapIntensity = 1.0;
  6311. this.specularMap = null;
  6312. this.alphaMap = null;
  6313. this.envMap = null;
  6314. this.combine = MultiplyOperation;
  6315. this.reflectivity = 1;
  6316. this.refractionRatio = 0.98;
  6317. this.wireframe = false;
  6318. this.wireframeLinewidth = 1;
  6319. this.wireframeLinecap = 'round';
  6320. this.wireframeLinejoin = 'round';
  6321. this.skinning = false;
  6322. this.morphTargets = false;
  6323. this.setValues(parameters);
  6324. }
  6325. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6326. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6327. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6328. MeshBasicMaterial.prototype.copy = function (source) {
  6329. Material.prototype.copy.call(this, source);
  6330. this.color.copy(source.color);
  6331. this.map = source.map;
  6332. this.lightMap = source.lightMap;
  6333. this.lightMapIntensity = source.lightMapIntensity;
  6334. this.aoMap = source.aoMap;
  6335. this.aoMapIntensity = source.aoMapIntensity;
  6336. this.specularMap = source.specularMap;
  6337. this.alphaMap = source.alphaMap;
  6338. this.envMap = source.envMap;
  6339. this.combine = source.combine;
  6340. this.reflectivity = source.reflectivity;
  6341. this.refractionRatio = source.refractionRatio;
  6342. this.wireframe = source.wireframe;
  6343. this.wireframeLinewidth = source.wireframeLinewidth;
  6344. this.wireframeLinecap = source.wireframeLinecap;
  6345. this.wireframeLinejoin = source.wireframeLinejoin;
  6346. this.skinning = source.skinning;
  6347. this.morphTargets = source.morphTargets;
  6348. return this;
  6349. };
  6350. /**
  6351. * @author mrdoob / http://mrdoob.com/
  6352. */
  6353. var _vector$3 = new Vector3();
  6354. function BufferAttribute(array, itemSize, normalized) {
  6355. if (Array.isArray(array)) {
  6356. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6357. }
  6358. this.name = '';
  6359. this.array = array;
  6360. this.itemSize = itemSize;
  6361. this.count = array !== undefined ? array.length / itemSize : 0;
  6362. this.normalized = normalized === true;
  6363. this.usage = StaticDrawUsage;
  6364. this.updateRange = {
  6365. offset: 0,
  6366. count: -1
  6367. };
  6368. this.version = 0;
  6369. }
  6370. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6371. set: function (value) {
  6372. if (value === true) this.version++;
  6373. }
  6374. });
  6375. Object.assign(BufferAttribute.prototype, {
  6376. isBufferAttribute: true,
  6377. onUploadCallback: function () {},
  6378. setUsage: function (value) {
  6379. this.usage = value;
  6380. return this;
  6381. },
  6382. copy: function (source) {
  6383. this.name = source.name;
  6384. this.array = new source.array.constructor(source.array);
  6385. this.itemSize = source.itemSize;
  6386. this.count = source.count;
  6387. this.normalized = source.normalized;
  6388. this.usage = source.usage;
  6389. return this;
  6390. },
  6391. copyAt: function (index1, attribute, index2) {
  6392. index1 *= this.itemSize;
  6393. index2 *= attribute.itemSize;
  6394. for (var i = 0, l = this.itemSize; i < l; i++) {
  6395. this.array[index1 + i] = attribute.array[index2 + i];
  6396. }
  6397. return this;
  6398. },
  6399. copyArray: function (array) {
  6400. this.array.set(array);
  6401. return this;
  6402. },
  6403. copyColorsArray: function (colors) {
  6404. var array = this.array,
  6405. offset = 0;
  6406. for (var i = 0, l = colors.length; i < l; i++) {
  6407. var color = colors[i];
  6408. if (color === undefined) {
  6409. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6410. color = new Color();
  6411. }
  6412. array[offset++] = color.r;
  6413. array[offset++] = color.g;
  6414. array[offset++] = color.b;
  6415. }
  6416. return this;
  6417. },
  6418. copyVector2sArray: function (vectors) {
  6419. var array = this.array,
  6420. offset = 0;
  6421. for (var i = 0, l = vectors.length; i < l; i++) {
  6422. var vector = vectors[i];
  6423. if (vector === undefined) {
  6424. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6425. vector = new Vector2();
  6426. }
  6427. array[offset++] = vector.x;
  6428. array[offset++] = vector.y;
  6429. }
  6430. return this;
  6431. },
  6432. copyVector3sArray: function (vectors) {
  6433. var array = this.array,
  6434. offset = 0;
  6435. for (var i = 0, l = vectors.length; i < l; i++) {
  6436. var vector = vectors[i];
  6437. if (vector === undefined) {
  6438. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6439. vector = new Vector3();
  6440. }
  6441. array[offset++] = vector.x;
  6442. array[offset++] = vector.y;
  6443. array[offset++] = vector.z;
  6444. }
  6445. return this;
  6446. },
  6447. copyVector4sArray: function (vectors) {
  6448. var array = this.array,
  6449. offset = 0;
  6450. for (var i = 0, l = vectors.length; i < l; i++) {
  6451. var vector = vectors[i];
  6452. if (vector === undefined) {
  6453. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6454. vector = new Vector4();
  6455. }
  6456. array[offset++] = vector.x;
  6457. array[offset++] = vector.y;
  6458. array[offset++] = vector.z;
  6459. array[offset++] = vector.w;
  6460. }
  6461. return this;
  6462. },
  6463. applyMatrix3: function (m) {
  6464. for (var i = 0, l = this.count; i < l; i++) {
  6465. _vector$3.x = this.getX(i);
  6466. _vector$3.y = this.getY(i);
  6467. _vector$3.z = this.getZ(i);
  6468. _vector$3.applyMatrix3(m);
  6469. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6470. }
  6471. return this;
  6472. },
  6473. applyMatrix4: function (m) {
  6474. for (var i = 0, l = this.count; i < l; i++) {
  6475. _vector$3.x = this.getX(i);
  6476. _vector$3.y = this.getY(i);
  6477. _vector$3.z = this.getZ(i);
  6478. _vector$3.applyMatrix4(m);
  6479. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6480. }
  6481. return this;
  6482. },
  6483. applyNormalMatrix: function (m) {
  6484. for (var i = 0, l = this.count; i < l; i++) {
  6485. _vector$3.x = this.getX(i);
  6486. _vector$3.y = this.getY(i);
  6487. _vector$3.z = this.getZ(i);
  6488. _vector$3.applyNormalMatrix(m);
  6489. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6490. }
  6491. return this;
  6492. },
  6493. transformDirection: function (m) {
  6494. for (var i = 0, l = this.count; i < l; i++) {
  6495. _vector$3.x = this.getX(i);
  6496. _vector$3.y = this.getY(i);
  6497. _vector$3.z = this.getZ(i);
  6498. _vector$3.transformDirection(m);
  6499. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6500. }
  6501. return this;
  6502. },
  6503. set: function (value, offset) {
  6504. if (offset === undefined) offset = 0;
  6505. this.array.set(value, offset);
  6506. return this;
  6507. },
  6508. getX: function (index) {
  6509. return this.array[index * this.itemSize];
  6510. },
  6511. setX: function (index, x) {
  6512. this.array[index * this.itemSize] = x;
  6513. return this;
  6514. },
  6515. getY: function (index) {
  6516. return this.array[index * this.itemSize + 1];
  6517. },
  6518. setY: function (index, y) {
  6519. this.array[index * this.itemSize + 1] = y;
  6520. return this;
  6521. },
  6522. getZ: function (index) {
  6523. return this.array[index * this.itemSize + 2];
  6524. },
  6525. setZ: function (index, z) {
  6526. this.array[index * this.itemSize + 2] = z;
  6527. return this;
  6528. },
  6529. getW: function (index) {
  6530. return this.array[index * this.itemSize + 3];
  6531. },
  6532. setW: function (index, w) {
  6533. this.array[index * this.itemSize + 3] = w;
  6534. return this;
  6535. },
  6536. setXY: function (index, x, y) {
  6537. index *= this.itemSize;
  6538. this.array[index + 0] = x;
  6539. this.array[index + 1] = y;
  6540. return this;
  6541. },
  6542. setXYZ: function (index, x, y, z) {
  6543. index *= this.itemSize;
  6544. this.array[index + 0] = x;
  6545. this.array[index + 1] = y;
  6546. this.array[index + 2] = z;
  6547. return this;
  6548. },
  6549. setXYZW: function (index, x, y, z, w) {
  6550. index *= this.itemSize;
  6551. this.array[index + 0] = x;
  6552. this.array[index + 1] = y;
  6553. this.array[index + 2] = z;
  6554. this.array[index + 3] = w;
  6555. return this;
  6556. },
  6557. onUpload: function (callback) {
  6558. this.onUploadCallback = callback;
  6559. return this;
  6560. },
  6561. clone: function () {
  6562. return new this.constructor(this.array, this.itemSize).copy(this);
  6563. },
  6564. toJSON: function () {
  6565. return {
  6566. itemSize: this.itemSize,
  6567. type: this.array.constructor.name,
  6568. array: Array.prototype.slice.call(this.array),
  6569. normalized: this.normalized
  6570. };
  6571. }
  6572. }); //
  6573. function Int8BufferAttribute(array, itemSize, normalized) {
  6574. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6575. }
  6576. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6577. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6578. function Uint8BufferAttribute(array, itemSize, normalized) {
  6579. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6580. }
  6581. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6582. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6583. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6584. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6585. }
  6586. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6587. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6588. function Int16BufferAttribute(array, itemSize, normalized) {
  6589. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6590. }
  6591. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6592. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6593. function Uint16BufferAttribute(array, itemSize, normalized) {
  6594. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6595. }
  6596. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6597. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6598. function Int32BufferAttribute(array, itemSize, normalized) {
  6599. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6600. }
  6601. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6602. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6603. function Uint32BufferAttribute(array, itemSize, normalized) {
  6604. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6605. }
  6606. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6607. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6608. function Float32BufferAttribute(array, itemSize, normalized) {
  6609. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6610. }
  6611. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6612. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6613. function Float64BufferAttribute(array, itemSize, normalized) {
  6614. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6615. }
  6616. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6617. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6618. /**
  6619. * @author mrdoob / http://mrdoob.com/
  6620. */
  6621. function DirectGeometry() {
  6622. this.vertices = [];
  6623. this.normals = [];
  6624. this.colors = [];
  6625. this.uvs = [];
  6626. this.uvs2 = [];
  6627. this.groups = [];
  6628. this.morphTargets = {};
  6629. this.skinWeights = [];
  6630. this.skinIndices = []; // this.lineDistances = [];
  6631. this.boundingBox = null;
  6632. this.boundingSphere = null; // update flags
  6633. this.verticesNeedUpdate = false;
  6634. this.normalsNeedUpdate = false;
  6635. this.colorsNeedUpdate = false;
  6636. this.uvsNeedUpdate = false;
  6637. this.groupsNeedUpdate = false;
  6638. }
  6639. Object.assign(DirectGeometry.prototype, {
  6640. computeGroups: function (geometry) {
  6641. var group;
  6642. var groups = [];
  6643. var materialIndex = undefined;
  6644. var faces = geometry.faces;
  6645. for (var i = 0; i < faces.length; i++) {
  6646. var face = faces[i]; // materials
  6647. if (face.materialIndex !== materialIndex) {
  6648. materialIndex = face.materialIndex;
  6649. if (group !== undefined) {
  6650. group.count = i * 3 - group.start;
  6651. groups.push(group);
  6652. }
  6653. group = {
  6654. start: i * 3,
  6655. materialIndex: materialIndex
  6656. };
  6657. }
  6658. }
  6659. if (group !== undefined) {
  6660. group.count = i * 3 - group.start;
  6661. groups.push(group);
  6662. }
  6663. this.groups = groups;
  6664. },
  6665. fromGeometry: function (geometry) {
  6666. var faces = geometry.faces;
  6667. var vertices = geometry.vertices;
  6668. var faceVertexUvs = geometry.faceVertexUvs;
  6669. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6670. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6671. var morphTargets = geometry.morphTargets;
  6672. var morphTargetsLength = morphTargets.length;
  6673. var morphTargetsPosition;
  6674. if (morphTargetsLength > 0) {
  6675. morphTargetsPosition = [];
  6676. for (var i = 0; i < morphTargetsLength; i++) {
  6677. morphTargetsPosition[i] = {
  6678. name: morphTargets[i].name,
  6679. data: []
  6680. };
  6681. }
  6682. this.morphTargets.position = morphTargetsPosition;
  6683. }
  6684. var morphNormals = geometry.morphNormals;
  6685. var morphNormalsLength = morphNormals.length;
  6686. var morphTargetsNormal;
  6687. if (morphNormalsLength > 0) {
  6688. morphTargetsNormal = [];
  6689. for (var i = 0; i < morphNormalsLength; i++) {
  6690. morphTargetsNormal[i] = {
  6691. name: morphNormals[i].name,
  6692. data: []
  6693. };
  6694. }
  6695. this.morphTargets.normal = morphTargetsNormal;
  6696. } // skins
  6697. var skinIndices = geometry.skinIndices;
  6698. var skinWeights = geometry.skinWeights;
  6699. var hasSkinIndices = skinIndices.length === vertices.length;
  6700. var hasSkinWeights = skinWeights.length === vertices.length; //
  6701. if (vertices.length > 0 && faces.length === 0) {
  6702. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6703. }
  6704. for (var i = 0; i < faces.length; i++) {
  6705. var face = faces[i];
  6706. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6707. var vertexNormals = face.vertexNormals;
  6708. if (vertexNormals.length === 3) {
  6709. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6710. } else {
  6711. var normal = face.normal;
  6712. this.normals.push(normal, normal, normal);
  6713. }
  6714. var vertexColors = face.vertexColors;
  6715. if (vertexColors.length === 3) {
  6716. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6717. } else {
  6718. var color = face.color;
  6719. this.colors.push(color, color, color);
  6720. }
  6721. if (hasFaceVertexUv === true) {
  6722. var vertexUvs = faceVertexUvs[0][i];
  6723. if (vertexUvs !== undefined) {
  6724. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6725. } else {
  6726. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6727. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6728. }
  6729. }
  6730. if (hasFaceVertexUv2 === true) {
  6731. var vertexUvs = faceVertexUvs[1][i];
  6732. if (vertexUvs !== undefined) {
  6733. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6734. } else {
  6735. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6736. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6737. }
  6738. } // morphs
  6739. for (var j = 0; j < morphTargetsLength; j++) {
  6740. var morphTarget = morphTargets[j].vertices;
  6741. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6742. }
  6743. for (var j = 0; j < morphNormalsLength; j++) {
  6744. var morphNormal = morphNormals[j].vertexNormals[i];
  6745. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6746. } // skins
  6747. if (hasSkinIndices) {
  6748. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6749. }
  6750. if (hasSkinWeights) {
  6751. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6752. }
  6753. }
  6754. this.computeGroups(geometry);
  6755. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6756. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6757. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6758. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6759. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6760. if (geometry.boundingSphere !== null) {
  6761. this.boundingSphere = geometry.boundingSphere.clone();
  6762. }
  6763. if (geometry.boundingBox !== null) {
  6764. this.boundingBox = geometry.boundingBox.clone();
  6765. }
  6766. return this;
  6767. }
  6768. });
  6769. /**
  6770. * @author mrdoob / http://mrdoob.com/
  6771. */
  6772. function arrayMax(array) {
  6773. if (array.length === 0) return -Infinity;
  6774. var max = array[0];
  6775. for (var i = 1, l = array.length; i < l; ++i) {
  6776. if (array[i] > max) max = array[i];
  6777. }
  6778. return max;
  6779. }
  6780. /**
  6781. * @author alteredq / http://alteredqualia.com/
  6782. * @author mrdoob / http://mrdoob.com/
  6783. */
  6784. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6785. var _m1$2 = new Matrix4();
  6786. var _obj = new Object3D();
  6787. var _offset = new Vector3();
  6788. var _box$2 = new Box3();
  6789. var _boxMorphTargets = new Box3();
  6790. var _vector$4 = new Vector3();
  6791. function BufferGeometry() {
  6792. Object.defineProperty(this, 'id', {
  6793. value: _bufferGeometryId += 2
  6794. });
  6795. this.uuid = MathUtils.generateUUID();
  6796. this.name = '';
  6797. this.type = 'BufferGeometry';
  6798. this.index = null;
  6799. this.attributes = {};
  6800. this.morphAttributes = {};
  6801. this.morphTargetsRelative = false;
  6802. this.groups = [];
  6803. this.boundingBox = null;
  6804. this.boundingSphere = null;
  6805. this.drawRange = {
  6806. start: 0,
  6807. count: Infinity
  6808. };
  6809. this.userData = {};
  6810. }
  6811. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6812. constructor: BufferGeometry,
  6813. isBufferGeometry: true,
  6814. getIndex: function () {
  6815. return this.index;
  6816. },
  6817. setIndex: function (index) {
  6818. if (Array.isArray(index)) {
  6819. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6820. } else {
  6821. this.index = index;
  6822. }
  6823. },
  6824. getAttribute: function (name) {
  6825. return this.attributes[name];
  6826. },
  6827. setAttribute: function (name, attribute) {
  6828. this.attributes[name] = attribute;
  6829. return this;
  6830. },
  6831. deleteAttribute: function (name) {
  6832. delete this.attributes[name];
  6833. return this;
  6834. },
  6835. addGroup: function (start, count, materialIndex) {
  6836. this.groups.push({
  6837. start: start,
  6838. count: count,
  6839. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6840. });
  6841. },
  6842. clearGroups: function () {
  6843. this.groups = [];
  6844. },
  6845. setDrawRange: function (start, count) {
  6846. this.drawRange.start = start;
  6847. this.drawRange.count = count;
  6848. },
  6849. applyMatrix4: function (matrix) {
  6850. var position = this.attributes.position;
  6851. if (position !== undefined) {
  6852. position.applyMatrix4(matrix);
  6853. position.needsUpdate = true;
  6854. }
  6855. var normal = this.attributes.normal;
  6856. if (normal !== undefined) {
  6857. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6858. normal.applyNormalMatrix(normalMatrix);
  6859. normal.needsUpdate = true;
  6860. }
  6861. var tangent = this.attributes.tangent;
  6862. if (tangent !== undefined) {
  6863. tangent.transformDirection(matrix);
  6864. tangent.needsUpdate = true;
  6865. }
  6866. if (this.boundingBox !== null) {
  6867. this.computeBoundingBox();
  6868. }
  6869. if (this.boundingSphere !== null) {
  6870. this.computeBoundingSphere();
  6871. }
  6872. return this;
  6873. },
  6874. rotateX: function (angle) {
  6875. // rotate geometry around world x-axis
  6876. _m1$2.makeRotationX(angle);
  6877. this.applyMatrix4(_m1$2);
  6878. return this;
  6879. },
  6880. rotateY: function (angle) {
  6881. // rotate geometry around world y-axis
  6882. _m1$2.makeRotationY(angle);
  6883. this.applyMatrix4(_m1$2);
  6884. return this;
  6885. },
  6886. rotateZ: function (angle) {
  6887. // rotate geometry around world z-axis
  6888. _m1$2.makeRotationZ(angle);
  6889. this.applyMatrix4(_m1$2);
  6890. return this;
  6891. },
  6892. translate: function (x, y, z) {
  6893. // translate geometry
  6894. _m1$2.makeTranslation(x, y, z);
  6895. this.applyMatrix4(_m1$2);
  6896. return this;
  6897. },
  6898. scale: function (x, y, z) {
  6899. // scale geometry
  6900. _m1$2.makeScale(x, y, z);
  6901. this.applyMatrix4(_m1$2);
  6902. return this;
  6903. },
  6904. lookAt: function (vector) {
  6905. _obj.lookAt(vector);
  6906. _obj.updateMatrix();
  6907. this.applyMatrix4(_obj.matrix);
  6908. return this;
  6909. },
  6910. center: function () {
  6911. this.computeBoundingBox();
  6912. this.boundingBox.getCenter(_offset).negate();
  6913. this.translate(_offset.x, _offset.y, _offset.z);
  6914. return this;
  6915. },
  6916. setFromObject: function (object) {
  6917. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6918. var geometry = object.geometry;
  6919. if (object.isPoints || object.isLine) {
  6920. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6921. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6922. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6923. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  6924. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6925. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6926. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6927. }
  6928. if (geometry.boundingSphere !== null) {
  6929. this.boundingSphere = geometry.boundingSphere.clone();
  6930. }
  6931. if (geometry.boundingBox !== null) {
  6932. this.boundingBox = geometry.boundingBox.clone();
  6933. }
  6934. } else if (object.isMesh) {
  6935. if (geometry && geometry.isGeometry) {
  6936. this.fromGeometry(geometry);
  6937. }
  6938. }
  6939. return this;
  6940. },
  6941. setFromPoints: function (points) {
  6942. var position = [];
  6943. for (var i = 0, l = points.length; i < l; i++) {
  6944. var point = points[i];
  6945. position.push(point.x, point.y, point.z || 0);
  6946. }
  6947. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6948. return this;
  6949. },
  6950. updateFromObject: function (object) {
  6951. var geometry = object.geometry;
  6952. if (object.isMesh) {
  6953. var direct = geometry.__directGeometry;
  6954. if (geometry.elementsNeedUpdate === true) {
  6955. direct = undefined;
  6956. geometry.elementsNeedUpdate = false;
  6957. }
  6958. if (direct === undefined) {
  6959. return this.fromGeometry(geometry);
  6960. }
  6961. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6962. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6963. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6964. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6965. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6966. geometry.verticesNeedUpdate = false;
  6967. geometry.normalsNeedUpdate = false;
  6968. geometry.colorsNeedUpdate = false;
  6969. geometry.uvsNeedUpdate = false;
  6970. geometry.groupsNeedUpdate = false;
  6971. geometry = direct;
  6972. }
  6973. var attribute;
  6974. if (geometry.verticesNeedUpdate === true) {
  6975. attribute = this.attributes.position;
  6976. if (attribute !== undefined) {
  6977. attribute.copyVector3sArray(geometry.vertices);
  6978. attribute.needsUpdate = true;
  6979. }
  6980. geometry.verticesNeedUpdate = false;
  6981. }
  6982. if (geometry.normalsNeedUpdate === true) {
  6983. attribute = this.attributes.normal;
  6984. if (attribute !== undefined) {
  6985. attribute.copyVector3sArray(geometry.normals);
  6986. attribute.needsUpdate = true;
  6987. }
  6988. geometry.normalsNeedUpdate = false;
  6989. }
  6990. if (geometry.colorsNeedUpdate === true) {
  6991. attribute = this.attributes.color;
  6992. if (attribute !== undefined) {
  6993. attribute.copyColorsArray(geometry.colors);
  6994. attribute.needsUpdate = true;
  6995. }
  6996. geometry.colorsNeedUpdate = false;
  6997. }
  6998. if (geometry.uvsNeedUpdate) {
  6999. attribute = this.attributes.uv;
  7000. if (attribute !== undefined) {
  7001. attribute.copyVector2sArray(geometry.uvs);
  7002. attribute.needsUpdate = true;
  7003. }
  7004. geometry.uvsNeedUpdate = false;
  7005. }
  7006. if (geometry.lineDistancesNeedUpdate) {
  7007. attribute = this.attributes.lineDistance;
  7008. if (attribute !== undefined) {
  7009. attribute.copyArray(geometry.lineDistances);
  7010. attribute.needsUpdate = true;
  7011. }
  7012. geometry.lineDistancesNeedUpdate = false;
  7013. }
  7014. if (geometry.groupsNeedUpdate) {
  7015. geometry.computeGroups(object.geometry);
  7016. this.groups = geometry.groups;
  7017. geometry.groupsNeedUpdate = false;
  7018. }
  7019. return this;
  7020. },
  7021. fromGeometry: function (geometry) {
  7022. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7023. return this.fromDirectGeometry(geometry.__directGeometry);
  7024. },
  7025. fromDirectGeometry: function (geometry) {
  7026. var positions = new Float32Array(geometry.vertices.length * 3);
  7027. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7028. if (geometry.normals.length > 0) {
  7029. var normals = new Float32Array(geometry.normals.length * 3);
  7030. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7031. }
  7032. if (geometry.colors.length > 0) {
  7033. var colors = new Float32Array(geometry.colors.length * 3);
  7034. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7035. }
  7036. if (geometry.uvs.length > 0) {
  7037. var uvs = new Float32Array(geometry.uvs.length * 2);
  7038. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7039. }
  7040. if (geometry.uvs2.length > 0) {
  7041. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7042. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7043. } // groups
  7044. this.groups = geometry.groups; // morphs
  7045. for (var name in geometry.morphTargets) {
  7046. var array = [];
  7047. var morphTargets = geometry.morphTargets[name];
  7048. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7049. var morphTarget = morphTargets[i];
  7050. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7051. attribute.name = morphTarget.name;
  7052. array.push(attribute.copyVector3sArray(morphTarget.data));
  7053. }
  7054. this.morphAttributes[name] = array;
  7055. } // skinning
  7056. if (geometry.skinIndices.length > 0) {
  7057. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7058. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7059. }
  7060. if (geometry.skinWeights.length > 0) {
  7061. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7062. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7063. } //
  7064. if (geometry.boundingSphere !== null) {
  7065. this.boundingSphere = geometry.boundingSphere.clone();
  7066. }
  7067. if (geometry.boundingBox !== null) {
  7068. this.boundingBox = geometry.boundingBox.clone();
  7069. }
  7070. return this;
  7071. },
  7072. computeBoundingBox: function () {
  7073. if (this.boundingBox === null) {
  7074. this.boundingBox = new Box3();
  7075. }
  7076. var position = this.attributes.position;
  7077. var morphAttributesPosition = this.morphAttributes.position;
  7078. if (position !== undefined) {
  7079. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7080. if (morphAttributesPosition) {
  7081. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7082. var morphAttribute = morphAttributesPosition[i];
  7083. _box$2.setFromBufferAttribute(morphAttribute);
  7084. if (this.morphTargetsRelative) {
  7085. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  7086. this.boundingBox.expandByPoint(_vector$4);
  7087. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  7088. this.boundingBox.expandByPoint(_vector$4);
  7089. } else {
  7090. this.boundingBox.expandByPoint(_box$2.min);
  7091. this.boundingBox.expandByPoint(_box$2.max);
  7092. }
  7093. }
  7094. }
  7095. } else {
  7096. this.boundingBox.makeEmpty();
  7097. }
  7098. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7099. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7100. }
  7101. },
  7102. computeBoundingSphere: function () {
  7103. if (this.boundingSphere === null) {
  7104. this.boundingSphere = new Sphere();
  7105. }
  7106. var position = this.attributes.position;
  7107. var morphAttributesPosition = this.morphAttributes.position;
  7108. if (position) {
  7109. // first, find the center of the bounding sphere
  7110. var center = this.boundingSphere.center;
  7111. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  7112. if (morphAttributesPosition) {
  7113. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7114. var morphAttribute = morphAttributesPosition[i];
  7115. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7116. if (this.morphTargetsRelative) {
  7117. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  7118. _box$2.expandByPoint(_vector$4);
  7119. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  7120. _box$2.expandByPoint(_vector$4);
  7121. } else {
  7122. _box$2.expandByPoint(_boxMorphTargets.min);
  7123. _box$2.expandByPoint(_boxMorphTargets.max);
  7124. }
  7125. }
  7126. }
  7127. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7128. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7129. var maxRadiusSq = 0;
  7130. for (var i = 0, il = position.count; i < il; i++) {
  7131. _vector$4.fromBufferAttribute(position, i);
  7132. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7133. } // process morph attributes if present
  7134. if (morphAttributesPosition) {
  7135. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7136. var morphAttribute = morphAttributesPosition[i];
  7137. var morphTargetsRelative = this.morphTargetsRelative;
  7138. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7139. _vector$4.fromBufferAttribute(morphAttribute, j);
  7140. if (morphTargetsRelative) {
  7141. _offset.fromBufferAttribute(position, j);
  7142. _vector$4.add(_offset);
  7143. }
  7144. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7145. }
  7146. }
  7147. }
  7148. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7149. if (isNaN(this.boundingSphere.radius)) {
  7150. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7151. }
  7152. }
  7153. },
  7154. computeFaceNormals: function () {// backwards compatibility
  7155. },
  7156. computeVertexNormals: function () {
  7157. var index = this.index;
  7158. var attributes = this.attributes;
  7159. if (attributes.position) {
  7160. var positions = attributes.position.array;
  7161. if (attributes.normal === undefined) {
  7162. this.setAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  7163. } else {
  7164. // reset existing normals to zero
  7165. var array = attributes.normal.array;
  7166. for (var i = 0, il = array.length; i < il; i++) {
  7167. array[i] = 0;
  7168. }
  7169. }
  7170. var normals = attributes.normal.array;
  7171. var vA, vB, vC;
  7172. var pA = new Vector3(),
  7173. pB = new Vector3(),
  7174. pC = new Vector3();
  7175. var cb = new Vector3(),
  7176. ab = new Vector3(); // indexed elements
  7177. if (index) {
  7178. var indices = index.array;
  7179. for (var i = 0, il = index.count; i < il; i += 3) {
  7180. vA = indices[i + 0] * 3;
  7181. vB = indices[i + 1] * 3;
  7182. vC = indices[i + 2] * 3;
  7183. pA.fromArray(positions, vA);
  7184. pB.fromArray(positions, vB);
  7185. pC.fromArray(positions, vC);
  7186. cb.subVectors(pC, pB);
  7187. ab.subVectors(pA, pB);
  7188. cb.cross(ab);
  7189. normals[vA] += cb.x;
  7190. normals[vA + 1] += cb.y;
  7191. normals[vA + 2] += cb.z;
  7192. normals[vB] += cb.x;
  7193. normals[vB + 1] += cb.y;
  7194. normals[vB + 2] += cb.z;
  7195. normals[vC] += cb.x;
  7196. normals[vC + 1] += cb.y;
  7197. normals[vC + 2] += cb.z;
  7198. }
  7199. } else {
  7200. // non-indexed elements (unconnected triangle soup)
  7201. for (var i = 0, il = positions.length; i < il; i += 9) {
  7202. pA.fromArray(positions, i);
  7203. pB.fromArray(positions, i + 3);
  7204. pC.fromArray(positions, i + 6);
  7205. cb.subVectors(pC, pB);
  7206. ab.subVectors(pA, pB);
  7207. cb.cross(ab);
  7208. normals[i] = cb.x;
  7209. normals[i + 1] = cb.y;
  7210. normals[i + 2] = cb.z;
  7211. normals[i + 3] = cb.x;
  7212. normals[i + 4] = cb.y;
  7213. normals[i + 5] = cb.z;
  7214. normals[i + 6] = cb.x;
  7215. normals[i + 7] = cb.y;
  7216. normals[i + 8] = cb.z;
  7217. }
  7218. }
  7219. this.normalizeNormals();
  7220. attributes.normal.needsUpdate = true;
  7221. }
  7222. },
  7223. merge: function (geometry, offset) {
  7224. if (!(geometry && geometry.isBufferGeometry)) {
  7225. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  7226. return;
  7227. }
  7228. if (offset === undefined) {
  7229. offset = 0;
  7230. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  7231. }
  7232. var attributes = this.attributes;
  7233. for (var key in attributes) {
  7234. if (geometry.attributes[key] === undefined) continue;
  7235. var attribute1 = attributes[key];
  7236. var attributeArray1 = attribute1.array;
  7237. var attribute2 = geometry.attributes[key];
  7238. var attributeArray2 = attribute2.array;
  7239. var attributeOffset = attribute2.itemSize * offset;
  7240. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  7241. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  7242. attributeArray1[j] = attributeArray2[i];
  7243. }
  7244. }
  7245. return this;
  7246. },
  7247. normalizeNormals: function () {
  7248. var normals = this.attributes.normal;
  7249. for (var i = 0, il = normals.count; i < il; i++) {
  7250. _vector$4.x = normals.getX(i);
  7251. _vector$4.y = normals.getY(i);
  7252. _vector$4.z = normals.getZ(i);
  7253. _vector$4.normalize();
  7254. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7255. }
  7256. },
  7257. toNonIndexed: function () {
  7258. function convertBufferAttribute(attribute, indices) {
  7259. var array = attribute.array;
  7260. var itemSize = attribute.itemSize;
  7261. var array2 = new array.constructor(indices.length * itemSize);
  7262. var index = 0,
  7263. index2 = 0;
  7264. for (var i = 0, l = indices.length; i < l; i++) {
  7265. index = indices[i] * itemSize;
  7266. for (var j = 0; j < itemSize; j++) {
  7267. array2[index2++] = array[index++];
  7268. }
  7269. }
  7270. return new BufferAttribute(array2, itemSize);
  7271. } //
  7272. if (this.index === null) {
  7273. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7274. return this;
  7275. }
  7276. var geometry2 = new BufferGeometry();
  7277. var indices = this.index.array;
  7278. var attributes = this.attributes; // attributes
  7279. for (var name in attributes) {
  7280. var attribute = attributes[name];
  7281. var newAttribute = convertBufferAttribute(attribute, indices);
  7282. geometry2.setAttribute(name, newAttribute);
  7283. } // morph attributes
  7284. var morphAttributes = this.morphAttributes;
  7285. for (name in morphAttributes) {
  7286. var morphArray = [];
  7287. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7288. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  7289. var attribute = morphAttribute[i];
  7290. var newAttribute = convertBufferAttribute(attribute, indices);
  7291. morphArray.push(newAttribute);
  7292. }
  7293. geometry2.morphAttributes[name] = morphArray;
  7294. }
  7295. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  7296. var groups = this.groups;
  7297. for (var i = 0, l = groups.length; i < l; i++) {
  7298. var group = groups[i];
  7299. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7300. }
  7301. return geometry2;
  7302. },
  7303. toJSON: function () {
  7304. var data = {
  7305. metadata: {
  7306. version: 4.5,
  7307. type: 'BufferGeometry',
  7308. generator: 'BufferGeometry.toJSON'
  7309. }
  7310. }; // standard BufferGeometry serialization
  7311. data.uuid = this.uuid;
  7312. data.type = this.type;
  7313. if (this.name !== '') data.name = this.name;
  7314. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7315. if (this.parameters !== undefined) {
  7316. var parameters = this.parameters;
  7317. for (var key in parameters) {
  7318. if (parameters[key] !== undefined) data[key] = parameters[key];
  7319. }
  7320. return data;
  7321. }
  7322. data.data = {
  7323. attributes: {}
  7324. };
  7325. var index = this.index;
  7326. if (index !== null) {
  7327. data.data.index = {
  7328. type: index.array.constructor.name,
  7329. array: Array.prototype.slice.call(index.array)
  7330. };
  7331. }
  7332. var attributes = this.attributes;
  7333. for (var key in attributes) {
  7334. var attribute = attributes[key];
  7335. var attributeData = attribute.toJSON();
  7336. if (attribute.name !== '') attributeData.name = attribute.name;
  7337. data.data.attributes[key] = attributeData;
  7338. }
  7339. var morphAttributes = {};
  7340. var hasMorphAttributes = false;
  7341. for (var key in this.morphAttributes) {
  7342. var attributeArray = this.morphAttributes[key];
  7343. var array = [];
  7344. for (var i = 0, il = attributeArray.length; i < il; i++) {
  7345. var attribute = attributeArray[i];
  7346. var attributeData = attribute.toJSON();
  7347. if (attribute.name !== '') attributeData.name = attribute.name;
  7348. array.push(attributeData);
  7349. }
  7350. if (array.length > 0) {
  7351. morphAttributes[key] = array;
  7352. hasMorphAttributes = true;
  7353. }
  7354. }
  7355. if (hasMorphAttributes) {
  7356. data.data.morphAttributes = morphAttributes;
  7357. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7358. }
  7359. var groups = this.groups;
  7360. if (groups.length > 0) {
  7361. data.data.groups = JSON.parse(JSON.stringify(groups));
  7362. }
  7363. var boundingSphere = this.boundingSphere;
  7364. if (boundingSphere !== null) {
  7365. data.data.boundingSphere = {
  7366. center: boundingSphere.center.toArray(),
  7367. radius: boundingSphere.radius
  7368. };
  7369. }
  7370. return data;
  7371. },
  7372. clone: function () {
  7373. /*
  7374. // Handle primitives
  7375. var parameters = this.parameters;
  7376. if ( parameters !== undefined ) {
  7377. var values = [];
  7378. for ( var key in parameters ) {
  7379. values.push( parameters[ key ] );
  7380. }
  7381. var geometry = Object.create( this.constructor.prototype );
  7382. this.constructor.apply( geometry, values );
  7383. return geometry;
  7384. }
  7385. return new this.constructor().copy( this );
  7386. */
  7387. return new BufferGeometry().copy(this);
  7388. },
  7389. copy: function (source) {
  7390. var name, i, l; // reset
  7391. this.index = null;
  7392. this.attributes = {};
  7393. this.morphAttributes = {};
  7394. this.groups = [];
  7395. this.boundingBox = null;
  7396. this.boundingSphere = null; // name
  7397. this.name = source.name; // index
  7398. var index = source.index;
  7399. if (index !== null) {
  7400. this.setIndex(index.clone());
  7401. } // attributes
  7402. var attributes = source.attributes;
  7403. for (name in attributes) {
  7404. var attribute = attributes[name];
  7405. this.setAttribute(name, attribute.clone());
  7406. } // morph attributes
  7407. var morphAttributes = source.morphAttributes;
  7408. for (name in morphAttributes) {
  7409. var array = [];
  7410. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7411. for (i = 0, l = morphAttribute.length; i < l; i++) {
  7412. array.push(morphAttribute[i].clone());
  7413. }
  7414. this.morphAttributes[name] = array;
  7415. }
  7416. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  7417. var groups = source.groups;
  7418. for (i = 0, l = groups.length; i < l; i++) {
  7419. var group = groups[i];
  7420. this.addGroup(group.start, group.count, group.materialIndex);
  7421. } // bounding box
  7422. var boundingBox = source.boundingBox;
  7423. if (boundingBox !== null) {
  7424. this.boundingBox = boundingBox.clone();
  7425. } // bounding sphere
  7426. var boundingSphere = source.boundingSphere;
  7427. if (boundingSphere !== null) {
  7428. this.boundingSphere = boundingSphere.clone();
  7429. } // draw range
  7430. this.drawRange.start = source.drawRange.start;
  7431. this.drawRange.count = source.drawRange.count; // user data
  7432. this.userData = source.userData;
  7433. return this;
  7434. },
  7435. dispose: function () {
  7436. this.dispatchEvent({
  7437. type: 'dispose'
  7438. });
  7439. }
  7440. });
  7441. /**
  7442. * @author mrdoob / http://mrdoob.com/
  7443. * @author alteredq / http://alteredqualia.com/
  7444. * @author mikael emtinger / http://gomo.se/
  7445. * @author jonobr1 / http://jonobr1.com/
  7446. */
  7447. var _inverseMatrix = new Matrix4();
  7448. var _ray = new Ray();
  7449. var _sphere = new Sphere();
  7450. var _vA = new Vector3();
  7451. var _vB = new Vector3();
  7452. var _vC = new Vector3();
  7453. var _tempA = new Vector3();
  7454. var _tempB = new Vector3();
  7455. var _tempC = new Vector3();
  7456. var _morphA = new Vector3();
  7457. var _morphB = new Vector3();
  7458. var _morphC = new Vector3();
  7459. var _uvA = new Vector2();
  7460. var _uvB = new Vector2();
  7461. var _uvC = new Vector2();
  7462. var _intersectionPoint = new Vector3();
  7463. var _intersectionPointWorld = new Vector3();
  7464. function Mesh(geometry, material) {
  7465. Object3D.call(this);
  7466. this.type = 'Mesh';
  7467. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7468. this.material = material !== undefined ? material : new MeshBasicMaterial();
  7469. this.updateMorphTargets();
  7470. }
  7471. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7472. constructor: Mesh,
  7473. isMesh: true,
  7474. copy: function (source) {
  7475. Object3D.prototype.copy.call(this, source);
  7476. if (source.morphTargetInfluences !== undefined) {
  7477. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7478. }
  7479. if (source.morphTargetDictionary !== undefined) {
  7480. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7481. }
  7482. return this;
  7483. },
  7484. updateMorphTargets: function () {
  7485. var geometry = this.geometry;
  7486. var m, ml, name;
  7487. if (geometry.isBufferGeometry) {
  7488. var morphAttributes = geometry.morphAttributes;
  7489. var keys = Object.keys(morphAttributes);
  7490. if (keys.length > 0) {
  7491. var morphAttribute = morphAttributes[keys[0]];
  7492. if (morphAttribute !== undefined) {
  7493. this.morphTargetInfluences = [];
  7494. this.morphTargetDictionary = {};
  7495. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  7496. name = morphAttribute[m].name || String(m);
  7497. this.morphTargetInfluences.push(0);
  7498. this.morphTargetDictionary[name] = m;
  7499. }
  7500. }
  7501. }
  7502. } else {
  7503. var morphTargets = geometry.morphTargets;
  7504. if (morphTargets !== undefined && morphTargets.length > 0) {
  7505. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7506. }
  7507. }
  7508. },
  7509. raycast: function (raycaster, intersects) {
  7510. var geometry = this.geometry;
  7511. var material = this.material;
  7512. var matrixWorld = this.matrixWorld;
  7513. if (material === undefined) return; // Checking boundingSphere distance to ray
  7514. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7515. _sphere.copy(geometry.boundingSphere);
  7516. _sphere.applyMatrix4(matrixWorld);
  7517. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7518. _inverseMatrix.getInverse(matrixWorld);
  7519. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7520. if (geometry.boundingBox !== null) {
  7521. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7522. }
  7523. var intersection;
  7524. if (geometry.isBufferGeometry) {
  7525. var a, b, c;
  7526. var index = geometry.index;
  7527. var position = geometry.attributes.position;
  7528. var morphPosition = geometry.morphAttributes.position;
  7529. var morphTargetsRelative = geometry.morphTargetsRelative;
  7530. var uv = geometry.attributes.uv;
  7531. var uv2 = geometry.attributes.uv2;
  7532. var groups = geometry.groups;
  7533. var drawRange = geometry.drawRange;
  7534. var i, j, il, jl;
  7535. var group, groupMaterial;
  7536. var start, end;
  7537. if (index !== null) {
  7538. // indexed buffer geometry
  7539. if (Array.isArray(material)) {
  7540. for (i = 0, il = groups.length; i < il; i++) {
  7541. group = groups[i];
  7542. groupMaterial = material[group.materialIndex];
  7543. start = Math.max(group.start, drawRange.start);
  7544. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7545. for (j = start, jl = end; j < jl; j += 3) {
  7546. a = index.getX(j);
  7547. b = index.getX(j + 1);
  7548. c = index.getX(j + 2);
  7549. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7550. if (intersection) {
  7551. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7552. intersection.face.materialIndex = group.materialIndex;
  7553. intersects.push(intersection);
  7554. }
  7555. }
  7556. }
  7557. } else {
  7558. start = Math.max(0, drawRange.start);
  7559. end = Math.min(index.count, drawRange.start + drawRange.count);
  7560. for (i = start, il = end; i < il; i += 3) {
  7561. a = index.getX(i);
  7562. b = index.getX(i + 1);
  7563. c = index.getX(i + 2);
  7564. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7565. if (intersection) {
  7566. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7567. intersects.push(intersection);
  7568. }
  7569. }
  7570. }
  7571. } else if (position !== undefined) {
  7572. // non-indexed buffer geometry
  7573. if (Array.isArray(material)) {
  7574. for (i = 0, il = groups.length; i < il; i++) {
  7575. group = groups[i];
  7576. groupMaterial = material[group.materialIndex];
  7577. start = Math.max(group.start, drawRange.start);
  7578. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7579. for (j = start, jl = end; j < jl; j += 3) {
  7580. a = j;
  7581. b = j + 1;
  7582. c = j + 2;
  7583. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7584. if (intersection) {
  7585. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7586. intersection.face.materialIndex = group.materialIndex;
  7587. intersects.push(intersection);
  7588. }
  7589. }
  7590. }
  7591. } else {
  7592. start = Math.max(0, drawRange.start);
  7593. end = Math.min(position.count, drawRange.start + drawRange.count);
  7594. for (i = start, il = end; i < il; i += 3) {
  7595. a = i;
  7596. b = i + 1;
  7597. c = i + 2;
  7598. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7599. if (intersection) {
  7600. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7601. intersects.push(intersection);
  7602. }
  7603. }
  7604. }
  7605. }
  7606. } else if (geometry.isGeometry) {
  7607. var fvA, fvB, fvC;
  7608. var isMultiMaterial = Array.isArray(material);
  7609. var vertices = geometry.vertices;
  7610. var faces = geometry.faces;
  7611. var uvs;
  7612. var faceVertexUvs = geometry.faceVertexUvs[0];
  7613. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7614. for (var f = 0, fl = faces.length; f < fl; f++) {
  7615. var face = faces[f];
  7616. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7617. if (faceMaterial === undefined) continue;
  7618. fvA = vertices[face.a];
  7619. fvB = vertices[face.b];
  7620. fvC = vertices[face.c];
  7621. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7622. if (intersection) {
  7623. if (uvs && uvs[f]) {
  7624. var uvs_f = uvs[f];
  7625. _uvA.copy(uvs_f[0]);
  7626. _uvB.copy(uvs_f[1]);
  7627. _uvC.copy(uvs_f[2]);
  7628. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7629. }
  7630. intersection.face = face;
  7631. intersection.faceIndex = f;
  7632. intersects.push(intersection);
  7633. }
  7634. }
  7635. }
  7636. },
  7637. clone: function () {
  7638. return new this.constructor(this.geometry, this.material).copy(this);
  7639. }
  7640. });
  7641. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7642. var intersect;
  7643. if (material.side === BackSide) {
  7644. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7645. } else {
  7646. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7647. }
  7648. if (intersect === null) return null;
  7649. _intersectionPointWorld.copy(point);
  7650. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7651. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7652. if (distance < raycaster.near || distance > raycaster.far) return null;
  7653. return {
  7654. distance: distance,
  7655. point: _intersectionPointWorld.clone(),
  7656. object: object
  7657. };
  7658. }
  7659. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  7660. _vA.fromBufferAttribute(position, a);
  7661. _vB.fromBufferAttribute(position, b);
  7662. _vC.fromBufferAttribute(position, c);
  7663. var morphInfluences = object.morphTargetInfluences;
  7664. if (material.morphTargets && morphPosition && morphInfluences) {
  7665. _morphA.set(0, 0, 0);
  7666. _morphB.set(0, 0, 0);
  7667. _morphC.set(0, 0, 0);
  7668. for (var i = 0, il = morphPosition.length; i < il; i++) {
  7669. var influence = morphInfluences[i];
  7670. var morphAttribute = morphPosition[i];
  7671. if (influence === 0) continue;
  7672. _tempA.fromBufferAttribute(morphAttribute, a);
  7673. _tempB.fromBufferAttribute(morphAttribute, b);
  7674. _tempC.fromBufferAttribute(morphAttribute, c);
  7675. if (morphTargetsRelative) {
  7676. _morphA.addScaledVector(_tempA, influence);
  7677. _morphB.addScaledVector(_tempB, influence);
  7678. _morphC.addScaledVector(_tempC, influence);
  7679. } else {
  7680. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7681. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7682. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7683. }
  7684. }
  7685. _vA.add(_morphA);
  7686. _vB.add(_morphB);
  7687. _vC.add(_morphC);
  7688. }
  7689. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7690. if (intersection) {
  7691. if (uv) {
  7692. _uvA.fromBufferAttribute(uv, a);
  7693. _uvB.fromBufferAttribute(uv, b);
  7694. _uvC.fromBufferAttribute(uv, c);
  7695. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7696. }
  7697. if (uv2) {
  7698. _uvA.fromBufferAttribute(uv2, a);
  7699. _uvB.fromBufferAttribute(uv2, b);
  7700. _uvC.fromBufferAttribute(uv2, c);
  7701. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7702. }
  7703. var face = new Face3(a, b, c);
  7704. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7705. intersection.face = face;
  7706. }
  7707. return intersection;
  7708. }
  7709. /**
  7710. * @author mrdoob / http://mrdoob.com/
  7711. * @author kile / http://kile.stravaganza.org/
  7712. * @author alteredq / http://alteredqualia.com/
  7713. * @author mikael emtinger / http://gomo.se/
  7714. * @author zz85 / http://www.lab4games.net/zz85/blog
  7715. * @author bhouston / http://clara.io
  7716. */
  7717. var _geometryId = 0; // Geometry uses even numbers as Id
  7718. var _m1$3 = new Matrix4();
  7719. var _obj$1 = new Object3D();
  7720. var _offset$1 = new Vector3();
  7721. function Geometry() {
  7722. Object.defineProperty(this, 'id', {
  7723. value: _geometryId += 2
  7724. });
  7725. this.uuid = MathUtils.generateUUID();
  7726. this.name = '';
  7727. this.type = 'Geometry';
  7728. this.vertices = [];
  7729. this.colors = [];
  7730. this.faces = [];
  7731. this.faceVertexUvs = [[]];
  7732. this.morphTargets = [];
  7733. this.morphNormals = [];
  7734. this.skinWeights = [];
  7735. this.skinIndices = [];
  7736. this.lineDistances = [];
  7737. this.boundingBox = null;
  7738. this.boundingSphere = null; // update flags
  7739. this.elementsNeedUpdate = false;
  7740. this.verticesNeedUpdate = false;
  7741. this.uvsNeedUpdate = false;
  7742. this.normalsNeedUpdate = false;
  7743. this.colorsNeedUpdate = false;
  7744. this.lineDistancesNeedUpdate = false;
  7745. this.groupsNeedUpdate = false;
  7746. }
  7747. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7748. constructor: Geometry,
  7749. isGeometry: true,
  7750. applyMatrix4: function (matrix) {
  7751. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7752. for (var i = 0, il = this.vertices.length; i < il; i++) {
  7753. var vertex = this.vertices[i];
  7754. vertex.applyMatrix4(matrix);
  7755. }
  7756. for (var i = 0, il = this.faces.length; i < il; i++) {
  7757. var face = this.faces[i];
  7758. face.normal.applyMatrix3(normalMatrix).normalize();
  7759. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  7760. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  7761. }
  7762. }
  7763. if (this.boundingBox !== null) {
  7764. this.computeBoundingBox();
  7765. }
  7766. if (this.boundingSphere !== null) {
  7767. this.computeBoundingSphere();
  7768. }
  7769. this.verticesNeedUpdate = true;
  7770. this.normalsNeedUpdate = true;
  7771. return this;
  7772. },
  7773. rotateX: function (angle) {
  7774. // rotate geometry around world x-axis
  7775. _m1$3.makeRotationX(angle);
  7776. this.applyMatrix4(_m1$3);
  7777. return this;
  7778. },
  7779. rotateY: function (angle) {
  7780. // rotate geometry around world y-axis
  7781. _m1$3.makeRotationY(angle);
  7782. this.applyMatrix4(_m1$3);
  7783. return this;
  7784. },
  7785. rotateZ: function (angle) {
  7786. // rotate geometry around world z-axis
  7787. _m1$3.makeRotationZ(angle);
  7788. this.applyMatrix4(_m1$3);
  7789. return this;
  7790. },
  7791. translate: function (x, y, z) {
  7792. // translate geometry
  7793. _m1$3.makeTranslation(x, y, z);
  7794. this.applyMatrix4(_m1$3);
  7795. return this;
  7796. },
  7797. scale: function (x, y, z) {
  7798. // scale geometry
  7799. _m1$3.makeScale(x, y, z);
  7800. this.applyMatrix4(_m1$3);
  7801. return this;
  7802. },
  7803. lookAt: function (vector) {
  7804. _obj$1.lookAt(vector);
  7805. _obj$1.updateMatrix();
  7806. this.applyMatrix4(_obj$1.matrix);
  7807. return this;
  7808. },
  7809. fromBufferGeometry: function (geometry) {
  7810. var scope = this;
  7811. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7812. var attributes = geometry.attributes;
  7813. if (attributes.position === undefined) {
  7814. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  7815. return this;
  7816. }
  7817. var positions = attributes.position.array;
  7818. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7819. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7820. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7821. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7822. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  7823. for (var i = 0; i < positions.length; i += 3) {
  7824. scope.vertices.push(new Vector3().fromArray(positions, i));
  7825. if (colors !== undefined) {
  7826. scope.colors.push(new Color().fromArray(colors, i));
  7827. }
  7828. }
  7829. function addFace(a, b, c, materialIndex) {
  7830. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  7831. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  7832. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  7833. scope.faces.push(face);
  7834. if (uvs !== undefined) {
  7835. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  7836. }
  7837. if (uvs2 !== undefined) {
  7838. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  7839. }
  7840. }
  7841. var groups = geometry.groups;
  7842. if (groups.length > 0) {
  7843. for (var i = 0; i < groups.length; i++) {
  7844. var group = groups[i];
  7845. var start = group.start;
  7846. var count = group.count;
  7847. for (var j = start, jl = start + count; j < jl; j += 3) {
  7848. if (indices !== undefined) {
  7849. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  7850. } else {
  7851. addFace(j, j + 1, j + 2, group.materialIndex);
  7852. }
  7853. }
  7854. }
  7855. } else {
  7856. if (indices !== undefined) {
  7857. for (var i = 0; i < indices.length; i += 3) {
  7858. addFace(indices[i], indices[i + 1], indices[i + 2]);
  7859. }
  7860. } else {
  7861. for (var i = 0; i < positions.length / 3; i += 3) {
  7862. addFace(i, i + 1, i + 2);
  7863. }
  7864. }
  7865. }
  7866. this.computeFaceNormals();
  7867. if (geometry.boundingBox !== null) {
  7868. this.boundingBox = geometry.boundingBox.clone();
  7869. }
  7870. if (geometry.boundingSphere !== null) {
  7871. this.boundingSphere = geometry.boundingSphere.clone();
  7872. }
  7873. return this;
  7874. },
  7875. center: function () {
  7876. this.computeBoundingBox();
  7877. this.boundingBox.getCenter(_offset$1).negate();
  7878. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  7879. return this;
  7880. },
  7881. normalize: function () {
  7882. this.computeBoundingSphere();
  7883. var center = this.boundingSphere.center;
  7884. var radius = this.boundingSphere.radius;
  7885. var s = radius === 0 ? 1 : 1.0 / radius;
  7886. var matrix = new Matrix4();
  7887. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  7888. this.applyMatrix4(matrix);
  7889. return this;
  7890. },
  7891. computeFaceNormals: function () {
  7892. var cb = new Vector3(),
  7893. ab = new Vector3();
  7894. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  7895. var face = this.faces[f];
  7896. var vA = this.vertices[face.a];
  7897. var vB = this.vertices[face.b];
  7898. var vC = this.vertices[face.c];
  7899. cb.subVectors(vC, vB);
  7900. ab.subVectors(vA, vB);
  7901. cb.cross(ab);
  7902. cb.normalize();
  7903. face.normal.copy(cb);
  7904. }
  7905. },
  7906. computeVertexNormals: function (areaWeighted) {
  7907. if (areaWeighted === undefined) areaWeighted = true;
  7908. var v, vl, f, fl, face, vertices;
  7909. vertices = new Array(this.vertices.length);
  7910. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7911. vertices[v] = new Vector3();
  7912. }
  7913. if (areaWeighted) {
  7914. // vertex normals weighted by triangle areas
  7915. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7916. var vA, vB, vC;
  7917. var cb = new Vector3(),
  7918. ab = new Vector3();
  7919. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7920. face = this.faces[f];
  7921. vA = this.vertices[face.a];
  7922. vB = this.vertices[face.b];
  7923. vC = this.vertices[face.c];
  7924. cb.subVectors(vC, vB);
  7925. ab.subVectors(vA, vB);
  7926. cb.cross(ab);
  7927. vertices[face.a].add(cb);
  7928. vertices[face.b].add(cb);
  7929. vertices[face.c].add(cb);
  7930. }
  7931. } else {
  7932. this.computeFaceNormals();
  7933. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7934. face = this.faces[f];
  7935. vertices[face.a].add(face.normal);
  7936. vertices[face.b].add(face.normal);
  7937. vertices[face.c].add(face.normal);
  7938. }
  7939. }
  7940. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7941. vertices[v].normalize();
  7942. }
  7943. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7944. face = this.faces[f];
  7945. var vertexNormals = face.vertexNormals;
  7946. if (vertexNormals.length === 3) {
  7947. vertexNormals[0].copy(vertices[face.a]);
  7948. vertexNormals[1].copy(vertices[face.b]);
  7949. vertexNormals[2].copy(vertices[face.c]);
  7950. } else {
  7951. vertexNormals[0] = vertices[face.a].clone();
  7952. vertexNormals[1] = vertices[face.b].clone();
  7953. vertexNormals[2] = vertices[face.c].clone();
  7954. }
  7955. }
  7956. if (this.faces.length > 0) {
  7957. this.normalsNeedUpdate = true;
  7958. }
  7959. },
  7960. computeFlatVertexNormals: function () {
  7961. var f, fl, face;
  7962. this.computeFaceNormals();
  7963. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7964. face = this.faces[f];
  7965. var vertexNormals = face.vertexNormals;
  7966. if (vertexNormals.length === 3) {
  7967. vertexNormals[0].copy(face.normal);
  7968. vertexNormals[1].copy(face.normal);
  7969. vertexNormals[2].copy(face.normal);
  7970. } else {
  7971. vertexNormals[0] = face.normal.clone();
  7972. vertexNormals[1] = face.normal.clone();
  7973. vertexNormals[2] = face.normal.clone();
  7974. }
  7975. }
  7976. if (this.faces.length > 0) {
  7977. this.normalsNeedUpdate = true;
  7978. }
  7979. },
  7980. computeMorphNormals: function () {
  7981. var i, il, f, fl, face; // save original normals
  7982. // - create temp variables on first access
  7983. // otherwise just copy (for faster repeated calls)
  7984. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7985. face = this.faces[f];
  7986. if (!face.__originalFaceNormal) {
  7987. face.__originalFaceNormal = face.normal.clone();
  7988. } else {
  7989. face.__originalFaceNormal.copy(face.normal);
  7990. }
  7991. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  7992. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  7993. if (!face.__originalVertexNormals[i]) {
  7994. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  7995. } else {
  7996. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  7997. }
  7998. }
  7999. } // use temp geometry to compute face and vertex normals for each morph
  8000. var tmpGeo = new Geometry();
  8001. tmpGeo.faces = this.faces;
  8002. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8003. // create on first access
  8004. if (!this.morphNormals[i]) {
  8005. this.morphNormals[i] = {};
  8006. this.morphNormals[i].faceNormals = [];
  8007. this.morphNormals[i].vertexNormals = [];
  8008. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8009. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8010. var faceNormal, vertexNormals;
  8011. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8012. faceNormal = new Vector3();
  8013. vertexNormals = {
  8014. a: new Vector3(),
  8015. b: new Vector3(),
  8016. c: new Vector3()
  8017. };
  8018. dstNormalsFace.push(faceNormal);
  8019. dstNormalsVertex.push(vertexNormals);
  8020. }
  8021. }
  8022. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8023. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8024. tmpGeo.computeFaceNormals();
  8025. tmpGeo.computeVertexNormals(); // store morph normals
  8026. var faceNormal, vertexNormals;
  8027. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8028. face = this.faces[f];
  8029. faceNormal = morphNormals.faceNormals[f];
  8030. vertexNormals = morphNormals.vertexNormals[f];
  8031. faceNormal.copy(face.normal);
  8032. vertexNormals.a.copy(face.vertexNormals[0]);
  8033. vertexNormals.b.copy(face.vertexNormals[1]);
  8034. vertexNormals.c.copy(face.vertexNormals[2]);
  8035. }
  8036. } // restore original normals
  8037. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8038. face = this.faces[f];
  8039. face.normal = face.__originalFaceNormal;
  8040. face.vertexNormals = face.__originalVertexNormals;
  8041. }
  8042. },
  8043. computeBoundingBox: function () {
  8044. if (this.boundingBox === null) {
  8045. this.boundingBox = new Box3();
  8046. }
  8047. this.boundingBox.setFromPoints(this.vertices);
  8048. },
  8049. computeBoundingSphere: function () {
  8050. if (this.boundingSphere === null) {
  8051. this.boundingSphere = new Sphere();
  8052. }
  8053. this.boundingSphere.setFromPoints(this.vertices);
  8054. },
  8055. merge: function (geometry, matrix, materialIndexOffset) {
  8056. if (!(geometry && geometry.isGeometry)) {
  8057. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8058. return;
  8059. }
  8060. var normalMatrix,
  8061. vertexOffset = this.vertices.length,
  8062. vertices1 = this.vertices,
  8063. vertices2 = geometry.vertices,
  8064. faces1 = this.faces,
  8065. faces2 = geometry.faces,
  8066. colors1 = this.colors,
  8067. colors2 = geometry.colors;
  8068. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8069. if (matrix !== undefined) {
  8070. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8071. } // vertices
  8072. for (var i = 0, il = vertices2.length; i < il; i++) {
  8073. var vertex = vertices2[i];
  8074. var vertexCopy = vertex.clone();
  8075. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8076. vertices1.push(vertexCopy);
  8077. } // colors
  8078. for (var i = 0, il = colors2.length; i < il; i++) {
  8079. colors1.push(colors2[i].clone());
  8080. } // faces
  8081. for (i = 0, il = faces2.length; i < il; i++) {
  8082. var face = faces2[i],
  8083. faceCopy,
  8084. normal,
  8085. color,
  8086. faceVertexNormals = face.vertexNormals,
  8087. faceVertexColors = face.vertexColors;
  8088. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8089. faceCopy.normal.copy(face.normal);
  8090. if (normalMatrix !== undefined) {
  8091. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8092. }
  8093. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8094. normal = faceVertexNormals[j].clone();
  8095. if (normalMatrix !== undefined) {
  8096. normal.applyMatrix3(normalMatrix).normalize();
  8097. }
  8098. faceCopy.vertexNormals.push(normal);
  8099. }
  8100. faceCopy.color.copy(face.color);
  8101. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8102. color = faceVertexColors[j];
  8103. faceCopy.vertexColors.push(color.clone());
  8104. }
  8105. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8106. faces1.push(faceCopy);
  8107. } // uvs
  8108. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8109. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8110. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8111. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8112. var uvs2 = faceVertexUvs2[j],
  8113. uvsCopy = [];
  8114. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8115. uvsCopy.push(uvs2[k].clone());
  8116. }
  8117. this.faceVertexUvs[i].push(uvsCopy);
  8118. }
  8119. }
  8120. },
  8121. mergeMesh: function (mesh) {
  8122. if (!(mesh && mesh.isMesh)) {
  8123. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8124. return;
  8125. }
  8126. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8127. this.merge(mesh.geometry, mesh.matrix);
  8128. },
  8129. /*
  8130. * Checks for duplicate vertices with hashmap.
  8131. * Duplicated vertices are removed
  8132. * and faces' vertices are updated.
  8133. */
  8134. mergeVertices: function () {
  8135. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8136. var unique = [],
  8137. changes = [];
  8138. var v, key;
  8139. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8140. var precision = Math.pow(10, precisionPoints);
  8141. var i, il, face;
  8142. var indices, j, jl;
  8143. for (i = 0, il = this.vertices.length; i < il; i++) {
  8144. v = this.vertices[i];
  8145. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8146. if (verticesMap[key] === undefined) {
  8147. verticesMap[key] = i;
  8148. unique.push(this.vertices[i]);
  8149. changes[i] = unique.length - 1;
  8150. } else {
  8151. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8152. changes[i] = changes[verticesMap[key]];
  8153. }
  8154. } // if faces are completely degenerate after merging vertices, we
  8155. // have to remove them from the geometry.
  8156. var faceIndicesToRemove = [];
  8157. for (i = 0, il = this.faces.length; i < il; i++) {
  8158. face = this.faces[i];
  8159. face.a = changes[face.a];
  8160. face.b = changes[face.b];
  8161. face.c = changes[face.c];
  8162. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8163. // we have to remove the face as nothing can be saved
  8164. for (var n = 0; n < 3; n++) {
  8165. if (indices[n] === indices[(n + 1) % 3]) {
  8166. faceIndicesToRemove.push(i);
  8167. break;
  8168. }
  8169. }
  8170. }
  8171. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  8172. var idx = faceIndicesToRemove[i];
  8173. this.faces.splice(idx, 1);
  8174. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  8175. this.faceVertexUvs[j].splice(idx, 1);
  8176. }
  8177. } // Use unique set of vertices
  8178. var diff = this.vertices.length - unique.length;
  8179. this.vertices = unique;
  8180. return diff;
  8181. },
  8182. setFromPoints: function (points) {
  8183. this.vertices = [];
  8184. for (var i = 0, l = points.length; i < l; i++) {
  8185. var point = points[i];
  8186. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  8187. }
  8188. return this;
  8189. },
  8190. sortFacesByMaterialIndex: function () {
  8191. var faces = this.faces;
  8192. var length = faces.length; // tag faces
  8193. for (var i = 0; i < length; i++) {
  8194. faces[i]._id = i;
  8195. } // sort faces
  8196. function materialIndexSort(a, b) {
  8197. return a.materialIndex - b.materialIndex;
  8198. }
  8199. faces.sort(materialIndexSort); // sort uvs
  8200. var uvs1 = this.faceVertexUvs[0];
  8201. var uvs2 = this.faceVertexUvs[1];
  8202. var newUvs1, newUvs2;
  8203. if (uvs1 && uvs1.length === length) newUvs1 = [];
  8204. if (uvs2 && uvs2.length === length) newUvs2 = [];
  8205. for (var i = 0; i < length; i++) {
  8206. var id = faces[i]._id;
  8207. if (newUvs1) newUvs1.push(uvs1[id]);
  8208. if (newUvs2) newUvs2.push(uvs2[id]);
  8209. }
  8210. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  8211. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  8212. },
  8213. toJSON: function () {
  8214. var data = {
  8215. metadata: {
  8216. version: 4.5,
  8217. type: 'Geometry',
  8218. generator: 'Geometry.toJSON'
  8219. }
  8220. }; // standard Geometry serialization
  8221. data.uuid = this.uuid;
  8222. data.type = this.type;
  8223. if (this.name !== '') data.name = this.name;
  8224. if (this.parameters !== undefined) {
  8225. var parameters = this.parameters;
  8226. for (var key in parameters) {
  8227. if (parameters[key] !== undefined) data[key] = parameters[key];
  8228. }
  8229. return data;
  8230. }
  8231. var vertices = [];
  8232. for (var i = 0; i < this.vertices.length; i++) {
  8233. var vertex = this.vertices[i];
  8234. vertices.push(vertex.x, vertex.y, vertex.z);
  8235. }
  8236. var faces = [];
  8237. var normals = [];
  8238. var normalsHash = {};
  8239. var colors = [];
  8240. var colorsHash = {};
  8241. var uvs = [];
  8242. var uvsHash = {};
  8243. for (var i = 0; i < this.faces.length; i++) {
  8244. var face = this.faces[i];
  8245. var hasMaterial = true;
  8246. var hasFaceUv = false; // deprecated
  8247. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  8248. var hasFaceNormal = face.normal.length() > 0;
  8249. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8250. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8251. var hasFaceVertexColor = face.vertexColors.length > 0;
  8252. var faceType = 0;
  8253. faceType = setBit(faceType, 0, 0); // isQuad
  8254. faceType = setBit(faceType, 1, hasMaterial);
  8255. faceType = setBit(faceType, 2, hasFaceUv);
  8256. faceType = setBit(faceType, 3, hasFaceVertexUv);
  8257. faceType = setBit(faceType, 4, hasFaceNormal);
  8258. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  8259. faceType = setBit(faceType, 6, hasFaceColor);
  8260. faceType = setBit(faceType, 7, hasFaceVertexColor);
  8261. faces.push(faceType);
  8262. faces.push(face.a, face.b, face.c);
  8263. faces.push(face.materialIndex);
  8264. if (hasFaceVertexUv) {
  8265. var faceVertexUvs = this.faceVertexUvs[0][i];
  8266. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  8267. }
  8268. if (hasFaceNormal) {
  8269. faces.push(getNormalIndex(face.normal));
  8270. }
  8271. if (hasFaceVertexNormal) {
  8272. var vertexNormals = face.vertexNormals;
  8273. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  8274. }
  8275. if (hasFaceColor) {
  8276. faces.push(getColorIndex(face.color));
  8277. }
  8278. if (hasFaceVertexColor) {
  8279. var vertexColors = face.vertexColors;
  8280. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  8281. }
  8282. }
  8283. function setBit(value, position, enabled) {
  8284. return enabled ? value | 1 << position : value & ~(1 << position);
  8285. }
  8286. function getNormalIndex(normal) {
  8287. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8288. if (normalsHash[hash] !== undefined) {
  8289. return normalsHash[hash];
  8290. }
  8291. normalsHash[hash] = normals.length / 3;
  8292. normals.push(normal.x, normal.y, normal.z);
  8293. return normalsHash[hash];
  8294. }
  8295. function getColorIndex(color) {
  8296. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8297. if (colorsHash[hash] !== undefined) {
  8298. return colorsHash[hash];
  8299. }
  8300. colorsHash[hash] = colors.length;
  8301. colors.push(color.getHex());
  8302. return colorsHash[hash];
  8303. }
  8304. function getUvIndex(uv) {
  8305. var hash = uv.x.toString() + uv.y.toString();
  8306. if (uvsHash[hash] !== undefined) {
  8307. return uvsHash[hash];
  8308. }
  8309. uvsHash[hash] = uvs.length / 2;
  8310. uvs.push(uv.x, uv.y);
  8311. return uvsHash[hash];
  8312. }
  8313. data.data = {};
  8314. data.data.vertices = vertices;
  8315. data.data.normals = normals;
  8316. if (colors.length > 0) data.data.colors = colors;
  8317. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  8318. data.data.faces = faces;
  8319. return data;
  8320. },
  8321. clone: function () {
  8322. /*
  8323. // Handle primitives
  8324. var parameters = this.parameters;
  8325. if ( parameters !== undefined ) {
  8326. var values = [];
  8327. for ( var key in parameters ) {
  8328. values.push( parameters[ key ] );
  8329. }
  8330. var geometry = Object.create( this.constructor.prototype );
  8331. this.constructor.apply( geometry, values );
  8332. return geometry;
  8333. }
  8334. return new this.constructor().copy( this );
  8335. */
  8336. return new Geometry().copy(this);
  8337. },
  8338. copy: function (source) {
  8339. var i, il, j, jl, k, kl; // reset
  8340. this.vertices = [];
  8341. this.colors = [];
  8342. this.faces = [];
  8343. this.faceVertexUvs = [[]];
  8344. this.morphTargets = [];
  8345. this.morphNormals = [];
  8346. this.skinWeights = [];
  8347. this.skinIndices = [];
  8348. this.lineDistances = [];
  8349. this.boundingBox = null;
  8350. this.boundingSphere = null; // name
  8351. this.name = source.name; // vertices
  8352. var vertices = source.vertices;
  8353. for (i = 0, il = vertices.length; i < il; i++) {
  8354. this.vertices.push(vertices[i].clone());
  8355. } // colors
  8356. var colors = source.colors;
  8357. for (i = 0, il = colors.length; i < il; i++) {
  8358. this.colors.push(colors[i].clone());
  8359. } // faces
  8360. var faces = source.faces;
  8361. for (i = 0, il = faces.length; i < il; i++) {
  8362. this.faces.push(faces[i].clone());
  8363. } // face vertex uvs
  8364. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  8365. var faceVertexUvs = source.faceVertexUvs[i];
  8366. if (this.faceVertexUvs[i] === undefined) {
  8367. this.faceVertexUvs[i] = [];
  8368. }
  8369. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  8370. var uvs = faceVertexUvs[j],
  8371. uvsCopy = [];
  8372. for (k = 0, kl = uvs.length; k < kl; k++) {
  8373. var uv = uvs[k];
  8374. uvsCopy.push(uv.clone());
  8375. }
  8376. this.faceVertexUvs[i].push(uvsCopy);
  8377. }
  8378. } // morph targets
  8379. var morphTargets = source.morphTargets;
  8380. for (i = 0, il = morphTargets.length; i < il; i++) {
  8381. var morphTarget = {};
  8382. morphTarget.name = morphTargets[i].name; // vertices
  8383. if (morphTargets[i].vertices !== undefined) {
  8384. morphTarget.vertices = [];
  8385. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  8386. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  8387. }
  8388. } // normals
  8389. if (morphTargets[i].normals !== undefined) {
  8390. morphTarget.normals = [];
  8391. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  8392. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  8393. }
  8394. }
  8395. this.morphTargets.push(morphTarget);
  8396. } // morph normals
  8397. var morphNormals = source.morphNormals;
  8398. for (i = 0, il = morphNormals.length; i < il; i++) {
  8399. var morphNormal = {}; // vertex normals
  8400. if (morphNormals[i].vertexNormals !== undefined) {
  8401. morphNormal.vertexNormals = [];
  8402. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  8403. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  8404. var destVertexNormal = {};
  8405. destVertexNormal.a = srcVertexNormal.a.clone();
  8406. destVertexNormal.b = srcVertexNormal.b.clone();
  8407. destVertexNormal.c = srcVertexNormal.c.clone();
  8408. morphNormal.vertexNormals.push(destVertexNormal);
  8409. }
  8410. } // face normals
  8411. if (morphNormals[i].faceNormals !== undefined) {
  8412. morphNormal.faceNormals = [];
  8413. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  8414. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  8415. }
  8416. }
  8417. this.morphNormals.push(morphNormal);
  8418. } // skin weights
  8419. var skinWeights = source.skinWeights;
  8420. for (i = 0, il = skinWeights.length; i < il; i++) {
  8421. this.skinWeights.push(skinWeights[i].clone());
  8422. } // skin indices
  8423. var skinIndices = source.skinIndices;
  8424. for (i = 0, il = skinIndices.length; i < il; i++) {
  8425. this.skinIndices.push(skinIndices[i].clone());
  8426. } // line distances
  8427. var lineDistances = source.lineDistances;
  8428. for (i = 0, il = lineDistances.length; i < il; i++) {
  8429. this.lineDistances.push(lineDistances[i]);
  8430. } // bounding box
  8431. var boundingBox = source.boundingBox;
  8432. if (boundingBox !== null) {
  8433. this.boundingBox = boundingBox.clone();
  8434. } // bounding sphere
  8435. var boundingSphere = source.boundingSphere;
  8436. if (boundingSphere !== null) {
  8437. this.boundingSphere = boundingSphere.clone();
  8438. } // update flags
  8439. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8440. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8441. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8442. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8443. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8444. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8445. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8446. return this;
  8447. },
  8448. dispose: function () {
  8449. this.dispatchEvent({
  8450. type: 'dispose'
  8451. });
  8452. }
  8453. });
  8454. /**
  8455. * @author mrdoob / http://mrdoob.com/
  8456. * @author Mugen87 / https://github.com/Mugen87
  8457. */
  8458. // BoxGeometry
  8459. class BoxGeometry extends Geometry {
  8460. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8461. super();
  8462. this.type = 'BoxGeometry';
  8463. this.parameters = {
  8464. width: width,
  8465. height: height,
  8466. depth: depth,
  8467. widthSegments: widthSegments,
  8468. heightSegments: heightSegments,
  8469. depthSegments: depthSegments
  8470. };
  8471. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  8472. this.mergeVertices();
  8473. }
  8474. } // BoxBufferGeometry
  8475. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  8476. class BoxBufferGeometry extends BufferGeometry {
  8477. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8478. super();
  8479. this.type = 'BoxBufferGeometry';
  8480. this.parameters = {
  8481. width: width,
  8482. height: height,
  8483. depth: depth,
  8484. widthSegments: widthSegments,
  8485. heightSegments: heightSegments,
  8486. depthSegments: depthSegments
  8487. };
  8488. var scope = this;
  8489. width = width || 1;
  8490. height = height || 1;
  8491. depth = depth || 1; // segments
  8492. widthSegments = Math.floor(widthSegments) || 1;
  8493. heightSegments = Math.floor(heightSegments) || 1;
  8494. depthSegments = Math.floor(depthSegments) || 1; // buffers
  8495. var indices = [];
  8496. var vertices = [];
  8497. var normals = [];
  8498. var uvs = []; // helper variables
  8499. var numberOfVertices = 0;
  8500. var groupStart = 0; // build each side of the box geometry
  8501. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  8502. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  8503. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  8504. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  8505. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  8506. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  8507. // build geometry
  8508. this.setIndex(indices);
  8509. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8510. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8511. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8512. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  8513. var segmentWidth = width / gridX;
  8514. var segmentHeight = height / gridY;
  8515. var widthHalf = width / 2;
  8516. var heightHalf = height / 2;
  8517. var depthHalf = depth / 2;
  8518. var gridX1 = gridX + 1;
  8519. var gridY1 = gridY + 1;
  8520. var vertexCounter = 0;
  8521. var groupCount = 0;
  8522. var ix, iy;
  8523. var vector = new Vector3(); // generate vertices, normals and uvs
  8524. for (iy = 0; iy < gridY1; iy++) {
  8525. var y = iy * segmentHeight - heightHalf;
  8526. for (ix = 0; ix < gridX1; ix++) {
  8527. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  8528. vector[u] = x * udir;
  8529. vector[v] = y * vdir;
  8530. vector[w] = depthHalf; // now apply vector to vertex buffer
  8531. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  8532. vector[u] = 0;
  8533. vector[v] = 0;
  8534. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  8535. normals.push(vector.x, vector.y, vector.z); // uvs
  8536. uvs.push(ix / gridX);
  8537. uvs.push(1 - iy / gridY); // counters
  8538. vertexCounter += 1;
  8539. }
  8540. } // indices
  8541. // 1. you need three indices to draw a single face
  8542. // 2. a single segment consists of two faces
  8543. // 3. so we need to generate six (2*3) indices per segment
  8544. for (iy = 0; iy < gridY; iy++) {
  8545. for (ix = 0; ix < gridX; ix++) {
  8546. var a = numberOfVertices + ix + gridX1 * iy;
  8547. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  8548. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  8549. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  8550. indices.push(a, b, d);
  8551. indices.push(b, c, d); // increase counter
  8552. groupCount += 6;
  8553. }
  8554. } // add a group to the geometry. this will ensure multi material support
  8555. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  8556. groupStart += groupCount; // update total number of vertices
  8557. numberOfVertices += vertexCounter;
  8558. }
  8559. }
  8560. }
  8561. /**
  8562. * Uniform Utilities
  8563. */
  8564. exports.BoxBufferGeometry = BoxBufferGeometry;
  8565. function cloneUniforms(src) {
  8566. var dst = {};
  8567. for (var u in src) {
  8568. dst[u] = {};
  8569. for (var p in src[u]) {
  8570. var property = src[u][p];
  8571. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  8572. dst[u][p] = property.clone();
  8573. } else if (Array.isArray(property)) {
  8574. dst[u][p] = property.slice();
  8575. } else {
  8576. dst[u][p] = property;
  8577. }
  8578. }
  8579. }
  8580. return dst;
  8581. }
  8582. function mergeUniforms(uniforms) {
  8583. var merged = {};
  8584. for (var u = 0; u < uniforms.length; u++) {
  8585. var tmp = cloneUniforms(uniforms[u]);
  8586. for (var p in tmp) {
  8587. merged[p] = tmp[p];
  8588. }
  8589. }
  8590. return merged;
  8591. } // Legacy
  8592. var UniformsUtils = {
  8593. clone: cloneUniforms,
  8594. merge: mergeUniforms
  8595. };
  8596. exports.UniformsUtils = UniformsUtils;
  8597. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8598. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8599. /**
  8600. * @author alteredq / http://alteredqualia.com/
  8601. *
  8602. * parameters = {
  8603. * defines: { "label" : "value" },
  8604. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8605. *
  8606. * fragmentShader: <string>,
  8607. * vertexShader: <string>,
  8608. *
  8609. * wireframe: <boolean>,
  8610. * wireframeLinewidth: <float>,
  8611. *
  8612. * lights: <bool>,
  8613. *
  8614. * skinning: <bool>,
  8615. * morphTargets: <bool>,
  8616. * morphNormals: <bool>
  8617. * }
  8618. */
  8619. function ShaderMaterial(parameters) {
  8620. Material.call(this);
  8621. this.type = 'ShaderMaterial';
  8622. this.defines = {};
  8623. this.uniforms = {};
  8624. this.vertexShader = default_vertex;
  8625. this.fragmentShader = default_fragment;
  8626. this.linewidth = 1;
  8627. this.wireframe = false;
  8628. this.wireframeLinewidth = 1;
  8629. this.fog = false; // set to use scene fog
  8630. this.lights = false; // set to use scene lights
  8631. this.clipping = false; // set to use user-defined clipping planes
  8632. this.skinning = false; // set to use skinning attribute streams
  8633. this.morphTargets = false; // set to use morph targets
  8634. this.morphNormals = false; // set to use morph normals
  8635. this.extensions = {
  8636. derivatives: false,
  8637. // set to use derivatives
  8638. fragDepth: false,
  8639. // set to use fragment depth values
  8640. drawBuffers: false,
  8641. // set to use draw buffers
  8642. shaderTextureLOD: false // set to use shader texture LOD
  8643. }; // When rendered geometry doesn't include these attributes but the material does,
  8644. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8645. this.defaultAttributeValues = {
  8646. 'color': [1, 1, 1],
  8647. 'uv': [0, 0],
  8648. 'uv2': [0, 0]
  8649. };
  8650. this.index0AttributeName = undefined;
  8651. this.uniformsNeedUpdate = false;
  8652. if (parameters !== undefined) {
  8653. if (parameters.attributes !== undefined) {
  8654. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  8655. }
  8656. this.setValues(parameters);
  8657. }
  8658. }
  8659. ShaderMaterial.prototype = Object.create(Material.prototype);
  8660. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8661. ShaderMaterial.prototype.isShaderMaterial = true;
  8662. ShaderMaterial.prototype.copy = function (source) {
  8663. Material.prototype.copy.call(this, source);
  8664. this.fragmentShader = source.fragmentShader;
  8665. this.vertexShader = source.vertexShader;
  8666. this.uniforms = cloneUniforms(source.uniforms);
  8667. this.defines = Object.assign({}, source.defines);
  8668. this.wireframe = source.wireframe;
  8669. this.wireframeLinewidth = source.wireframeLinewidth;
  8670. this.lights = source.lights;
  8671. this.clipping = source.clipping;
  8672. this.skinning = source.skinning;
  8673. this.morphTargets = source.morphTargets;
  8674. this.morphNormals = source.morphNormals;
  8675. this.extensions = source.extensions;
  8676. return this;
  8677. };
  8678. ShaderMaterial.prototype.toJSON = function (meta) {
  8679. var data = Material.prototype.toJSON.call(this, meta);
  8680. data.uniforms = {};
  8681. for (var name in this.uniforms) {
  8682. var uniform = this.uniforms[name];
  8683. var value = uniform.value;
  8684. if (value && value.isTexture) {
  8685. data.uniforms[name] = {
  8686. type: 't',
  8687. value: value.toJSON(meta).uuid
  8688. };
  8689. } else if (value && value.isColor) {
  8690. data.uniforms[name] = {
  8691. type: 'c',
  8692. value: value.getHex()
  8693. };
  8694. } else if (value && value.isVector2) {
  8695. data.uniforms[name] = {
  8696. type: 'v2',
  8697. value: value.toArray()
  8698. };
  8699. } else if (value && value.isVector3) {
  8700. data.uniforms[name] = {
  8701. type: 'v3',
  8702. value: value.toArray()
  8703. };
  8704. } else if (value && value.isVector4) {
  8705. data.uniforms[name] = {
  8706. type: 'v4',
  8707. value: value.toArray()
  8708. };
  8709. } else if (value && value.isMatrix3) {
  8710. data.uniforms[name] = {
  8711. type: 'm3',
  8712. value: value.toArray()
  8713. };
  8714. } else if (value && value.isMatrix4) {
  8715. data.uniforms[name] = {
  8716. type: 'm4',
  8717. value: value.toArray()
  8718. };
  8719. } else {
  8720. data.uniforms[name] = {
  8721. value: value
  8722. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  8723. }
  8724. }
  8725. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  8726. data.vertexShader = this.vertexShader;
  8727. data.fragmentShader = this.fragmentShader;
  8728. var extensions = {};
  8729. for (var key in this.extensions) {
  8730. if (this.extensions[key] === true) extensions[key] = true;
  8731. }
  8732. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  8733. return data;
  8734. };
  8735. /**
  8736. * @author mrdoob / http://mrdoob.com/
  8737. * @author mikael emtinger / http://gomo.se/
  8738. * @author WestLangley / http://github.com/WestLangley
  8739. */
  8740. function Camera() {
  8741. Object3D.call(this);
  8742. this.type = 'Camera';
  8743. this.matrixWorldInverse = new Matrix4();
  8744. this.projectionMatrix = new Matrix4();
  8745. this.projectionMatrixInverse = new Matrix4();
  8746. }
  8747. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  8748. constructor: Camera,
  8749. isCamera: true,
  8750. copy: function (source, recursive) {
  8751. Object3D.prototype.copy.call(this, source, recursive);
  8752. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  8753. this.projectionMatrix.copy(source.projectionMatrix);
  8754. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  8755. return this;
  8756. },
  8757. getWorldDirection: function (target) {
  8758. if (target === undefined) {
  8759. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  8760. target = new Vector3();
  8761. }
  8762. this.updateMatrixWorld(true);
  8763. var e = this.matrixWorld.elements;
  8764. return target.set(-e[8], -e[9], -e[10]).normalize();
  8765. },
  8766. updateMatrixWorld: function (force) {
  8767. Object3D.prototype.updateMatrixWorld.call(this, force);
  8768. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8769. },
  8770. updateWorldMatrix: function (updateParents, updateChildren) {
  8771. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  8772. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8773. },
  8774. clone: function () {
  8775. return new this.constructor().copy(this);
  8776. }
  8777. });
  8778. /**
  8779. * @author mrdoob / http://mrdoob.com/
  8780. * @author greggman / http://games.greggman.com/
  8781. * @author zz85 / http://www.lab4games.net/zz85/blog
  8782. * @author tschw
  8783. */
  8784. function PerspectiveCamera(fov, aspect, near, far) {
  8785. Camera.call(this);
  8786. this.type = 'PerspectiveCamera';
  8787. this.fov = fov !== undefined ? fov : 50;
  8788. this.zoom = 1;
  8789. this.near = near !== undefined ? near : 0.1;
  8790. this.far = far !== undefined ? far : 2000;
  8791. this.focus = 10;
  8792. this.aspect = aspect !== undefined ? aspect : 1;
  8793. this.view = null;
  8794. this.filmGauge = 35; // width of the film (default in millimeters)
  8795. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  8796. this.updateProjectionMatrix();
  8797. }
  8798. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  8799. constructor: PerspectiveCamera,
  8800. isPerspectiveCamera: true,
  8801. copy: function (source, recursive) {
  8802. Camera.prototype.copy.call(this, source, recursive);
  8803. this.fov = source.fov;
  8804. this.zoom = source.zoom;
  8805. this.near = source.near;
  8806. this.far = source.far;
  8807. this.focus = source.focus;
  8808. this.aspect = source.aspect;
  8809. this.view = source.view === null ? null : Object.assign({}, source.view);
  8810. this.filmGauge = source.filmGauge;
  8811. this.filmOffset = source.filmOffset;
  8812. return this;
  8813. },
  8814. /**
  8815. * Sets the FOV by focal length in respect to the current .filmGauge.
  8816. *
  8817. * The default film gauge is 35, so that the focal length can be specified for
  8818. * a 35mm (full frame) camera.
  8819. *
  8820. * Values for focal length and film gauge must have the same unit.
  8821. */
  8822. setFocalLength: function (focalLength) {
  8823. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  8824. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8825. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  8826. this.updateProjectionMatrix();
  8827. },
  8828. /**
  8829. * Calculates the focal length from the current .fov and .filmGauge.
  8830. */
  8831. getFocalLength: function () {
  8832. var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  8833. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8834. },
  8835. getEffectiveFOV: function () {
  8836. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8837. },
  8838. getFilmWidth: function () {
  8839. // film not completely covered in portrait format (aspect < 1)
  8840. return this.filmGauge * Math.min(this.aspect, 1);
  8841. },
  8842. getFilmHeight: function () {
  8843. // film not completely covered in landscape format (aspect > 1)
  8844. return this.filmGauge / Math.max(this.aspect, 1);
  8845. },
  8846. /**
  8847. * Sets an offset in a larger frustum. This is useful for multi-window or
  8848. * multi-monitor/multi-machine setups.
  8849. *
  8850. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8851. * the monitors are in grid like this
  8852. *
  8853. * +---+---+---+
  8854. * | A | B | C |
  8855. * +---+---+---+
  8856. * | D | E | F |
  8857. * +---+---+---+
  8858. *
  8859. * then for each monitor you would call it like this
  8860. *
  8861. * var w = 1920;
  8862. * var h = 1080;
  8863. * var fullWidth = w * 3;
  8864. * var fullHeight = h * 2;
  8865. *
  8866. * --A--
  8867. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8868. * --B--
  8869. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8870. * --C--
  8871. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8872. * --D--
  8873. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8874. * --E--
  8875. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8876. * --F--
  8877. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8878. *
  8879. * Note there is no reason monitors have to be the same size or in a grid.
  8880. */
  8881. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8882. this.aspect = fullWidth / fullHeight;
  8883. if (this.view === null) {
  8884. this.view = {
  8885. enabled: true,
  8886. fullWidth: 1,
  8887. fullHeight: 1,
  8888. offsetX: 0,
  8889. offsetY: 0,
  8890. width: 1,
  8891. height: 1
  8892. };
  8893. }
  8894. this.view.enabled = true;
  8895. this.view.fullWidth = fullWidth;
  8896. this.view.fullHeight = fullHeight;
  8897. this.view.offsetX = x;
  8898. this.view.offsetY = y;
  8899. this.view.width = width;
  8900. this.view.height = height;
  8901. this.updateProjectionMatrix();
  8902. },
  8903. clearViewOffset: function () {
  8904. if (this.view !== null) {
  8905. this.view.enabled = false;
  8906. }
  8907. this.updateProjectionMatrix();
  8908. },
  8909. updateProjectionMatrix: function () {
  8910. var near = this.near,
  8911. top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom,
  8912. height = 2 * top,
  8913. width = this.aspect * height,
  8914. left = -0.5 * width,
  8915. view = this.view;
  8916. if (this.view !== null && this.view.enabled) {
  8917. var fullWidth = view.fullWidth,
  8918. fullHeight = view.fullHeight;
  8919. left += view.offsetX * width / fullWidth;
  8920. top -= view.offsetY * height / fullHeight;
  8921. width *= view.width / fullWidth;
  8922. height *= view.height / fullHeight;
  8923. }
  8924. var skew = this.filmOffset;
  8925. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8926. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8927. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  8928. },
  8929. toJSON: function (meta) {
  8930. var data = Object3D.prototype.toJSON.call(this, meta);
  8931. data.object.fov = this.fov;
  8932. data.object.zoom = this.zoom;
  8933. data.object.near = this.near;
  8934. data.object.far = this.far;
  8935. data.object.focus = this.focus;
  8936. data.object.aspect = this.aspect;
  8937. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8938. data.object.filmGauge = this.filmGauge;
  8939. data.object.filmOffset = this.filmOffset;
  8940. return data;
  8941. }
  8942. });
  8943. /**
  8944. * Camera for rendering cube maps
  8945. * - renders scene into axis-aligned cube
  8946. *
  8947. * @author alteredq / http://alteredqualia.com/
  8948. */
  8949. var fov = 90,
  8950. aspect = 1;
  8951. function CubeCamera(near, far, cubeResolution, options) {
  8952. Object3D.call(this);
  8953. this.type = 'CubeCamera';
  8954. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8955. cameraPX.up.set(0, -1, 0);
  8956. cameraPX.lookAt(new Vector3(1, 0, 0));
  8957. this.add(cameraPX);
  8958. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8959. cameraNX.up.set(0, -1, 0);
  8960. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8961. this.add(cameraNX);
  8962. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8963. cameraPY.up.set(0, 0, 1);
  8964. cameraPY.lookAt(new Vector3(0, 1, 0));
  8965. this.add(cameraPY);
  8966. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8967. cameraNY.up.set(0, 0, -1);
  8968. cameraNY.lookAt(new Vector3(0, -1, 0));
  8969. this.add(cameraNY);
  8970. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8971. cameraPZ.up.set(0, -1, 0);
  8972. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8973. this.add(cameraPZ);
  8974. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8975. cameraNZ.up.set(0, -1, 0);
  8976. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8977. this.add(cameraNZ);
  8978. options = options || {
  8979. format: RGBFormat,
  8980. magFilter: LinearFilter,
  8981. minFilter: LinearFilter
  8982. };
  8983. this.renderTarget = new WebGLCubeRenderTarget(cubeResolution, options);
  8984. this.renderTarget.texture.name = "CubeCamera";
  8985. this.update = function (renderer, scene) {
  8986. if (this.parent === null) this.updateMatrixWorld();
  8987. var currentRenderTarget = renderer.getRenderTarget();
  8988. var renderTarget = this.renderTarget;
  8989. var generateMipmaps = renderTarget.texture.generateMipmaps;
  8990. renderTarget.texture.generateMipmaps = false;
  8991. renderer.setRenderTarget(renderTarget, 0);
  8992. renderer.render(scene, cameraPX);
  8993. renderer.setRenderTarget(renderTarget, 1);
  8994. renderer.render(scene, cameraNX);
  8995. renderer.setRenderTarget(renderTarget, 2);
  8996. renderer.render(scene, cameraPY);
  8997. renderer.setRenderTarget(renderTarget, 3);
  8998. renderer.render(scene, cameraNY);
  8999. renderer.setRenderTarget(renderTarget, 4);
  9000. renderer.render(scene, cameraPZ);
  9001. renderTarget.texture.generateMipmaps = generateMipmaps;
  9002. renderer.setRenderTarget(renderTarget, 5);
  9003. renderer.render(scene, cameraNZ);
  9004. renderer.setRenderTarget(currentRenderTarget);
  9005. };
  9006. this.clear = function (renderer, color, depth, stencil) {
  9007. var currentRenderTarget = renderer.getRenderTarget();
  9008. var renderTarget = this.renderTarget;
  9009. for (var i = 0; i < 6; i++) {
  9010. renderer.setRenderTarget(renderTarget, i);
  9011. renderer.clear(color, depth, stencil);
  9012. }
  9013. renderer.setRenderTarget(currentRenderTarget);
  9014. };
  9015. }
  9016. CubeCamera.prototype = Object.create(Object3D.prototype);
  9017. CubeCamera.prototype.constructor = CubeCamera;
  9018. /**
  9019. * @author alteredq / http://alteredqualia.com
  9020. * @author WestLangley / http://github.com/WestLangley
  9021. */
  9022. function WebGLCubeRenderTarget(size, options, dummy) {
  9023. if (Number.isInteger(options)) {
  9024. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  9025. options = dummy;
  9026. }
  9027. WebGLRenderTarget.call(this, size, size, options);
  9028. }
  9029. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  9030. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  9031. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  9032. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9033. this.texture.type = texture.type;
  9034. this.texture.format = texture.format;
  9035. this.texture.encoding = texture.encoding;
  9036. var scene = new Scene();
  9037. var shader = {
  9038. uniforms: {
  9039. tEquirect: {
  9040. value: null
  9041. }
  9042. },
  9043. vertexShader: ["varying vec3 vWorldDirection;", "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", "}", "void main() {", " vWorldDirection = transformDirection( position, modelMatrix );", " #include <begin_vertex>", " #include <project_vertex>", "}"].join('\n'),
  9044. fragmentShader: ["uniform sampler2D tEquirect;", "varying vec3 vWorldDirection;", "#define RECIPROCAL_PI 0.31830988618", "#define RECIPROCAL_PI2 0.15915494", "void main() {", " vec3 direction = normalize( vWorldDirection );", " vec2 sampleUV;", " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;", " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", " gl_FragColor = texture2D( tEquirect, sampleUV );", "}"].join('\n')
  9045. };
  9046. var material = new ShaderMaterial({
  9047. type: 'CubemapFromEquirect',
  9048. uniforms: cloneUniforms(shader.uniforms),
  9049. vertexShader: shader.vertexShader,
  9050. fragmentShader: shader.fragmentShader,
  9051. side: BackSide,
  9052. blending: NoBlending
  9053. });
  9054. material.uniforms.tEquirect.value = texture;
  9055. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9056. scene.add(mesh);
  9057. var camera = new CubeCamera(1, 10, 1);
  9058. camera.renderTarget = this;
  9059. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9060. camera.update(renderer, scene);
  9061. mesh.geometry.dispose();
  9062. mesh.material.dispose();
  9063. return this;
  9064. };
  9065. /**
  9066. * @author alteredq / http://alteredqualia.com/
  9067. */
  9068. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9069. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9070. this.image = {
  9071. data: data || null,
  9072. width: width || 1,
  9073. height: height || 1
  9074. };
  9075. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9076. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9077. this.generateMipmaps = false;
  9078. this.flipY = false;
  9079. this.unpackAlignment = 1;
  9080. this.needsUpdate = true;
  9081. }
  9082. DataTexture.prototype = Object.create(Texture.prototype);
  9083. DataTexture.prototype.constructor = DataTexture;
  9084. DataTexture.prototype.isDataTexture = true;
  9085. /**
  9086. * @author mrdoob / http://mrdoob.com/
  9087. * @author alteredq / http://alteredqualia.com/
  9088. * @author bhouston / http://clara.io
  9089. */
  9090. var _sphere$1 = new Sphere();
  9091. var _vector$5 = new Vector3();
  9092. function Frustum(p0, p1, p2, p3, p4, p5) {
  9093. 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()];
  9094. }
  9095. Object.assign(Frustum.prototype, {
  9096. set: function (p0, p1, p2, p3, p4, p5) {
  9097. var planes = this.planes;
  9098. planes[0].copy(p0);
  9099. planes[1].copy(p1);
  9100. planes[2].copy(p2);
  9101. planes[3].copy(p3);
  9102. planes[4].copy(p4);
  9103. planes[5].copy(p5);
  9104. return this;
  9105. },
  9106. clone: function () {
  9107. return new this.constructor().copy(this);
  9108. },
  9109. copy: function (frustum) {
  9110. var planes = this.planes;
  9111. for (var i = 0; i < 6; i++) {
  9112. planes[i].copy(frustum.planes[i]);
  9113. }
  9114. return this;
  9115. },
  9116. setFromProjectionMatrix: function (m) {
  9117. var planes = this.planes;
  9118. var me = m.elements;
  9119. var me0 = me[0],
  9120. me1 = me[1],
  9121. me2 = me[2],
  9122. me3 = me[3];
  9123. var me4 = me[4],
  9124. me5 = me[5],
  9125. me6 = me[6],
  9126. me7 = me[7];
  9127. var me8 = me[8],
  9128. me9 = me[9],
  9129. me10 = me[10],
  9130. me11 = me[11];
  9131. var me12 = me[12],
  9132. me13 = me[13],
  9133. me14 = me[14],
  9134. me15 = me[15];
  9135. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  9136. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  9137. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  9138. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  9139. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  9140. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  9141. return this;
  9142. },
  9143. intersectsObject: function (object) {
  9144. var geometry = object.geometry;
  9145. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  9146. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  9147. return this.intersectsSphere(_sphere$1);
  9148. },
  9149. intersectsSprite: function (sprite) {
  9150. _sphere$1.center.set(0, 0, 0);
  9151. _sphere$1.radius = 0.7071067811865476;
  9152. _sphere$1.applyMatrix4(sprite.matrixWorld);
  9153. return this.intersectsSphere(_sphere$1);
  9154. },
  9155. intersectsSphere: function (sphere) {
  9156. var planes = this.planes;
  9157. var center = sphere.center;
  9158. var negRadius = -sphere.radius;
  9159. for (var i = 0; i < 6; i++) {
  9160. var distance = planes[i].distanceToPoint(center);
  9161. if (distance < negRadius) {
  9162. return false;
  9163. }
  9164. }
  9165. return true;
  9166. },
  9167. intersectsBox: function (box) {
  9168. var planes = this.planes;
  9169. for (var i = 0; i < 6; i++) {
  9170. var plane = planes[i]; // corner at max distance
  9171. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9172. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9173. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9174. if (plane.distanceToPoint(_vector$5) < 0) {
  9175. return false;
  9176. }
  9177. }
  9178. return true;
  9179. },
  9180. containsPoint: function (point) {
  9181. var planes = this.planes;
  9182. for (var i = 0; i < 6; i++) {
  9183. if (planes[i].distanceToPoint(point) < 0) {
  9184. return false;
  9185. }
  9186. }
  9187. return true;
  9188. }
  9189. });
  9190. /**
  9191. * Uniforms library for shared webgl shaders
  9192. */
  9193. var UniformsLib = {
  9194. common: {
  9195. diffuse: {
  9196. value: new Color(0xeeeeee)
  9197. },
  9198. opacity: {
  9199. value: 1.0
  9200. },
  9201. map: {
  9202. value: null
  9203. },
  9204. uvTransform: {
  9205. value: new Matrix3()
  9206. },
  9207. uv2Transform: {
  9208. value: new Matrix3()
  9209. },
  9210. alphaMap: {
  9211. value: null
  9212. }
  9213. },
  9214. specularmap: {
  9215. specularMap: {
  9216. value: null
  9217. }
  9218. },
  9219. envmap: {
  9220. envMap: {
  9221. value: null
  9222. },
  9223. flipEnvMap: {
  9224. value: -1
  9225. },
  9226. reflectivity: {
  9227. value: 1.0
  9228. },
  9229. refractionRatio: {
  9230. value: 0.98
  9231. },
  9232. maxMipLevel: {
  9233. value: 0
  9234. }
  9235. },
  9236. aomap: {
  9237. aoMap: {
  9238. value: null
  9239. },
  9240. aoMapIntensity: {
  9241. value: 1
  9242. }
  9243. },
  9244. lightmap: {
  9245. lightMap: {
  9246. value: null
  9247. },
  9248. lightMapIntensity: {
  9249. value: 1
  9250. }
  9251. },
  9252. emissivemap: {
  9253. emissiveMap: {
  9254. value: null
  9255. }
  9256. },
  9257. bumpmap: {
  9258. bumpMap: {
  9259. value: null
  9260. },
  9261. bumpScale: {
  9262. value: 1
  9263. }
  9264. },
  9265. normalmap: {
  9266. normalMap: {
  9267. value: null
  9268. },
  9269. normalScale: {
  9270. value: new Vector2(1, 1)
  9271. }
  9272. },
  9273. displacementmap: {
  9274. displacementMap: {
  9275. value: null
  9276. },
  9277. displacementScale: {
  9278. value: 1
  9279. },
  9280. displacementBias: {
  9281. value: 0
  9282. }
  9283. },
  9284. roughnessmap: {
  9285. roughnessMap: {
  9286. value: null
  9287. }
  9288. },
  9289. metalnessmap: {
  9290. metalnessMap: {
  9291. value: null
  9292. }
  9293. },
  9294. gradientmap: {
  9295. gradientMap: {
  9296. value: null
  9297. }
  9298. },
  9299. fog: {
  9300. fogDensity: {
  9301. value: 0.00025
  9302. },
  9303. fogNear: {
  9304. value: 1
  9305. },
  9306. fogFar: {
  9307. value: 2000
  9308. },
  9309. fogColor: {
  9310. value: new Color(0xffffff)
  9311. }
  9312. },
  9313. lights: {
  9314. ambientLightColor: {
  9315. value: []
  9316. },
  9317. lightProbe: {
  9318. value: []
  9319. },
  9320. directionalLights: {
  9321. value: [],
  9322. properties: {
  9323. direction: {},
  9324. color: {}
  9325. }
  9326. },
  9327. directionalLightShadows: {
  9328. value: [],
  9329. properties: {
  9330. shadowBias: {},
  9331. shadowRadius: {},
  9332. shadowMapSize: {}
  9333. }
  9334. },
  9335. directionalShadowMap: {
  9336. value: []
  9337. },
  9338. directionalShadowMatrix: {
  9339. value: []
  9340. },
  9341. spotLights: {
  9342. value: [],
  9343. properties: {
  9344. color: {},
  9345. position: {},
  9346. direction: {},
  9347. distance: {},
  9348. coneCos: {},
  9349. penumbraCos: {},
  9350. decay: {}
  9351. }
  9352. },
  9353. spotLightShadows: {
  9354. value: [],
  9355. properties: {
  9356. shadowBias: {},
  9357. shadowRadius: {},
  9358. shadowMapSize: {}
  9359. }
  9360. },
  9361. spotShadowMap: {
  9362. value: []
  9363. },
  9364. spotShadowMatrix: {
  9365. value: []
  9366. },
  9367. pointLights: {
  9368. value: [],
  9369. properties: {
  9370. color: {},
  9371. position: {},
  9372. decay: {},
  9373. distance: {}
  9374. }
  9375. },
  9376. pointLightShadows: {
  9377. value: [],
  9378. properties: {
  9379. shadowBias: {},
  9380. shadowRadius: {},
  9381. shadowMapSize: {},
  9382. shadowCameraNear: {},
  9383. shadowCameraFar: {}
  9384. }
  9385. },
  9386. pointShadowMap: {
  9387. value: []
  9388. },
  9389. pointShadowMatrix: {
  9390. value: []
  9391. },
  9392. hemisphereLights: {
  9393. value: [],
  9394. properties: {
  9395. direction: {},
  9396. skyColor: {},
  9397. groundColor: {}
  9398. }
  9399. },
  9400. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9401. rectAreaLights: {
  9402. value: [],
  9403. properties: {
  9404. color: {},
  9405. position: {},
  9406. width: {},
  9407. height: {}
  9408. }
  9409. }
  9410. },
  9411. points: {
  9412. diffuse: {
  9413. value: new Color(0xeeeeee)
  9414. },
  9415. opacity: {
  9416. value: 1.0
  9417. },
  9418. size: {
  9419. value: 1.0
  9420. },
  9421. scale: {
  9422. value: 1.0
  9423. },
  9424. map: {
  9425. value: null
  9426. },
  9427. alphaMap: {
  9428. value: null
  9429. },
  9430. uvTransform: {
  9431. value: new Matrix3()
  9432. }
  9433. },
  9434. sprite: {
  9435. diffuse: {
  9436. value: new Color(0xeeeeee)
  9437. },
  9438. opacity: {
  9439. value: 1.0
  9440. },
  9441. center: {
  9442. value: new Vector2(0.5, 0.5)
  9443. },
  9444. rotation: {
  9445. value: 0.0
  9446. },
  9447. map: {
  9448. value: null
  9449. },
  9450. alphaMap: {
  9451. value: null
  9452. },
  9453. uvTransform: {
  9454. value: new Matrix3()
  9455. }
  9456. }
  9457. };
  9458. /**
  9459. * @author mrdoob / http://mrdoob.com/
  9460. */
  9461. exports.UniformsLib = UniformsLib;
  9462. function WebGLAnimation() {
  9463. var context = null;
  9464. var isAnimating = false;
  9465. var animationLoop = null;
  9466. function onAnimationFrame(time, frame) {
  9467. if (isAnimating === false) return;
  9468. animationLoop(time, frame);
  9469. context.requestAnimationFrame(onAnimationFrame);
  9470. }
  9471. return {
  9472. start: function () {
  9473. if (isAnimating === true) return;
  9474. if (animationLoop === null) return;
  9475. context.requestAnimationFrame(onAnimationFrame);
  9476. isAnimating = true;
  9477. },
  9478. stop: function () {
  9479. isAnimating = false;
  9480. },
  9481. setAnimationLoop: function (callback) {
  9482. animationLoop = callback;
  9483. },
  9484. setContext: function (value) {
  9485. context = value;
  9486. }
  9487. };
  9488. }
  9489. /**
  9490. * @author mrdoob / http://mrdoob.com/
  9491. */
  9492. function WebGLAttributes(gl, capabilities) {
  9493. var isWebGL2 = capabilities.isWebGL2;
  9494. var buffers = new WeakMap();
  9495. function createBuffer(attribute, bufferType) {
  9496. var array = attribute.array;
  9497. var usage = attribute.usage;
  9498. var buffer = gl.createBuffer();
  9499. gl.bindBuffer(bufferType, buffer);
  9500. gl.bufferData(bufferType, array, usage);
  9501. attribute.onUploadCallback();
  9502. var type = 5126;
  9503. if (array instanceof Float32Array) {
  9504. type = 5126;
  9505. } else if (array instanceof Float64Array) {
  9506. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  9507. } else if (array instanceof Uint16Array) {
  9508. type = 5123;
  9509. } else if (array instanceof Int16Array) {
  9510. type = 5122;
  9511. } else if (array instanceof Uint32Array) {
  9512. type = 5125;
  9513. } else if (array instanceof Int32Array) {
  9514. type = 5124;
  9515. } else if (array instanceof Int8Array) {
  9516. type = 5120;
  9517. } else if (array instanceof Uint8Array) {
  9518. type = 5121;
  9519. }
  9520. return {
  9521. buffer: buffer,
  9522. type: type,
  9523. bytesPerElement: array.BYTES_PER_ELEMENT,
  9524. version: attribute.version
  9525. };
  9526. }
  9527. function updateBuffer(buffer, attribute, bufferType) {
  9528. var array = attribute.array;
  9529. var updateRange = attribute.updateRange;
  9530. gl.bindBuffer(bufferType, buffer);
  9531. if (updateRange.count === -1) {
  9532. // Not using update ranges
  9533. gl.bufferSubData(bufferType, 0, array);
  9534. } else {
  9535. if (isWebGL2) {
  9536. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  9537. } else {
  9538. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  9539. }
  9540. updateRange.count = -1; // reset range
  9541. }
  9542. } //
  9543. function get(attribute) {
  9544. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9545. return buffers.get(attribute);
  9546. }
  9547. function remove(attribute) {
  9548. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9549. var data = buffers.get(attribute);
  9550. if (data) {
  9551. gl.deleteBuffer(data.buffer);
  9552. buffers.delete(attribute);
  9553. }
  9554. }
  9555. function update(attribute, bufferType) {
  9556. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9557. var data = buffers.get(attribute);
  9558. if (data === undefined) {
  9559. buffers.set(attribute, createBuffer(attribute, bufferType));
  9560. } else if (data.version < attribute.version) {
  9561. updateBuffer(data.buffer, attribute, bufferType);
  9562. data.version = attribute.version;
  9563. }
  9564. }
  9565. return {
  9566. get: get,
  9567. remove: remove,
  9568. update: update
  9569. };
  9570. }
  9571. /**
  9572. * @author mrdoob / http://mrdoob.com/
  9573. * @author Mugen87 / https://github.com/Mugen87
  9574. */
  9575. // PlaneGeometry
  9576. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  9577. Geometry.call(this);
  9578. this.type = 'PlaneGeometry';
  9579. this.parameters = {
  9580. width: width,
  9581. height: height,
  9582. widthSegments: widthSegments,
  9583. heightSegments: heightSegments
  9584. };
  9585. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  9586. this.mergeVertices();
  9587. }
  9588. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  9589. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  9590. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  9591. BufferGeometry.call(this);
  9592. this.type = 'PlaneBufferGeometry';
  9593. this.parameters = {
  9594. width: width,
  9595. height: height,
  9596. widthSegments: widthSegments,
  9597. heightSegments: heightSegments
  9598. };
  9599. width = width || 1;
  9600. height = height || 1;
  9601. var width_half = width / 2;
  9602. var height_half = height / 2;
  9603. var gridX = Math.floor(widthSegments) || 1;
  9604. var gridY = Math.floor(heightSegments) || 1;
  9605. var gridX1 = gridX + 1;
  9606. var gridY1 = gridY + 1;
  9607. var segment_width = width / gridX;
  9608. var segment_height = height / gridY;
  9609. var ix, iy; // buffers
  9610. var indices = [];
  9611. var vertices = [];
  9612. var normals = [];
  9613. var uvs = []; // generate vertices, normals and uvs
  9614. for (iy = 0; iy < gridY1; iy++) {
  9615. var y = iy * segment_height - height_half;
  9616. for (ix = 0; ix < gridX1; ix++) {
  9617. var x = ix * segment_width - width_half;
  9618. vertices.push(x, -y, 0);
  9619. normals.push(0, 0, 1);
  9620. uvs.push(ix / gridX);
  9621. uvs.push(1 - iy / gridY);
  9622. }
  9623. } // indices
  9624. for (iy = 0; iy < gridY; iy++) {
  9625. for (ix = 0; ix < gridX; ix++) {
  9626. var a = ix + gridX1 * iy;
  9627. var b = ix + gridX1 * (iy + 1);
  9628. var c = ix + 1 + gridX1 * (iy + 1);
  9629. var d = ix + 1 + gridX1 * iy; // faces
  9630. indices.push(a, b, d);
  9631. indices.push(b, c, d);
  9632. }
  9633. } // build geometry
  9634. this.setIndex(indices);
  9635. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  9636. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  9637. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9638. }
  9639. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  9640. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9641. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  9642. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  9643. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  9644. 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";
  9645. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  9646. var begin_vertex = "vec3 transformed = vec3( position );";
  9647. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  9648. 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";
  9649. 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";
  9650. 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";
  9651. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  9652. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  9653. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  9654. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  9655. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9656. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9657. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  9658. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\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 return m[ 2 ][ 3 ] == - 1.0;\n}";
  9659. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x);\n } else if (face == 1.0) {\n uv = vec2(direction.x, -direction.z) / abs(direction.y);\n } else if (face == 2.0) {\n uv = direction.xy / abs(direction.z);\n } else if (face == 3.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x);\n } else if (face == 4.0) {\n uv = direction.xz / abs(direction.y);\n } else {\n uv = vec2(-direction.x, direction.y) / abs(direction.z);\n }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif";
  9660. 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";
  9661. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  9662. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  9663. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  9664. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  9665. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  9666. 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}";
  9667. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\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#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\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";
  9668. 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";
  9669. 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";
  9670. 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";
  9671. 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";
  9672. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  9673. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  9674. 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";
  9675. 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";
  9676. 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}";
  9677. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  9678. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  9679. 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;\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";
  9680. 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\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\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\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\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\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\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\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\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\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";
  9681. 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 vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 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#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  9682. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9683. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\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\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\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)";
  9684. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9685. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\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)";
  9686. 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";
  9687. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\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}";
  9688. 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";
  9689. 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";
  9690. 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";
  9691. 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";
  9692. 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";
  9693. 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";
  9694. 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";
  9695. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  9696. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  9697. 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";
  9698. 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";
  9699. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  9700. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  9701. 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";
  9702. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  9703. 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\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  9704. 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;";
  9705. 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";
  9706. 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";
  9707. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  9708. 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";
  9709. 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";
  9710. 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}";
  9711. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  9712. 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;";
  9713. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  9714. 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";
  9715. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  9716. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  9717. 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#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#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#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";
  9718. 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#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#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#endif\n#endif";
  9719. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\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\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\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\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\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\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  9720. 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}";
  9721. 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";
  9722. 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";
  9723. 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";
  9724. 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";
  9725. 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";
  9726. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  9727. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  9728. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\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}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\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 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";
  9729. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  9730. 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";
  9731. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  9732. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  9733. 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";
  9734. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  9735. 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";
  9736. 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}";
  9737. 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}";
  9738. 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}";
  9739. 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}";
  9740. 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}";
  9741. 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}";
  9742. 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}";
  9743. 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}";
  9744. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  9745. 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}";
  9746. 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}";
  9747. 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 <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 <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  9748. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\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}";
  9749. 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}";
  9750. 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\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\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}";
  9751. 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}";
  9752. 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 <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}";
  9753. 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}";
  9754. var meshtoon_frag = "#define TOON\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 <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 <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_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 + reflectedLight.directSpecular + reflectedLight.indirectSpecular + 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}";
  9755. 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}";
  9756. 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}";
  9757. 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}";
  9758. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\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}";
  9759. 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}";
  9760. 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}";
  9761. 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}";
  9762. 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}";
  9763. 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}";
  9764. 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}";
  9765. var shadow_vert = "#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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9766. 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}";
  9767. 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}";
  9768. var ShaderChunk = {
  9769. alphamap_fragment: alphamap_fragment,
  9770. alphamap_pars_fragment: alphamap_pars_fragment,
  9771. alphatest_fragment: alphatest_fragment,
  9772. aomap_fragment: aomap_fragment,
  9773. aomap_pars_fragment: aomap_pars_fragment,
  9774. begin_vertex: begin_vertex,
  9775. beginnormal_vertex: beginnormal_vertex,
  9776. bsdfs: bsdfs,
  9777. bumpmap_pars_fragment: bumpmap_pars_fragment,
  9778. clipping_planes_fragment: clipping_planes_fragment,
  9779. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  9780. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  9781. clipping_planes_vertex: clipping_planes_vertex,
  9782. color_fragment: color_fragment,
  9783. color_pars_fragment: color_pars_fragment,
  9784. color_pars_vertex: color_pars_vertex,
  9785. color_vertex: color_vertex,
  9786. common: common,
  9787. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  9788. defaultnormal_vertex: defaultnormal_vertex,
  9789. displacementmap_pars_vertex: displacementmap_pars_vertex,
  9790. displacementmap_vertex: displacementmap_vertex,
  9791. emissivemap_fragment: emissivemap_fragment,
  9792. emissivemap_pars_fragment: emissivemap_pars_fragment,
  9793. encodings_fragment: encodings_fragment,
  9794. encodings_pars_fragment: encodings_pars_fragment,
  9795. envmap_fragment: envmap_fragment,
  9796. envmap_common_pars_fragment: envmap_common_pars_fragment,
  9797. envmap_pars_fragment: envmap_pars_fragment,
  9798. envmap_pars_vertex: envmap_pars_vertex,
  9799. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  9800. envmap_vertex: envmap_vertex,
  9801. fog_vertex: fog_vertex,
  9802. fog_pars_vertex: fog_pars_vertex,
  9803. fog_fragment: fog_fragment,
  9804. fog_pars_fragment: fog_pars_fragment,
  9805. gradientmap_pars_fragment: gradientmap_pars_fragment,
  9806. lightmap_fragment: lightmap_fragment,
  9807. lightmap_pars_fragment: lightmap_pars_fragment,
  9808. lights_lambert_vertex: lights_lambert_vertex,
  9809. lights_pars_begin: lights_pars_begin,
  9810. lights_toon_fragment: lights_toon_fragment,
  9811. lights_toon_pars_fragment: lights_toon_pars_fragment,
  9812. lights_phong_fragment: lights_phong_fragment,
  9813. lights_phong_pars_fragment: lights_phong_pars_fragment,
  9814. lights_physical_fragment: lights_physical_fragment,
  9815. lights_physical_pars_fragment: lights_physical_pars_fragment,
  9816. lights_fragment_begin: lights_fragment_begin,
  9817. lights_fragment_maps: lights_fragment_maps,
  9818. lights_fragment_end: lights_fragment_end,
  9819. logdepthbuf_fragment: logdepthbuf_fragment,
  9820. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  9821. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  9822. logdepthbuf_vertex: logdepthbuf_vertex,
  9823. map_fragment: map_fragment,
  9824. map_pars_fragment: map_pars_fragment,
  9825. map_particle_fragment: map_particle_fragment,
  9826. map_particle_pars_fragment: map_particle_pars_fragment,
  9827. metalnessmap_fragment: metalnessmap_fragment,
  9828. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  9829. morphnormal_vertex: morphnormal_vertex,
  9830. morphtarget_pars_vertex: morphtarget_pars_vertex,
  9831. morphtarget_vertex: morphtarget_vertex,
  9832. normal_fragment_begin: normal_fragment_begin,
  9833. normal_fragment_maps: normal_fragment_maps,
  9834. normalmap_pars_fragment: normalmap_pars_fragment,
  9835. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  9836. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  9837. clearcoat_pars_fragment: clearcoat_pars_fragment,
  9838. packing: packing,
  9839. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  9840. project_vertex: project_vertex,
  9841. dithering_fragment: dithering_fragment,
  9842. dithering_pars_fragment: dithering_pars_fragment,
  9843. roughnessmap_fragment: roughnessmap_fragment,
  9844. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  9845. shadowmap_pars_fragment: shadowmap_pars_fragment,
  9846. shadowmap_pars_vertex: shadowmap_pars_vertex,
  9847. shadowmap_vertex: shadowmap_vertex,
  9848. shadowmask_pars_fragment: shadowmask_pars_fragment,
  9849. skinbase_vertex: skinbase_vertex,
  9850. skinning_pars_vertex: skinning_pars_vertex,
  9851. skinning_vertex: skinning_vertex,
  9852. skinnormal_vertex: skinnormal_vertex,
  9853. specularmap_fragment: specularmap_fragment,
  9854. specularmap_pars_fragment: specularmap_pars_fragment,
  9855. tonemapping_fragment: tonemapping_fragment,
  9856. tonemapping_pars_fragment: tonemapping_pars_fragment,
  9857. uv_pars_fragment: uv_pars_fragment,
  9858. uv_pars_vertex: uv_pars_vertex,
  9859. uv_vertex: uv_vertex,
  9860. uv2_pars_fragment: uv2_pars_fragment,
  9861. uv2_pars_vertex: uv2_pars_vertex,
  9862. uv2_vertex: uv2_vertex,
  9863. worldpos_vertex: worldpos_vertex,
  9864. background_frag: background_frag,
  9865. background_vert: background_vert,
  9866. cube_frag: cube_frag,
  9867. cube_vert: cube_vert,
  9868. depth_frag: depth_frag,
  9869. depth_vert: depth_vert,
  9870. distanceRGBA_frag: distanceRGBA_frag,
  9871. distanceRGBA_vert: distanceRGBA_vert,
  9872. equirect_frag: equirect_frag,
  9873. equirect_vert: equirect_vert,
  9874. linedashed_frag: linedashed_frag,
  9875. linedashed_vert: linedashed_vert,
  9876. meshbasic_frag: meshbasic_frag,
  9877. meshbasic_vert: meshbasic_vert,
  9878. meshlambert_frag: meshlambert_frag,
  9879. meshlambert_vert: meshlambert_vert,
  9880. meshmatcap_frag: meshmatcap_frag,
  9881. meshmatcap_vert: meshmatcap_vert,
  9882. meshtoon_frag: meshtoon_frag,
  9883. meshtoon_vert: meshtoon_vert,
  9884. meshphong_frag: meshphong_frag,
  9885. meshphong_vert: meshphong_vert,
  9886. meshphysical_frag: meshphysical_frag,
  9887. meshphysical_vert: meshphysical_vert,
  9888. normal_frag: normal_frag,
  9889. normal_vert: normal_vert,
  9890. points_frag: points_frag,
  9891. points_vert: points_vert,
  9892. shadow_frag: shadow_frag,
  9893. shadow_vert: shadow_vert,
  9894. sprite_frag: sprite_frag,
  9895. sprite_vert: sprite_vert
  9896. };
  9897. /**
  9898. * @author alteredq / http://alteredqualia.com/
  9899. * @author mrdoob / http://mrdoob.com/
  9900. * @author mikael emtinger / http://gomo.se/
  9901. */
  9902. exports.ShaderChunk = ShaderChunk;
  9903. var ShaderLib = {
  9904. basic: {
  9905. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9906. vertexShader: ShaderChunk.meshbasic_vert,
  9907. fragmentShader: ShaderChunk.meshbasic_frag
  9908. },
  9909. lambert: {
  9910. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9911. emissive: {
  9912. value: new Color(0x000000)
  9913. }
  9914. }]),
  9915. vertexShader: ShaderChunk.meshlambert_vert,
  9916. fragmentShader: ShaderChunk.meshlambert_frag
  9917. },
  9918. phong: {
  9919. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  9920. emissive: {
  9921. value: new Color(0x000000)
  9922. },
  9923. specular: {
  9924. value: new Color(0x111111)
  9925. },
  9926. shininess: {
  9927. value: 30
  9928. }
  9929. }]),
  9930. vertexShader: ShaderChunk.meshphong_vert,
  9931. fragmentShader: ShaderChunk.meshphong_frag
  9932. },
  9933. standard: {
  9934. 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, {
  9935. emissive: {
  9936. value: new Color(0x000000)
  9937. },
  9938. roughness: {
  9939. value: 0.5
  9940. },
  9941. metalness: {
  9942. value: 0.5
  9943. },
  9944. envMapIntensity: {
  9945. value: 1
  9946. } // temporary
  9947. }]),
  9948. vertexShader: ShaderChunk.meshphysical_vert,
  9949. fragmentShader: ShaderChunk.meshphysical_frag
  9950. },
  9951. toon: {
  9952. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  9953. emissive: {
  9954. value: new Color(0x000000)
  9955. },
  9956. specular: {
  9957. value: new Color(0x111111)
  9958. },
  9959. shininess: {
  9960. value: 30
  9961. }
  9962. }]),
  9963. vertexShader: ShaderChunk.meshtoon_vert,
  9964. fragmentShader: ShaderChunk.meshtoon_frag
  9965. },
  9966. matcap: {
  9967. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9968. matcap: {
  9969. value: null
  9970. }
  9971. }]),
  9972. vertexShader: ShaderChunk.meshmatcap_vert,
  9973. fragmentShader: ShaderChunk.meshmatcap_frag
  9974. },
  9975. points: {
  9976. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9977. vertexShader: ShaderChunk.points_vert,
  9978. fragmentShader: ShaderChunk.points_frag
  9979. },
  9980. dashed: {
  9981. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9982. scale: {
  9983. value: 1
  9984. },
  9985. dashSize: {
  9986. value: 1
  9987. },
  9988. totalSize: {
  9989. value: 2
  9990. }
  9991. }]),
  9992. vertexShader: ShaderChunk.linedashed_vert,
  9993. fragmentShader: ShaderChunk.linedashed_frag
  9994. },
  9995. depth: {
  9996. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9997. vertexShader: ShaderChunk.depth_vert,
  9998. fragmentShader: ShaderChunk.depth_frag
  9999. },
  10000. normal: {
  10001. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10002. opacity: {
  10003. value: 1.0
  10004. }
  10005. }]),
  10006. vertexShader: ShaderChunk.normal_vert,
  10007. fragmentShader: ShaderChunk.normal_frag
  10008. },
  10009. sprite: {
  10010. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10011. vertexShader: ShaderChunk.sprite_vert,
  10012. fragmentShader: ShaderChunk.sprite_frag
  10013. },
  10014. background: {
  10015. uniforms: {
  10016. uvTransform: {
  10017. value: new Matrix3()
  10018. },
  10019. t2D: {
  10020. value: null
  10021. }
  10022. },
  10023. vertexShader: ShaderChunk.background_vert,
  10024. fragmentShader: ShaderChunk.background_frag
  10025. },
  10026. /* -------------------------------------------------------------------------
  10027. // Cube map shader
  10028. ------------------------------------------------------------------------- */
  10029. cube: {
  10030. uniforms: mergeUniforms([UniformsLib.envmap, {
  10031. opacity: {
  10032. value: 1.0
  10033. }
  10034. }]),
  10035. vertexShader: ShaderChunk.cube_vert,
  10036. fragmentShader: ShaderChunk.cube_frag
  10037. },
  10038. equirect: {
  10039. uniforms: {
  10040. tEquirect: {
  10041. value: null
  10042. }
  10043. },
  10044. vertexShader: ShaderChunk.equirect_vert,
  10045. fragmentShader: ShaderChunk.equirect_frag
  10046. },
  10047. distanceRGBA: {
  10048. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10049. referencePosition: {
  10050. value: new Vector3()
  10051. },
  10052. nearDistance: {
  10053. value: 1
  10054. },
  10055. farDistance: {
  10056. value: 1000
  10057. }
  10058. }]),
  10059. vertexShader: ShaderChunk.distanceRGBA_vert,
  10060. fragmentShader: ShaderChunk.distanceRGBA_frag
  10061. },
  10062. shadow: {
  10063. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10064. color: {
  10065. value: new Color(0x00000)
  10066. },
  10067. opacity: {
  10068. value: 1.0
  10069. }
  10070. }]),
  10071. vertexShader: ShaderChunk.shadow_vert,
  10072. fragmentShader: ShaderChunk.shadow_frag
  10073. }
  10074. };
  10075. exports.ShaderLib = ShaderLib;
  10076. ShaderLib.physical = {
  10077. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10078. clearcoat: {
  10079. value: 0
  10080. },
  10081. clearcoatMap: {
  10082. value: null
  10083. },
  10084. clearcoatRoughness: {
  10085. value: 0
  10086. },
  10087. clearcoatRoughnessMap: {
  10088. value: null
  10089. },
  10090. clearcoatNormalScale: {
  10091. value: new Vector2(1, 1)
  10092. },
  10093. clearcoatNormalMap: {
  10094. value: null
  10095. },
  10096. sheen: {
  10097. value: new Color(0x000000)
  10098. },
  10099. transparency: {
  10100. value: 0
  10101. }
  10102. }]),
  10103. vertexShader: ShaderChunk.meshphysical_vert,
  10104. fragmentShader: ShaderChunk.meshphysical_frag
  10105. };
  10106. /**
  10107. * @author mrdoob / http://mrdoob.com/
  10108. */
  10109. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  10110. var clearColor = new Color(0x000000);
  10111. var clearAlpha = 0;
  10112. var planeMesh;
  10113. var boxMesh;
  10114. var currentBackground = null;
  10115. var currentBackgroundVersion = 0;
  10116. var currentTonemapping = null;
  10117. function render(renderList, scene, camera, forceClear) {
  10118. var background = scene.background; // Ignore background in AR
  10119. // TODO: Reconsider this.
  10120. var xr = renderer.xr;
  10121. var session = xr.getSession && xr.getSession();
  10122. if (session && session.environmentBlendMode === 'additive') {
  10123. background = null;
  10124. }
  10125. if (background === null) {
  10126. setClear(clearColor, clearAlpha);
  10127. } else if (background && background.isColor) {
  10128. setClear(background, 1);
  10129. forceClear = true;
  10130. }
  10131. if (renderer.autoClear || forceClear) {
  10132. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  10133. }
  10134. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  10135. if (boxMesh === undefined) {
  10136. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  10137. type: 'BackgroundCubeMaterial',
  10138. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  10139. vertexShader: ShaderLib.cube.vertexShader,
  10140. fragmentShader: ShaderLib.cube.fragmentShader,
  10141. side: BackSide,
  10142. depthTest: false,
  10143. depthWrite: false,
  10144. fog: false
  10145. }));
  10146. boxMesh.geometry.deleteAttribute('normal');
  10147. boxMesh.geometry.deleteAttribute('uv');
  10148. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  10149. this.matrixWorld.copyPosition(camera.matrixWorld);
  10150. }; // enable code injection for non-built-in material
  10151. Object.defineProperty(boxMesh.material, 'envMap', {
  10152. get: function () {
  10153. return this.uniforms.envMap.value;
  10154. }
  10155. });
  10156. objects.update(boxMesh);
  10157. }
  10158. var texture = background.isWebGLCubeRenderTarget ? background.texture : background;
  10159. boxMesh.material.uniforms.envMap.value = texture;
  10160. boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? -1 : 1;
  10161. if (currentBackground !== background || currentBackgroundVersion !== texture.version || currentTonemapping !== renderer.toneMapping) {
  10162. boxMesh.material.needsUpdate = true;
  10163. currentBackground = background;
  10164. currentBackgroundVersion = texture.version;
  10165. currentTonemapping = renderer.toneMapping;
  10166. } // push to the pre-sorted opaque render list
  10167. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  10168. } else if (background && background.isTexture) {
  10169. if (planeMesh === undefined) {
  10170. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  10171. type: 'BackgroundMaterial',
  10172. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  10173. vertexShader: ShaderLib.background.vertexShader,
  10174. fragmentShader: ShaderLib.background.fragmentShader,
  10175. side: FrontSide,
  10176. depthTest: false,
  10177. depthWrite: false,
  10178. fog: false
  10179. }));
  10180. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  10181. Object.defineProperty(planeMesh.material, 'map', {
  10182. get: function () {
  10183. return this.uniforms.t2D.value;
  10184. }
  10185. });
  10186. objects.update(planeMesh);
  10187. }
  10188. planeMesh.material.uniforms.t2D.value = background;
  10189. if (background.matrixAutoUpdate === true) {
  10190. background.updateMatrix();
  10191. }
  10192. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  10193. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  10194. planeMesh.material.needsUpdate = true;
  10195. currentBackground = background;
  10196. currentBackgroundVersion = background.version;
  10197. currentTonemapping = renderer.toneMapping;
  10198. } // push to the pre-sorted opaque render list
  10199. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  10200. }
  10201. }
  10202. function setClear(color, alpha) {
  10203. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  10204. }
  10205. return {
  10206. getClearColor: function () {
  10207. return clearColor;
  10208. },
  10209. setClearColor: function (color, alpha) {
  10210. clearColor.set(color);
  10211. clearAlpha = alpha !== undefined ? alpha : 1;
  10212. setClear(clearColor, clearAlpha);
  10213. },
  10214. getClearAlpha: function () {
  10215. return clearAlpha;
  10216. },
  10217. setClearAlpha: function (alpha) {
  10218. clearAlpha = alpha;
  10219. setClear(clearColor, clearAlpha);
  10220. },
  10221. render: render
  10222. };
  10223. }
  10224. /**
  10225. * @author mrdoob / http://mrdoob.com/
  10226. */
  10227. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  10228. var isWebGL2 = capabilities.isWebGL2;
  10229. var mode;
  10230. function setMode(value) {
  10231. mode = value;
  10232. }
  10233. function render(start, count) {
  10234. gl.drawArrays(mode, start, count);
  10235. info.update(count, mode);
  10236. }
  10237. function renderInstances(geometry, start, count, primcount) {
  10238. if (primcount === 0) return;
  10239. var extension, methodName;
  10240. if (isWebGL2) {
  10241. extension = gl;
  10242. methodName = 'drawArraysInstanced';
  10243. } else {
  10244. extension = extensions.get('ANGLE_instanced_arrays');
  10245. methodName = 'drawArraysInstancedANGLE';
  10246. if (extension === null) {
  10247. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10248. return;
  10249. }
  10250. }
  10251. extension[methodName](mode, start, count, primcount);
  10252. info.update(count, mode, primcount);
  10253. } //
  10254. this.setMode = setMode;
  10255. this.render = render;
  10256. this.renderInstances = renderInstances;
  10257. }
  10258. /**
  10259. * @author mrdoob / http://mrdoob.com/
  10260. */
  10261. function WebGLCapabilities(gl, extensions, parameters) {
  10262. var maxAnisotropy;
  10263. function getMaxAnisotropy() {
  10264. if (maxAnisotropy !== undefined) return maxAnisotropy;
  10265. var extension = extensions.get('EXT_texture_filter_anisotropic');
  10266. if (extension !== null) {
  10267. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  10268. } else {
  10269. maxAnisotropy = 0;
  10270. }
  10271. return maxAnisotropy;
  10272. }
  10273. function getMaxPrecision(precision) {
  10274. if (precision === 'highp') {
  10275. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  10276. return 'highp';
  10277. }
  10278. precision = 'mediump';
  10279. }
  10280. if (precision === 'mediump') {
  10281. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  10282. return 'mediump';
  10283. }
  10284. }
  10285. return 'lowp';
  10286. }
  10287. /* eslint-disable no-undef */
  10288. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  10289. /* eslint-enable no-undef */
  10290. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  10291. var maxPrecision = getMaxPrecision(precision);
  10292. if (maxPrecision !== precision) {
  10293. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  10294. precision = maxPrecision;
  10295. }
  10296. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  10297. var maxTextures = gl.getParameter(34930);
  10298. var maxVertexTextures = gl.getParameter(35660);
  10299. var maxTextureSize = gl.getParameter(3379);
  10300. var maxCubemapSize = gl.getParameter(34076);
  10301. var maxAttributes = gl.getParameter(34921);
  10302. var maxVertexUniforms = gl.getParameter(36347);
  10303. var maxVaryings = gl.getParameter(36348);
  10304. var maxFragmentUniforms = gl.getParameter(36349);
  10305. var vertexTextures = maxVertexTextures > 0;
  10306. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  10307. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  10308. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  10309. return {
  10310. isWebGL2: isWebGL2,
  10311. getMaxAnisotropy: getMaxAnisotropy,
  10312. getMaxPrecision: getMaxPrecision,
  10313. precision: precision,
  10314. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10315. maxTextures: maxTextures,
  10316. maxVertexTextures: maxVertexTextures,
  10317. maxTextureSize: maxTextureSize,
  10318. maxCubemapSize: maxCubemapSize,
  10319. maxAttributes: maxAttributes,
  10320. maxVertexUniforms: maxVertexUniforms,
  10321. maxVaryings: maxVaryings,
  10322. maxFragmentUniforms: maxFragmentUniforms,
  10323. vertexTextures: vertexTextures,
  10324. floatFragmentTextures: floatFragmentTextures,
  10325. floatVertexTextures: floatVertexTextures,
  10326. maxSamples: maxSamples
  10327. };
  10328. }
  10329. /**
  10330. * @author tschw
  10331. */
  10332. function WebGLClipping() {
  10333. var scope = this,
  10334. globalState = null,
  10335. numGlobalPlanes = 0,
  10336. localClippingEnabled = false,
  10337. renderingShadows = false,
  10338. plane = new Plane(),
  10339. viewNormalMatrix = new Matrix3(),
  10340. uniform = {
  10341. value: null,
  10342. needsUpdate: false
  10343. };
  10344. this.uniform = uniform;
  10345. this.numPlanes = 0;
  10346. this.numIntersection = 0;
  10347. this.init = function (planes, enableLocalClipping, camera) {
  10348. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  10349. // run another frame in order to reset the state:
  10350. numGlobalPlanes !== 0 || localClippingEnabled;
  10351. localClippingEnabled = enableLocalClipping;
  10352. globalState = projectPlanes(planes, camera, 0);
  10353. numGlobalPlanes = planes.length;
  10354. return enabled;
  10355. };
  10356. this.beginShadows = function () {
  10357. renderingShadows = true;
  10358. projectPlanes(null);
  10359. };
  10360. this.endShadows = function () {
  10361. renderingShadows = false;
  10362. resetGlobalState();
  10363. };
  10364. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  10365. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  10366. // there's no local clipping
  10367. if (renderingShadows) {
  10368. // there's no global clipping
  10369. projectPlanes(null);
  10370. } else {
  10371. resetGlobalState();
  10372. }
  10373. } else {
  10374. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10375. lGlobal = nGlobal * 4,
  10376. dstArray = cache.clippingState || null;
  10377. uniform.value = dstArray; // ensure unique state
  10378. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  10379. for (var i = 0; i !== lGlobal; ++i) {
  10380. dstArray[i] = globalState[i];
  10381. }
  10382. cache.clippingState = dstArray;
  10383. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  10384. this.numPlanes += nGlobal;
  10385. }
  10386. };
  10387. function resetGlobalState() {
  10388. if (uniform.value !== globalState) {
  10389. uniform.value = globalState;
  10390. uniform.needsUpdate = numGlobalPlanes > 0;
  10391. }
  10392. scope.numPlanes = numGlobalPlanes;
  10393. scope.numIntersection = 0;
  10394. }
  10395. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  10396. var nPlanes = planes !== null ? planes.length : 0,
  10397. dstArray = null;
  10398. if (nPlanes !== 0) {
  10399. dstArray = uniform.value;
  10400. if (skipTransform !== true || dstArray === null) {
  10401. var flatSize = dstOffset + nPlanes * 4,
  10402. viewMatrix = camera.matrixWorldInverse;
  10403. viewNormalMatrix.getNormalMatrix(viewMatrix);
  10404. if (dstArray === null || dstArray.length < flatSize) {
  10405. dstArray = new Float32Array(flatSize);
  10406. }
  10407. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  10408. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  10409. plane.normal.toArray(dstArray, i4);
  10410. dstArray[i4 + 3] = plane.constant;
  10411. }
  10412. }
  10413. uniform.value = dstArray;
  10414. uniform.needsUpdate = true;
  10415. }
  10416. scope.numPlanes = nPlanes;
  10417. scope.numIntersection = 0;
  10418. return dstArray;
  10419. }
  10420. }
  10421. /**
  10422. * @author mrdoob / http://mrdoob.com/
  10423. */
  10424. function WebGLExtensions(gl) {
  10425. var extensions = {};
  10426. return {
  10427. get: function (name) {
  10428. if (extensions[name] !== undefined) {
  10429. return extensions[name];
  10430. }
  10431. var extension;
  10432. switch (name) {
  10433. case 'WEBGL_depth_texture':
  10434. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10435. break;
  10436. case 'EXT_texture_filter_anisotropic':
  10437. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10438. break;
  10439. case 'WEBGL_compressed_texture_s3tc':
  10440. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10441. break;
  10442. case 'WEBGL_compressed_texture_pvrtc':
  10443. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10444. break;
  10445. default:
  10446. extension = gl.getExtension(name);
  10447. }
  10448. if (extension === null) {
  10449. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10450. }
  10451. extensions[name] = extension;
  10452. return extension;
  10453. }
  10454. };
  10455. }
  10456. /**
  10457. * @author mrdoob / http://mrdoob.com/
  10458. */
  10459. function WebGLGeometries(gl, attributes, info) {
  10460. var geometries = new WeakMap();
  10461. var wireframeAttributes = new WeakMap();
  10462. function onGeometryDispose(event) {
  10463. var geometry = event.target;
  10464. var buffergeometry = geometries.get(geometry);
  10465. if (buffergeometry.index !== null) {
  10466. attributes.remove(buffergeometry.index);
  10467. }
  10468. for (var name in buffergeometry.attributes) {
  10469. attributes.remove(buffergeometry.attributes[name]);
  10470. }
  10471. geometry.removeEventListener('dispose', onGeometryDispose);
  10472. geometries.delete(geometry);
  10473. var attribute = wireframeAttributes.get(buffergeometry);
  10474. if (attribute) {
  10475. attributes.remove(attribute);
  10476. wireframeAttributes.delete(buffergeometry);
  10477. } //
  10478. info.memory.geometries--;
  10479. }
  10480. function get(object, geometry) {
  10481. var buffergeometry = geometries.get(geometry);
  10482. if (buffergeometry) return buffergeometry;
  10483. geometry.addEventListener('dispose', onGeometryDispose);
  10484. if (geometry.isBufferGeometry) {
  10485. buffergeometry = geometry;
  10486. } else if (geometry.isGeometry) {
  10487. if (geometry._bufferGeometry === undefined) {
  10488. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10489. }
  10490. buffergeometry = geometry._bufferGeometry;
  10491. }
  10492. geometries.set(geometry, buffergeometry);
  10493. info.memory.geometries++;
  10494. return buffergeometry;
  10495. }
  10496. function update(geometry) {
  10497. var index = geometry.index;
  10498. var geometryAttributes = geometry.attributes;
  10499. if (index !== null) {
  10500. attributes.update(index, 34963);
  10501. }
  10502. for (var name in geometryAttributes) {
  10503. attributes.update(geometryAttributes[name], 34962);
  10504. } // morph targets
  10505. var morphAttributes = geometry.morphAttributes;
  10506. for (var name in morphAttributes) {
  10507. var array = morphAttributes[name];
  10508. for (var i = 0, l = array.length; i < l; i++) {
  10509. attributes.update(array[i], 34962);
  10510. }
  10511. }
  10512. }
  10513. function updateWireframeAttribute(geometry) {
  10514. var indices = [];
  10515. var geometryIndex = geometry.index;
  10516. var geometryPosition = geometry.attributes.position;
  10517. var version = 0;
  10518. if (geometryIndex !== null) {
  10519. var array = geometryIndex.array;
  10520. version = geometryIndex.version;
  10521. for (var i = 0, l = array.length; i < l; i += 3) {
  10522. var a = array[i + 0];
  10523. var b = array[i + 1];
  10524. var c = array[i + 2];
  10525. indices.push(a, b, b, c, c, a);
  10526. }
  10527. } else {
  10528. var array = geometryPosition.array;
  10529. version = geometryPosition.version;
  10530. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10531. var a = i + 0;
  10532. var b = i + 1;
  10533. var c = i + 2;
  10534. indices.push(a, b, b, c, c, a);
  10535. }
  10536. }
  10537. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10538. attribute.version = version;
  10539. attributes.update(attribute, 34963); //
  10540. var previousAttribute = wireframeAttributes.get(geometry);
  10541. if (previousAttribute) attributes.remove(previousAttribute); //
  10542. wireframeAttributes.set(geometry, attribute);
  10543. }
  10544. function getWireframeAttribute(geometry) {
  10545. var currentAttribute = wireframeAttributes.get(geometry);
  10546. if (currentAttribute) {
  10547. var geometryIndex = geometry.index;
  10548. if (geometryIndex !== null) {
  10549. // if the attribute is obsolete, create a new one
  10550. if (currentAttribute.version < geometryIndex.version) {
  10551. updateWireframeAttribute(geometry);
  10552. }
  10553. }
  10554. } else {
  10555. updateWireframeAttribute(geometry);
  10556. }
  10557. return wireframeAttributes.get(geometry);
  10558. }
  10559. return {
  10560. get: get,
  10561. update: update,
  10562. getWireframeAttribute: getWireframeAttribute
  10563. };
  10564. }
  10565. /**
  10566. * @author mrdoob / http://mrdoob.com/
  10567. */
  10568. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10569. var isWebGL2 = capabilities.isWebGL2;
  10570. var mode;
  10571. function setMode(value) {
  10572. mode = value;
  10573. }
  10574. var type, bytesPerElement;
  10575. function setIndex(value) {
  10576. type = value.type;
  10577. bytesPerElement = value.bytesPerElement;
  10578. }
  10579. function render(start, count) {
  10580. gl.drawElements(mode, count, type, start * bytesPerElement);
  10581. info.update(count, mode);
  10582. }
  10583. function renderInstances(geometry, start, count, primcount) {
  10584. if (primcount === 0) return;
  10585. var extension, methodName;
  10586. if (isWebGL2) {
  10587. extension = gl;
  10588. methodName = 'drawElementsInstanced';
  10589. } else {
  10590. extension = extensions.get('ANGLE_instanced_arrays');
  10591. methodName = 'drawElementsInstancedANGLE';
  10592. if (extension === null) {
  10593. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10594. return;
  10595. }
  10596. }
  10597. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10598. info.update(count, mode, primcount);
  10599. } //
  10600. this.setMode = setMode;
  10601. this.setIndex = setIndex;
  10602. this.render = render;
  10603. this.renderInstances = renderInstances;
  10604. }
  10605. /**
  10606. * @author Mugen87 / https://github.com/Mugen87
  10607. */
  10608. function WebGLInfo(gl) {
  10609. var memory = {
  10610. geometries: 0,
  10611. textures: 0
  10612. };
  10613. var render = {
  10614. frame: 0,
  10615. calls: 0,
  10616. triangles: 0,
  10617. points: 0,
  10618. lines: 0
  10619. };
  10620. function update(count, mode, instanceCount) {
  10621. instanceCount = instanceCount || 1;
  10622. render.calls++;
  10623. switch (mode) {
  10624. case 4:
  10625. render.triangles += instanceCount * (count / 3);
  10626. break;
  10627. case 1:
  10628. render.lines += instanceCount * (count / 2);
  10629. break;
  10630. case 3:
  10631. render.lines += instanceCount * (count - 1);
  10632. break;
  10633. case 2:
  10634. render.lines += instanceCount * count;
  10635. break;
  10636. case 0:
  10637. render.points += instanceCount * count;
  10638. break;
  10639. default:
  10640. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10641. break;
  10642. }
  10643. }
  10644. function reset() {
  10645. render.frame++;
  10646. render.calls = 0;
  10647. render.triangles = 0;
  10648. render.points = 0;
  10649. render.lines = 0;
  10650. }
  10651. return {
  10652. memory: memory,
  10653. render: render,
  10654. programs: null,
  10655. autoReset: true,
  10656. reset: reset,
  10657. update: update
  10658. };
  10659. }
  10660. /**
  10661. * @author mrdoob / http://mrdoob.com/
  10662. */
  10663. function absNumericalSort(a, b) {
  10664. return Math.abs(b[1]) - Math.abs(a[1]);
  10665. }
  10666. function WebGLMorphtargets(gl) {
  10667. var influencesList = {};
  10668. var morphInfluences = new Float32Array(8);
  10669. function update(object, geometry, material, program) {
  10670. var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10671. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10672. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10673. var influences = influencesList[geometry.id];
  10674. if (influences === undefined) {
  10675. // initialise list
  10676. influences = [];
  10677. for (var i = 0; i < length; i++) {
  10678. influences[i] = [i, 0];
  10679. }
  10680. influencesList[geometry.id] = influences;
  10681. }
  10682. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10683. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  10684. for (var i = 0; i < length; i++) {
  10685. var influence = influences[i];
  10686. if (influence[1] !== 0) {
  10687. if (morphTargets) geometry.deleteAttribute('morphTarget' + i);
  10688. if (morphNormals) geometry.deleteAttribute('morphNormal' + i);
  10689. }
  10690. } // Collect influences
  10691. for (var i = 0; i < length; i++) {
  10692. var influence = influences[i];
  10693. influence[0] = i;
  10694. influence[1] = objectInfluences[i];
  10695. }
  10696. influences.sort(absNumericalSort); // Add morphAttributes
  10697. var morphInfluencesSum = 0;
  10698. for (var i = 0; i < 8; i++) {
  10699. var influence = influences[i];
  10700. if (influence) {
  10701. var index = influence[0];
  10702. var value = influence[1];
  10703. if (value) {
  10704. if (morphTargets) geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10705. if (morphNormals) geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10706. morphInfluences[i] = value;
  10707. morphInfluencesSum += value;
  10708. continue;
  10709. }
  10710. }
  10711. morphInfluences[i] = 0;
  10712. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10713. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10714. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10715. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10716. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10717. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10718. }
  10719. return {
  10720. update: update
  10721. };
  10722. }
  10723. /**
  10724. * @author mrdoob / http://mrdoob.com/
  10725. */
  10726. function WebGLObjects(gl, geometries, attributes, info) {
  10727. var updateMap = new WeakMap();
  10728. function update(object) {
  10729. var frame = info.render.frame;
  10730. var geometry = object.geometry;
  10731. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  10732. if (updateMap.get(buffergeometry) !== frame) {
  10733. if (geometry.isGeometry) {
  10734. buffergeometry.updateFromObject(object);
  10735. }
  10736. geometries.update(buffergeometry);
  10737. updateMap.set(buffergeometry, frame);
  10738. }
  10739. if (object.isInstancedMesh) {
  10740. attributes.update(object.instanceMatrix, 34962);
  10741. }
  10742. return buffergeometry;
  10743. }
  10744. function dispose() {
  10745. updateMap = new WeakMap();
  10746. }
  10747. return {
  10748. update: update,
  10749. dispose: dispose
  10750. };
  10751. }
  10752. /**
  10753. * @author mrdoob / http://mrdoob.com/
  10754. */
  10755. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  10756. images = images !== undefined ? images : [];
  10757. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  10758. format = format !== undefined ? format : RGBFormat;
  10759. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  10760. this.flipY = false;
  10761. }
  10762. CubeTexture.prototype = Object.create(Texture.prototype);
  10763. CubeTexture.prototype.constructor = CubeTexture;
  10764. CubeTexture.prototype.isCubeTexture = true;
  10765. Object.defineProperty(CubeTexture.prototype, 'images', {
  10766. get: function () {
  10767. return this.image;
  10768. },
  10769. set: function (value) {
  10770. this.image = value;
  10771. }
  10772. });
  10773. /**
  10774. * @author Takahiro https://github.com/takahirox
  10775. */
  10776. function DataTexture2DArray(data, width, height, depth) {
  10777. Texture.call(this, null);
  10778. this.image = {
  10779. data: data || null,
  10780. width: width || 1,
  10781. height: height || 1,
  10782. depth: depth || 1
  10783. };
  10784. this.magFilter = NearestFilter;
  10785. this.minFilter = NearestFilter;
  10786. this.wrapR = ClampToEdgeWrapping;
  10787. this.generateMipmaps = false;
  10788. this.flipY = false;
  10789. this.needsUpdate = true;
  10790. }
  10791. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10792. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10793. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10794. /**
  10795. * @author Artur Trzesiok
  10796. */
  10797. function DataTexture3D(data, width, height, depth) {
  10798. // We're going to add .setXXX() methods for setting properties later.
  10799. // Users can still set in DataTexture3D directly.
  10800. //
  10801. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  10802. // texture.anisotropy = 16;
  10803. //
  10804. // See #14839
  10805. Texture.call(this, null);
  10806. this.image = {
  10807. data: data || null,
  10808. width: width || 1,
  10809. height: height || 1,
  10810. depth: depth || 1
  10811. };
  10812. this.magFilter = NearestFilter;
  10813. this.minFilter = NearestFilter;
  10814. this.wrapR = ClampToEdgeWrapping;
  10815. this.generateMipmaps = false;
  10816. this.flipY = false;
  10817. this.needsUpdate = true;
  10818. }
  10819. DataTexture3D.prototype = Object.create(Texture.prototype);
  10820. DataTexture3D.prototype.constructor = DataTexture3D;
  10821. DataTexture3D.prototype.isDataTexture3D = true;
  10822. /**
  10823. * @author tschw
  10824. * @author Mugen87 / https://github.com/Mugen87
  10825. * @author mrdoob / http://mrdoob.com/
  10826. *
  10827. * Uniforms of a program.
  10828. * Those form a tree structure with a special top-level container for the root,
  10829. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10830. *
  10831. *
  10832. * Properties of inner nodes including the top-level container:
  10833. *
  10834. * .seq - array of nested uniforms
  10835. * .map - nested uniforms by name
  10836. *
  10837. *
  10838. * Methods of all nodes except the top-level container:
  10839. *
  10840. * .setValue( gl, value, [textures] )
  10841. *
  10842. * uploads a uniform value(s)
  10843. * the 'textures' parameter is needed for sampler uniforms
  10844. *
  10845. *
  10846. * Static methods of the top-level container (textures factorizations):
  10847. *
  10848. * .upload( gl, seq, values, textures )
  10849. *
  10850. * sets uniforms in 'seq' to 'values[id].value'
  10851. *
  10852. * .seqWithValue( seq, values ) : filteredSeq
  10853. *
  10854. * filters 'seq' entries with corresponding entry in values
  10855. *
  10856. *
  10857. * Methods of the top-level container (textures factorizations):
  10858. *
  10859. * .setValue( gl, name, value, textures )
  10860. *
  10861. * sets uniform with name 'name' to 'value'
  10862. *
  10863. * .setOptional( gl, obj, prop )
  10864. *
  10865. * like .set for an optional property of the object
  10866. *
  10867. */
  10868. var emptyTexture = new Texture();
  10869. var emptyTexture2dArray = new DataTexture2DArray();
  10870. var emptyTexture3d = new DataTexture3D();
  10871. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10872. // Array Caches (provide typed arrays for temporary by size)
  10873. var arrayCacheF32 = [];
  10874. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10875. var mat4array = new Float32Array(16);
  10876. var mat3array = new Float32Array(9);
  10877. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10878. function flatten(array, nBlocks, blockSize) {
  10879. var firstElem = array[0];
  10880. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10881. // see http://jacksondunstan.com/articles/983
  10882. var n = nBlocks * blockSize,
  10883. r = arrayCacheF32[n];
  10884. if (r === undefined) {
  10885. r = new Float32Array(n);
  10886. arrayCacheF32[n] = r;
  10887. }
  10888. if (nBlocks !== 0) {
  10889. firstElem.toArray(r, 0);
  10890. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  10891. offset += blockSize;
  10892. array[i].toArray(r, offset);
  10893. }
  10894. }
  10895. return r;
  10896. }
  10897. function arraysEqual(a, b) {
  10898. if (a.length !== b.length) return false;
  10899. for (var i = 0, l = a.length; i < l; i++) {
  10900. if (a[i] !== b[i]) return false;
  10901. }
  10902. return true;
  10903. }
  10904. function copyArray(a, b) {
  10905. for (var i = 0, l = b.length; i < l; i++) {
  10906. a[i] = b[i];
  10907. }
  10908. } // Texture unit allocation
  10909. function allocTexUnits(textures, n) {
  10910. var r = arrayCacheI32[n];
  10911. if (r === undefined) {
  10912. r = new Int32Array(n);
  10913. arrayCacheI32[n] = r;
  10914. }
  10915. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  10916. return r;
  10917. } // --- Setters ---
  10918. // Note: Defining these methods externally, because they come in a bunch
  10919. // and this way their names minify.
  10920. // Single scalar
  10921. function setValueV1f(gl, v) {
  10922. var cache = this.cache;
  10923. if (cache[0] === v) return;
  10924. gl.uniform1f(this.addr, v);
  10925. cache[0] = v;
  10926. } // Single float vector (from flat array or THREE.VectorN)
  10927. function setValueV2f(gl, v) {
  10928. var cache = this.cache;
  10929. if (v.x !== undefined) {
  10930. if (cache[0] !== v.x || cache[1] !== v.y) {
  10931. gl.uniform2f(this.addr, v.x, v.y);
  10932. cache[0] = v.x;
  10933. cache[1] = v.y;
  10934. }
  10935. } else {
  10936. if (arraysEqual(cache, v)) return;
  10937. gl.uniform2fv(this.addr, v);
  10938. copyArray(cache, v);
  10939. }
  10940. }
  10941. function setValueV3f(gl, v) {
  10942. var cache = this.cache;
  10943. if (v.x !== undefined) {
  10944. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10945. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10946. cache[0] = v.x;
  10947. cache[1] = v.y;
  10948. cache[2] = v.z;
  10949. }
  10950. } else if (v.r !== undefined) {
  10951. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10952. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10953. cache[0] = v.r;
  10954. cache[1] = v.g;
  10955. cache[2] = v.b;
  10956. }
  10957. } else {
  10958. if (arraysEqual(cache, v)) return;
  10959. gl.uniform3fv(this.addr, v);
  10960. copyArray(cache, v);
  10961. }
  10962. }
  10963. function setValueV4f(gl, v) {
  10964. var cache = this.cache;
  10965. if (v.x !== undefined) {
  10966. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10967. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10968. cache[0] = v.x;
  10969. cache[1] = v.y;
  10970. cache[2] = v.z;
  10971. cache[3] = v.w;
  10972. }
  10973. } else {
  10974. if (arraysEqual(cache, v)) return;
  10975. gl.uniform4fv(this.addr, v);
  10976. copyArray(cache, v);
  10977. }
  10978. } // Single matrix (from flat array or MatrixN)
  10979. function setValueM2(gl, v) {
  10980. var cache = this.cache;
  10981. var elements = v.elements;
  10982. if (elements === undefined) {
  10983. if (arraysEqual(cache, v)) return;
  10984. gl.uniformMatrix2fv(this.addr, false, v);
  10985. copyArray(cache, v);
  10986. } else {
  10987. if (arraysEqual(cache, elements)) return;
  10988. mat2array.set(elements);
  10989. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10990. copyArray(cache, elements);
  10991. }
  10992. }
  10993. function setValueM3(gl, v) {
  10994. var cache = this.cache;
  10995. var elements = v.elements;
  10996. if (elements === undefined) {
  10997. if (arraysEqual(cache, v)) return;
  10998. gl.uniformMatrix3fv(this.addr, false, v);
  10999. copyArray(cache, v);
  11000. } else {
  11001. if (arraysEqual(cache, elements)) return;
  11002. mat3array.set(elements);
  11003. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11004. copyArray(cache, elements);
  11005. }
  11006. }
  11007. function setValueM4(gl, v) {
  11008. var cache = this.cache;
  11009. var elements = v.elements;
  11010. if (elements === undefined) {
  11011. if (arraysEqual(cache, v)) return;
  11012. gl.uniformMatrix4fv(this.addr, false, v);
  11013. copyArray(cache, v);
  11014. } else {
  11015. if (arraysEqual(cache, elements)) return;
  11016. mat4array.set(elements);
  11017. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11018. copyArray(cache, elements);
  11019. }
  11020. } // Single texture (2D / Cube)
  11021. function setValueT1(gl, v, textures) {
  11022. var cache = this.cache;
  11023. var unit = textures.allocateTextureUnit();
  11024. if (cache[0] !== unit) {
  11025. gl.uniform1i(this.addr, unit);
  11026. cache[0] = unit;
  11027. }
  11028. textures.safeSetTexture2D(v || emptyTexture, unit);
  11029. }
  11030. function setValueT2DArray1(gl, v, textures) {
  11031. var cache = this.cache;
  11032. var unit = textures.allocateTextureUnit();
  11033. if (cache[0] !== unit) {
  11034. gl.uniform1i(this.addr, unit);
  11035. cache[0] = unit;
  11036. }
  11037. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11038. }
  11039. function setValueT3D1(gl, v, textures) {
  11040. var cache = this.cache;
  11041. var unit = textures.allocateTextureUnit();
  11042. if (cache[0] !== unit) {
  11043. gl.uniform1i(this.addr, unit);
  11044. cache[0] = unit;
  11045. }
  11046. textures.setTexture3D(v || emptyTexture3d, unit);
  11047. }
  11048. function setValueT6(gl, v, textures) {
  11049. var cache = this.cache;
  11050. var unit = textures.allocateTextureUnit();
  11051. if (cache[0] !== unit) {
  11052. gl.uniform1i(this.addr, unit);
  11053. cache[0] = unit;
  11054. }
  11055. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11056. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11057. function setValueV1i(gl, v) {
  11058. var cache = this.cache;
  11059. if (cache[0] === v) return;
  11060. gl.uniform1i(this.addr, v);
  11061. cache[0] = v;
  11062. }
  11063. function setValueV2i(gl, v) {
  11064. var cache = this.cache;
  11065. if (arraysEqual(cache, v)) return;
  11066. gl.uniform2iv(this.addr, v);
  11067. copyArray(cache, v);
  11068. }
  11069. function setValueV3i(gl, v) {
  11070. var cache = this.cache;
  11071. if (arraysEqual(cache, v)) return;
  11072. gl.uniform3iv(this.addr, v);
  11073. copyArray(cache, v);
  11074. }
  11075. function setValueV4i(gl, v) {
  11076. var cache = this.cache;
  11077. if (arraysEqual(cache, v)) return;
  11078. gl.uniform4iv(this.addr, v);
  11079. copyArray(cache, v);
  11080. } // uint
  11081. function setValueV1ui(gl, v) {
  11082. var cache = this.cache;
  11083. if (cache[0] === v) return;
  11084. gl.uniform1ui(this.addr, v);
  11085. cache[0] = v;
  11086. } // Helper to pick the right setter for the singular case
  11087. function getSingularSetter(type) {
  11088. switch (type) {
  11089. case 0x1406:
  11090. return setValueV1f;
  11091. // FLOAT
  11092. case 0x8b50:
  11093. return setValueV2f;
  11094. // _VEC2
  11095. case 0x8b51:
  11096. return setValueV3f;
  11097. // _VEC3
  11098. case 0x8b52:
  11099. return setValueV4f;
  11100. // _VEC4
  11101. case 0x8b5a:
  11102. return setValueM2;
  11103. // _MAT2
  11104. case 0x8b5b:
  11105. return setValueM3;
  11106. // _MAT3
  11107. case 0x8b5c:
  11108. return setValueM4;
  11109. // _MAT4
  11110. case 0x1404:
  11111. case 0x8b56:
  11112. return setValueV1i;
  11113. // INT, BOOL
  11114. case 0x8b53:
  11115. case 0x8b57:
  11116. return setValueV2i;
  11117. // _VEC2
  11118. case 0x8b54:
  11119. case 0x8b58:
  11120. return setValueV3i;
  11121. // _VEC3
  11122. case 0x8b55:
  11123. case 0x8b59:
  11124. return setValueV4i;
  11125. // _VEC4
  11126. case 0x1405:
  11127. return setValueV1ui;
  11128. // UINT
  11129. case 0x8b5e: // SAMPLER_2D
  11130. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11131. case 0x8dca: // INT_SAMPLER_2D
  11132. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11133. case 0x8b62:
  11134. // SAMPLER_2D_SHADOW
  11135. return setValueT1;
  11136. case 0x8b5f: // SAMPLER_3D
  11137. case 0x8dcb: // INT_SAMPLER_3D
  11138. case 0x8dd3:
  11139. // UNSIGNED_INT_SAMPLER_3D
  11140. return setValueT3D1;
  11141. case 0x8b60: // SAMPLER_CUBE
  11142. case 0x8dcc: // INT_SAMPLER_CUBE
  11143. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11144. case 0x8dc5:
  11145. // SAMPLER_CUBE_SHADOW
  11146. return setValueT6;
  11147. case 0x8dc1: // SAMPLER_2D_ARRAY
  11148. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11149. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11150. case 0x8dc4:
  11151. // SAMPLER_2D_ARRAY_SHADOW
  11152. return setValueT2DArray1;
  11153. }
  11154. } // Array of scalars
  11155. function setValueV1fArray(gl, v) {
  11156. gl.uniform1fv(this.addr, v);
  11157. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11158. function setValueV1iArray(gl, v) {
  11159. gl.uniform1iv(this.addr, v);
  11160. }
  11161. function setValueV2iArray(gl, v) {
  11162. gl.uniform2iv(this.addr, v);
  11163. }
  11164. function setValueV3iArray(gl, v) {
  11165. gl.uniform3iv(this.addr, v);
  11166. }
  11167. function setValueV4iArray(gl, v) {
  11168. gl.uniform4iv(this.addr, v);
  11169. } // Array of vectors (flat or from THREE classes)
  11170. function setValueV2fArray(gl, v) {
  11171. var data = flatten(v, this.size, 2);
  11172. gl.uniform2fv(this.addr, data);
  11173. }
  11174. function setValueV3fArray(gl, v) {
  11175. var data = flatten(v, this.size, 3);
  11176. gl.uniform3fv(this.addr, data);
  11177. }
  11178. function setValueV4fArray(gl, v) {
  11179. var data = flatten(v, this.size, 4);
  11180. gl.uniform4fv(this.addr, data);
  11181. } // Array of matrices (flat or from THREE clases)
  11182. function setValueM2Array(gl, v) {
  11183. var data = flatten(v, this.size, 4);
  11184. gl.uniformMatrix2fv(this.addr, false, data);
  11185. }
  11186. function setValueM3Array(gl, v) {
  11187. var data = flatten(v, this.size, 9);
  11188. gl.uniformMatrix3fv(this.addr, false, data);
  11189. }
  11190. function setValueM4Array(gl, v) {
  11191. var data = flatten(v, this.size, 16);
  11192. gl.uniformMatrix4fv(this.addr, false, data);
  11193. } // Array of textures (2D / Cube)
  11194. function setValueT1Array(gl, v, textures) {
  11195. var n = v.length;
  11196. var units = allocTexUnits(textures, n);
  11197. gl.uniform1iv(this.addr, units);
  11198. for (var i = 0; i !== n; ++i) {
  11199. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  11200. }
  11201. }
  11202. function setValueT6Array(gl, v, textures) {
  11203. var n = v.length;
  11204. var units = allocTexUnits(textures, n);
  11205. gl.uniform1iv(this.addr, units);
  11206. for (var i = 0; i !== n; ++i) {
  11207. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  11208. }
  11209. } // Helper to pick the right setter for a pure (bottom-level) array
  11210. function getPureArraySetter(type) {
  11211. switch (type) {
  11212. case 0x1406:
  11213. return setValueV1fArray;
  11214. // FLOAT
  11215. case 0x8b50:
  11216. return setValueV2fArray;
  11217. // _VEC2
  11218. case 0x8b51:
  11219. return setValueV3fArray;
  11220. // _VEC3
  11221. case 0x8b52:
  11222. return setValueV4fArray;
  11223. // _VEC4
  11224. case 0x8b5a:
  11225. return setValueM2Array;
  11226. // _MAT2
  11227. case 0x8b5b:
  11228. return setValueM3Array;
  11229. // _MAT3
  11230. case 0x8b5c:
  11231. return setValueM4Array;
  11232. // _MAT4
  11233. case 0x1404:
  11234. case 0x8b56:
  11235. return setValueV1iArray;
  11236. // INT, BOOL
  11237. case 0x8b53:
  11238. case 0x8b57:
  11239. return setValueV2iArray;
  11240. // _VEC2
  11241. case 0x8b54:
  11242. case 0x8b58:
  11243. return setValueV3iArray;
  11244. // _VEC3
  11245. case 0x8b55:
  11246. case 0x8b59:
  11247. return setValueV4iArray;
  11248. // _VEC4
  11249. case 0x8b5e: // SAMPLER_2D
  11250. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11251. case 0x8dca: // INT_SAMPLER_2D
  11252. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11253. case 0x8b62:
  11254. // SAMPLER_2D_SHADOW
  11255. return setValueT1Array;
  11256. case 0x8b60: // SAMPLER_CUBE
  11257. case 0x8dcc: // INT_SAMPLER_CUBE
  11258. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11259. case 0x8dc5:
  11260. // SAMPLER_CUBE_SHADOW
  11261. return setValueT6Array;
  11262. }
  11263. } // --- Uniform Classes ---
  11264. function SingleUniform(id, activeInfo, addr) {
  11265. this.id = id;
  11266. this.addr = addr;
  11267. this.cache = [];
  11268. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11269. }
  11270. function PureArrayUniform(id, activeInfo, addr) {
  11271. this.id = id;
  11272. this.addr = addr;
  11273. this.cache = [];
  11274. this.size = activeInfo.size;
  11275. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11276. }
  11277. PureArrayUniform.prototype.updateCache = function (data) {
  11278. var cache = this.cache;
  11279. if (data instanceof Float32Array && cache.length !== data.length) {
  11280. this.cache = new Float32Array(data.length);
  11281. }
  11282. copyArray(cache, data);
  11283. };
  11284. function StructuredUniform(id) {
  11285. this.id = id;
  11286. this.seq = [];
  11287. this.map = {};
  11288. }
  11289. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11290. var seq = this.seq;
  11291. for (var i = 0, n = seq.length; i !== n; ++i) {
  11292. var u = seq[i];
  11293. u.setValue(gl, value[u.id], textures);
  11294. }
  11295. }; // --- Top-level ---
  11296. // Parser - builds up the property tree from the path strings
  11297. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  11298. // - the identifier (member name or array index)
  11299. // - followed by an optional right bracket (found when array index)
  11300. // - followed by an optional left bracket or dot (type of subscript)
  11301. //
  11302. // Note: These portions can be read in a non-overlapping fashion and
  11303. // allow straightforward parsing of the hierarchy that WebGL encodes
  11304. // in the uniform names.
  11305. function addUniform(container, uniformObject) {
  11306. container.seq.push(uniformObject);
  11307. container.map[uniformObject.id] = uniformObject;
  11308. }
  11309. function parseUniform(activeInfo, addr, container) {
  11310. var path = activeInfo.name,
  11311. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11312. RePathPart.lastIndex = 0;
  11313. while (true) {
  11314. var match = RePathPart.exec(path),
  11315. matchEnd = RePathPart.lastIndex,
  11316. id = match[1],
  11317. idIsIndex = match[2] === ']',
  11318. subscript = match[3];
  11319. if (idIsIndex) id = id | 0; // convert to integer
  11320. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11321. // bare name or "pure" bottom-level array "[0]" suffix
  11322. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11323. break;
  11324. } else {
  11325. // step into inner node / create it in case it doesn't exist
  11326. var map = container.map,
  11327. next = map[id];
  11328. if (next === undefined) {
  11329. next = new StructuredUniform(id);
  11330. addUniform(container, next);
  11331. }
  11332. container = next;
  11333. }
  11334. }
  11335. } // Root Container
  11336. function WebGLUniforms(gl, program) {
  11337. this.seq = [];
  11338. this.map = {};
  11339. var n = gl.getProgramParameter(program, 35718);
  11340. for (var i = 0; i < n; ++i) {
  11341. var info = gl.getActiveUniform(program, i),
  11342. addr = gl.getUniformLocation(program, info.name);
  11343. parseUniform(info, addr, this);
  11344. }
  11345. }
  11346. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11347. var u = this.map[name];
  11348. if (u !== undefined) u.setValue(gl, value, textures);
  11349. };
  11350. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11351. var v = object[name];
  11352. if (v !== undefined) this.setValue(gl, name, v);
  11353. }; // Static interface
  11354. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11355. for (var i = 0, n = seq.length; i !== n; ++i) {
  11356. var u = seq[i],
  11357. v = values[u.id];
  11358. if (v.needsUpdate !== false) {
  11359. // note: always updating when .needsUpdate is undefined
  11360. u.setValue(gl, v.value, textures);
  11361. }
  11362. }
  11363. };
  11364. WebGLUniforms.seqWithValue = function (seq, values) {
  11365. var r = [];
  11366. for (var i = 0, n = seq.length; i !== n; ++i) {
  11367. var u = seq[i];
  11368. if (u.id in values) r.push(u);
  11369. }
  11370. return r;
  11371. };
  11372. /**
  11373. * @author mrdoob / http://mrdoob.com/
  11374. */
  11375. function WebGLShader(gl, type, string) {
  11376. var shader = gl.createShader(type);
  11377. gl.shaderSource(shader, string);
  11378. gl.compileShader(shader);
  11379. return shader;
  11380. }
  11381. /**
  11382. * @author mrdoob / http://mrdoob.com/
  11383. */
  11384. var programIdCount = 0;
  11385. function addLineNumbers(string) {
  11386. var lines = string.split('\n');
  11387. for (var i = 0; i < lines.length; i++) {
  11388. lines[i] = i + 1 + ': ' + lines[i];
  11389. }
  11390. return lines.join('\n');
  11391. }
  11392. function getEncodingComponents(encoding) {
  11393. switch (encoding) {
  11394. case LinearEncoding:
  11395. return ['Linear', '( value )'];
  11396. case sRGBEncoding:
  11397. return ['sRGB', '( value )'];
  11398. case RGBEEncoding:
  11399. return ['RGBE', '( value )'];
  11400. case RGBM7Encoding:
  11401. return ['RGBM', '( value, 7.0 )'];
  11402. case RGBM16Encoding:
  11403. return ['RGBM', '( value, 16.0 )'];
  11404. case RGBDEncoding:
  11405. return ['RGBD', '( value, 256.0 )'];
  11406. case GammaEncoding:
  11407. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11408. case LogLuvEncoding:
  11409. return ['LogLuv', '( value )'];
  11410. default:
  11411. throw new Error('unsupported encoding: ' + encoding);
  11412. }
  11413. }
  11414. function getShaderErrors(gl, shader, type) {
  11415. var status = gl.getShaderParameter(shader, 35713);
  11416. var log = gl.getShaderInfoLog(shader).trim();
  11417. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  11418. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11419. var source = gl.getShaderSource(shader);
  11420. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  11421. }
  11422. function getTexelDecodingFunction(functionName, encoding) {
  11423. var components = getEncodingComponents(encoding);
  11424. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11425. }
  11426. function getTexelEncodingFunction(functionName, encoding) {
  11427. var components = getEncodingComponents(encoding);
  11428. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11429. }
  11430. function getToneMappingFunction(functionName, toneMapping) {
  11431. var toneMappingName;
  11432. switch (toneMapping) {
  11433. case LinearToneMapping:
  11434. toneMappingName = 'Linear';
  11435. break;
  11436. case ReinhardToneMapping:
  11437. toneMappingName = 'Reinhard';
  11438. break;
  11439. case Uncharted2ToneMapping:
  11440. toneMappingName = 'Uncharted2';
  11441. break;
  11442. case CineonToneMapping:
  11443. toneMappingName = 'OptimizedCineon';
  11444. break;
  11445. case ACESFilmicToneMapping:
  11446. toneMappingName = 'ACESFilmic';
  11447. break;
  11448. default:
  11449. throw new Error('unsupported toneMapping: ' + toneMapping);
  11450. }
  11451. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11452. }
  11453. function generateExtensions(parameters) {
  11454. var 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' : ''];
  11455. return chunks.filter(filterEmptyLine).join('\n');
  11456. }
  11457. function generateDefines(defines) {
  11458. var chunks = [];
  11459. for (var name in defines) {
  11460. var value = defines[name];
  11461. if (value === false) continue;
  11462. chunks.push('#define ' + name + ' ' + value);
  11463. }
  11464. return chunks.join('\n');
  11465. }
  11466. function fetchAttributeLocations(gl, program) {
  11467. var attributes = {};
  11468. var n = gl.getProgramParameter(program, 35721);
  11469. for (var i = 0; i < n; i++) {
  11470. var info = gl.getActiveAttrib(program, i);
  11471. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11472. attributes[name] = gl.getAttribLocation(program, name);
  11473. }
  11474. return attributes;
  11475. }
  11476. function filterEmptyLine(string) {
  11477. return string !== '';
  11478. }
  11479. function replaceLightNums(string, parameters) {
  11480. 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);
  11481. }
  11482. function replaceClippingPlaneNums(string, parameters) {
  11483. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11484. } // Resolve Includes
  11485. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11486. function resolveIncludes(string) {
  11487. return string.replace(includePattern, includeReplacer);
  11488. }
  11489. function includeReplacer(match, include) {
  11490. var string = ShaderChunk[include];
  11491. if (string === undefined) {
  11492. throw new Error('Can not resolve #include <' + include + '>');
  11493. }
  11494. return resolveIncludes(string);
  11495. } // Unroll Loops
  11496. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11497. var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;
  11498. function unrollLoops(string) {
  11499. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11500. }
  11501. function deprecatedLoopReplacer(match, start, end, snippet) {
  11502. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11503. return loopReplacer(match, start, end, snippet);
  11504. }
  11505. function loopReplacer(match, start, end, snippet) {
  11506. var string = '';
  11507. for (var i = parseInt(start); i < parseInt(end); i++) {
  11508. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11509. }
  11510. return string;
  11511. } //
  11512. function generatePrecision(parameters) {
  11513. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11514. if (parameters.precision === "highp") {
  11515. precisionstring += "\n#define HIGH_PRECISION";
  11516. } else if (parameters.precision === "mediump") {
  11517. precisionstring += "\n#define MEDIUM_PRECISION";
  11518. } else if (parameters.precision === "lowp") {
  11519. precisionstring += "\n#define LOW_PRECISION";
  11520. }
  11521. return precisionstring;
  11522. }
  11523. function generateShadowMapTypeDefine(parameters) {
  11524. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11525. if (parameters.shadowMapType === PCFShadowMap) {
  11526. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11527. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11528. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11529. } else if (parameters.shadowMapType === VSMShadowMap) {
  11530. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11531. }
  11532. return shadowMapTypeDefine;
  11533. }
  11534. function generateEnvMapTypeDefine(parameters) {
  11535. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11536. if (parameters.envMap) {
  11537. switch (parameters.envMapMode) {
  11538. case CubeReflectionMapping:
  11539. case CubeRefractionMapping:
  11540. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11541. break;
  11542. case CubeUVReflectionMapping:
  11543. case CubeUVRefractionMapping:
  11544. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11545. break;
  11546. case EquirectangularReflectionMapping:
  11547. case EquirectangularRefractionMapping:
  11548. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  11549. break;
  11550. case SphericalReflectionMapping:
  11551. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  11552. break;
  11553. }
  11554. }
  11555. return envMapTypeDefine;
  11556. }
  11557. function generateEnvMapModeDefine(parameters) {
  11558. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11559. if (parameters.envMap) {
  11560. switch (parameters.envMapMode) {
  11561. case CubeRefractionMapping:
  11562. case EquirectangularRefractionMapping:
  11563. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11564. break;
  11565. }
  11566. }
  11567. return envMapModeDefine;
  11568. }
  11569. function generateEnvMapBlendingDefine(parameters) {
  11570. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11571. if (parameters.envMap) {
  11572. switch (parameters.combine) {
  11573. case MultiplyOperation:
  11574. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11575. break;
  11576. case MixOperation:
  11577. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11578. break;
  11579. case AddOperation:
  11580. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11581. break;
  11582. }
  11583. }
  11584. return envMapBlendingDefine;
  11585. }
  11586. function WebGLProgram(renderer, cacheKey, parameters) {
  11587. var gl = renderer.getContext();
  11588. var defines = parameters.defines;
  11589. var vertexShader = parameters.vertexShader;
  11590. var fragmentShader = parameters.fragmentShader;
  11591. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11592. var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11593. var envMapModeDefine = generateEnvMapModeDefine(parameters);
  11594. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11595. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11596. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11597. var customDefines = generateDefines(defines);
  11598. var program = gl.createProgram();
  11599. var prefixVertex, prefixFragment;
  11600. if (parameters.isRawShaderMaterial) {
  11601. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11602. if (prefixVertex.length > 0) {
  11603. prefixVertex += '\n';
  11604. }
  11605. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11606. if (prefixFragment.length > 0) {
  11607. prefixFragment += '\n';
  11608. }
  11609. } else {
  11610. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', 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.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', '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');
  11611. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11612. '#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.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#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
  11613. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ? ShaderChunk['encodings_pars_fragment'] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  11614. parameters.mapEncoding ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcapEncoding ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMapEncoding ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMapEncoding ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', parameters.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11615. }
  11616. vertexShader = resolveIncludes(vertexShader);
  11617. vertexShader = replaceLightNums(vertexShader, parameters);
  11618. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11619. fragmentShader = resolveIncludes(fragmentShader);
  11620. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11621. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11622. vertexShader = unrollLoops(vertexShader);
  11623. fragmentShader = unrollLoops(fragmentShader);
  11624. if (parameters.isWebGL2 && !parameters.isRawShaderMaterial) {
  11625. var isGLSL3ShaderMaterial = false;
  11626. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  11627. if (parameters.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  11628. isGLSL3ShaderMaterial = true;
  11629. vertexShader = vertexShader.replace(versionRegex, '');
  11630. fragmentShader = fragmentShader.replace(versionRegex, '');
  11631. } // GLSL 3.0 conversion
  11632. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11633. prefixFragment = ['#version 300 es\n', '#define varying in', isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', isGLSL3ShaderMaterial ? '' : '#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;
  11634. }
  11635. var vertexGlsl = prefixVertex + vertexShader;
  11636. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11637. // console.log( '*FRAGMENT*', fragmentGlsl );
  11638. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11639. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11640. gl.attachShader(program, glVertexShader);
  11641. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11642. if (parameters.index0AttributeName !== undefined) {
  11643. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11644. } else if (parameters.morphTargets === true) {
  11645. // programs with morphTargets displace position out of attribute 0
  11646. gl.bindAttribLocation(program, 0, 'position');
  11647. }
  11648. gl.linkProgram(program); // check for link errors
  11649. if (renderer.debug.checkShaderErrors) {
  11650. var programLog = gl.getProgramInfoLog(program).trim();
  11651. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11652. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11653. var runnable = true;
  11654. var haveDiagnostics = true;
  11655. if (gl.getProgramParameter(program, 35714) === false) {
  11656. runnable = false;
  11657. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11658. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11659. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11660. } else if (programLog !== '') {
  11661. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11662. } else if (vertexLog === '' || fragmentLog === '') {
  11663. haveDiagnostics = false;
  11664. }
  11665. if (haveDiagnostics) {
  11666. this.diagnostics = {
  11667. runnable: runnable,
  11668. programLog: programLog,
  11669. vertexShader: {
  11670. log: vertexLog,
  11671. prefix: prefixVertex
  11672. },
  11673. fragmentShader: {
  11674. log: fragmentLog,
  11675. prefix: prefixFragment
  11676. }
  11677. };
  11678. }
  11679. } // clean up
  11680. gl.detachShader(program, glVertexShader);
  11681. gl.detachShader(program, glFragmentShader);
  11682. gl.deleteShader(glVertexShader);
  11683. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11684. var cachedUniforms;
  11685. this.getUniforms = function () {
  11686. if (cachedUniforms === undefined) {
  11687. cachedUniforms = new WebGLUniforms(gl, program);
  11688. }
  11689. return cachedUniforms;
  11690. }; // set up caching for attribute locations
  11691. var cachedAttributes;
  11692. this.getAttributes = function () {
  11693. if (cachedAttributes === undefined) {
  11694. cachedAttributes = fetchAttributeLocations(gl, program);
  11695. }
  11696. return cachedAttributes;
  11697. }; // free resource
  11698. this.destroy = function () {
  11699. gl.deleteProgram(program);
  11700. this.program = undefined;
  11701. }; //
  11702. this.name = parameters.shaderName;
  11703. this.id = programIdCount++;
  11704. this.cacheKey = cacheKey;
  11705. this.usedTimes = 1;
  11706. this.program = program;
  11707. this.vertexShader = glVertexShader;
  11708. this.fragmentShader = glFragmentShader;
  11709. return this;
  11710. }
  11711. /**
  11712. * @author mrdoob / http://mrdoob.com/
  11713. */
  11714. function WebGLPrograms(renderer, extensions, capabilities) {
  11715. var programs = [];
  11716. var isWebGL2 = capabilities.isWebGL2;
  11717. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11718. var floatVertexTextures = capabilities.floatVertexTextures;
  11719. var precision = capabilities.precision;
  11720. var maxVertexUniforms = capabilities.maxVertexUniforms;
  11721. var vertexTextures = capabilities.vertexTextures;
  11722. var shaderIDs = {
  11723. MeshDepthMaterial: 'depth',
  11724. MeshDistanceMaterial: 'distanceRGBA',
  11725. MeshNormalMaterial: 'normal',
  11726. MeshBasicMaterial: 'basic',
  11727. MeshLambertMaterial: 'lambert',
  11728. MeshPhongMaterial: 'phong',
  11729. MeshToonMaterial: 'toon',
  11730. MeshStandardMaterial: 'physical',
  11731. MeshPhysicalMaterial: 'physical',
  11732. MeshMatcapMaterial: 'matcap',
  11733. LineBasicMaterial: 'basic',
  11734. LineDashedMaterial: 'dashed',
  11735. PointsMaterial: 'points',
  11736. ShadowMaterial: 'shadow',
  11737. SpriteMaterial: 'sprite'
  11738. };
  11739. var parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "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"];
  11740. function getShaderObject(material, shaderID) {
  11741. var shaderobject;
  11742. if (shaderID) {
  11743. var shader = ShaderLib[shaderID];
  11744. shaderobject = {
  11745. name: material.type,
  11746. uniforms: UniformsUtils.clone(shader.uniforms),
  11747. vertexShader: shader.vertexShader,
  11748. fragmentShader: shader.fragmentShader
  11749. };
  11750. } else {
  11751. shaderobject = {
  11752. name: material.type,
  11753. uniforms: material.uniforms,
  11754. vertexShader: material.vertexShader,
  11755. fragmentShader: material.fragmentShader
  11756. };
  11757. }
  11758. return shaderobject;
  11759. }
  11760. function allocateBones(object) {
  11761. var skeleton = object.skeleton;
  11762. var bones = skeleton.bones;
  11763. if (floatVertexTextures) {
  11764. return 1024;
  11765. } else {
  11766. // default for when object is not specified
  11767. // ( for example when prebuilding shader to be used with multiple objects )
  11768. //
  11769. // - leave some extra space for other uniforms
  11770. // - limit here is ANGLE's 254 max uniform vectors
  11771. // (up to 54 should be safe)
  11772. var nVertexUniforms = maxVertexUniforms;
  11773. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11774. var maxBones = Math.min(nVertexMatrices, bones.length);
  11775. if (maxBones < bones.length) {
  11776. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11777. return 0;
  11778. }
  11779. return maxBones;
  11780. }
  11781. }
  11782. function getTextureEncodingFromMap(map) {
  11783. var encoding;
  11784. if (!map) {
  11785. encoding = LinearEncoding;
  11786. } else if (map.isTexture) {
  11787. encoding = map.encoding;
  11788. } else if (map.isWebGLRenderTarget) {
  11789. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11790. encoding = map.texture.encoding;
  11791. }
  11792. return encoding;
  11793. }
  11794. this.getParameters = function (material, lights, shadows, scene, nClipPlanes, nClipIntersection, object) {
  11795. var fog = scene.fog;
  11796. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  11797. var envMap = material.envMap || environment;
  11798. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11799. // (not to blow over maxLights budget)
  11800. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  11801. if (material.precision !== null) {
  11802. precision = capabilities.getMaxPrecision(material.precision);
  11803. if (precision !== material.precision) {
  11804. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11805. }
  11806. }
  11807. var shaderobject = getShaderObject(material, shaderID);
  11808. material.onBeforeCompile(shaderobject, renderer);
  11809. var currentRenderTarget = renderer.getRenderTarget();
  11810. var parameters = {
  11811. isWebGL2: isWebGL2,
  11812. shaderID: shaderID,
  11813. shaderName: shaderobject.name,
  11814. uniforms: shaderobject.uniforms,
  11815. vertexShader: shaderobject.vertexShader,
  11816. fragmentShader: shaderobject.fragmentShader,
  11817. defines: material.defines,
  11818. isRawShaderMaterial: material.isRawShaderMaterial,
  11819. isShaderMaterial: material.isShaderMaterial,
  11820. precision: precision,
  11821. instancing: object.isInstancedMesh === true,
  11822. supportsVertexTextures: vertexTextures,
  11823. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11824. map: !!material.map,
  11825. mapEncoding: getTextureEncodingFromMap(material.map),
  11826. matcap: !!material.matcap,
  11827. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11828. envMap: !!envMap,
  11829. envMapMode: envMap && envMap.mapping,
  11830. envMapEncoding: getTextureEncodingFromMap(envMap),
  11831. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11832. lightMap: !!material.lightMap,
  11833. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11834. aoMap: !!material.aoMap,
  11835. emissiveMap: !!material.emissiveMap,
  11836. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11837. bumpMap: !!material.bumpMap,
  11838. normalMap: !!material.normalMap,
  11839. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11840. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11841. clearcoatMap: !!material.clearcoatMap,
  11842. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11843. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11844. displacementMap: !!material.displacementMap,
  11845. roughnessMap: !!material.roughnessMap,
  11846. metalnessMap: !!material.metalnessMap,
  11847. specularMap: !!material.specularMap,
  11848. alphaMap: !!material.alphaMap,
  11849. gradientMap: !!material.gradientMap,
  11850. sheen: !!material.sheen,
  11851. combine: material.combine,
  11852. vertexTangents: material.normalMap && material.vertexTangents,
  11853. vertexColors: material.vertexColors,
  11854. 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,
  11855. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap) && !!material.displacementMap,
  11856. fog: !!fog,
  11857. useFog: material.fog,
  11858. fogExp2: fog && fog.isFogExp2,
  11859. flatShading: material.flatShading,
  11860. sizeAttenuation: material.sizeAttenuation,
  11861. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11862. skinning: material.skinning && maxBones > 0,
  11863. maxBones: maxBones,
  11864. useVertexTexture: floatVertexTextures,
  11865. morphTargets: material.morphTargets,
  11866. morphNormals: material.morphNormals,
  11867. maxMorphTargets: renderer.maxMorphTargets,
  11868. maxMorphNormals: renderer.maxMorphNormals,
  11869. numDirLights: lights.directional.length,
  11870. numPointLights: lights.point.length,
  11871. numSpotLights: lights.spot.length,
  11872. numRectAreaLights: lights.rectArea.length,
  11873. numHemiLights: lights.hemi.length,
  11874. numDirLightShadows: lights.directionalShadowMap.length,
  11875. numPointLightShadows: lights.pointShadowMap.length,
  11876. numSpotLightShadows: lights.spotShadowMap.length,
  11877. numClippingPlanes: nClipPlanes,
  11878. numClipIntersection: nClipIntersection,
  11879. dithering: material.dithering,
  11880. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11881. shadowMapType: renderer.shadowMap.type,
  11882. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11883. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11884. premultipliedAlpha: material.premultipliedAlpha,
  11885. alphaTest: material.alphaTest,
  11886. doubleSided: material.side === DoubleSide,
  11887. flipSided: material.side === BackSide,
  11888. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11889. index0AttributeName: material.index0AttributeName,
  11890. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11891. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11892. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11893. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11894. rendererExtensionFragDepth: isWebGL2 || extensions.get('EXT_frag_depth') !== null,
  11895. rendererExtensionDrawBuffers: isWebGL2 || extensions.get('WEBGL_draw_buffers') !== null,
  11896. rendererExtensionShaderTextureLod: isWebGL2 || extensions.get('EXT_shader_texture_lod') !== null,
  11897. onBeforeCompile: material.onBeforeCompile
  11898. };
  11899. return parameters;
  11900. };
  11901. this.getProgramCacheKey = function (parameters) {
  11902. var array = [];
  11903. if (parameters.shaderID) {
  11904. array.push(parameters.shaderID);
  11905. } else {
  11906. array.push(parameters.fragmentShader);
  11907. array.push(parameters.vertexShader);
  11908. }
  11909. if (parameters.defines !== undefined) {
  11910. for (var name in parameters.defines) {
  11911. array.push(name);
  11912. array.push(parameters.defines[name]);
  11913. }
  11914. }
  11915. if (parameters.isRawShaderMaterial === undefined) {
  11916. for (var i = 0; i < parameterNames.length; i++) {
  11917. array.push(parameters[parameterNames[i]]);
  11918. }
  11919. array.push(renderer.outputEncoding);
  11920. array.push(renderer.gammaFactor);
  11921. }
  11922. array.push(parameters.onBeforeCompile.toString());
  11923. return array.join();
  11924. };
  11925. this.acquireProgram = function (parameters, cacheKey) {
  11926. var program; // Check if code has been already compiled
  11927. for (var p = 0, pl = programs.length; p < pl; p++) {
  11928. var preexistingProgram = programs[p];
  11929. if (preexistingProgram.cacheKey === cacheKey) {
  11930. program = preexistingProgram;
  11931. ++program.usedTimes;
  11932. break;
  11933. }
  11934. }
  11935. if (program === undefined) {
  11936. program = new WebGLProgram(renderer, cacheKey, parameters);
  11937. programs.push(program);
  11938. }
  11939. return program;
  11940. };
  11941. this.releaseProgram = function (program) {
  11942. if (--program.usedTimes === 0) {
  11943. // Remove from unordered set
  11944. var i = programs.indexOf(program);
  11945. programs[i] = programs[programs.length - 1];
  11946. programs.pop(); // Free WebGL resources
  11947. program.destroy();
  11948. }
  11949. }; // Exposed for resource monitoring & error feedback via renderer.info:
  11950. this.programs = programs;
  11951. }
  11952. /**
  11953. * @author fordacious / fordacious.github.io
  11954. */
  11955. function WebGLProperties() {
  11956. var properties = new WeakMap();
  11957. function get(object) {
  11958. var map = properties.get(object);
  11959. if (map === undefined) {
  11960. map = {};
  11961. properties.set(object, map);
  11962. }
  11963. return map;
  11964. }
  11965. function remove(object) {
  11966. properties.delete(object);
  11967. }
  11968. function update(object, key, value) {
  11969. properties.get(object)[key] = value;
  11970. }
  11971. function dispose() {
  11972. properties = new WeakMap();
  11973. }
  11974. return {
  11975. get: get,
  11976. remove: remove,
  11977. update: update,
  11978. dispose: dispose
  11979. };
  11980. }
  11981. /**
  11982. * @author mrdoob / http://mrdoob.com/
  11983. */
  11984. function painterSortStable(a, b) {
  11985. if (a.groupOrder !== b.groupOrder) {
  11986. return a.groupOrder - b.groupOrder;
  11987. } else if (a.renderOrder !== b.renderOrder) {
  11988. return a.renderOrder - b.renderOrder;
  11989. } else if (a.program !== b.program) {
  11990. return a.program.id - b.program.id;
  11991. } else if (a.material.id !== b.material.id) {
  11992. return a.material.id - b.material.id;
  11993. } else if (a.z !== b.z) {
  11994. return a.z - b.z;
  11995. } else {
  11996. return a.id - b.id;
  11997. }
  11998. }
  11999. function reversePainterSortStable(a, b) {
  12000. if (a.groupOrder !== b.groupOrder) {
  12001. return a.groupOrder - b.groupOrder;
  12002. } else if (a.renderOrder !== b.renderOrder) {
  12003. return a.renderOrder - b.renderOrder;
  12004. } else if (a.z !== b.z) {
  12005. return b.z - a.z;
  12006. } else {
  12007. return a.id - b.id;
  12008. }
  12009. }
  12010. function WebGLRenderList() {
  12011. var renderItems = [];
  12012. var renderItemsIndex = 0;
  12013. var opaque = [];
  12014. var transparent = [];
  12015. var defaultProgram = {
  12016. id: -1
  12017. };
  12018. function init() {
  12019. renderItemsIndex = 0;
  12020. opaque.length = 0;
  12021. transparent.length = 0;
  12022. }
  12023. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12024. var renderItem = renderItems[renderItemsIndex];
  12025. if (renderItem === undefined) {
  12026. renderItem = {
  12027. id: object.id,
  12028. object: object,
  12029. geometry: geometry,
  12030. material: material,
  12031. program: material.program || defaultProgram,
  12032. groupOrder: groupOrder,
  12033. renderOrder: object.renderOrder,
  12034. z: z,
  12035. group: group
  12036. };
  12037. renderItems[renderItemsIndex] = renderItem;
  12038. } else {
  12039. renderItem.id = object.id;
  12040. renderItem.object = object;
  12041. renderItem.geometry = geometry;
  12042. renderItem.material = material;
  12043. renderItem.program = material.program || defaultProgram;
  12044. renderItem.groupOrder = groupOrder;
  12045. renderItem.renderOrder = object.renderOrder;
  12046. renderItem.z = z;
  12047. renderItem.group = group;
  12048. }
  12049. renderItemsIndex++;
  12050. return renderItem;
  12051. }
  12052. function push(object, geometry, material, groupOrder, z, group) {
  12053. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12054. (material.transparent === true ? transparent : opaque).push(renderItem);
  12055. }
  12056. function unshift(object, geometry, material, groupOrder, z, group) {
  12057. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12058. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12059. }
  12060. function sort(customOpaqueSort, customTransparentSort) {
  12061. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12062. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12063. }
  12064. function finish() {
  12065. // Clear references from inactive renderItems in the list
  12066. for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12067. var renderItem = renderItems[i];
  12068. if (renderItem.id === null) break;
  12069. renderItem.id = null;
  12070. renderItem.object = null;
  12071. renderItem.geometry = null;
  12072. renderItem.material = null;
  12073. renderItem.program = null;
  12074. renderItem.group = null;
  12075. }
  12076. }
  12077. return {
  12078. opaque: opaque,
  12079. transparent: transparent,
  12080. init: init,
  12081. push: push,
  12082. unshift: unshift,
  12083. finish: finish,
  12084. sort: sort
  12085. };
  12086. }
  12087. function WebGLRenderLists() {
  12088. var lists = new WeakMap();
  12089. function onSceneDispose(event) {
  12090. var scene = event.target;
  12091. scene.removeEventListener('dispose', onSceneDispose);
  12092. lists.delete(scene);
  12093. }
  12094. function get(scene, camera) {
  12095. var cameras = lists.get(scene);
  12096. var list;
  12097. if (cameras === undefined) {
  12098. list = new WebGLRenderList();
  12099. lists.set(scene, new WeakMap());
  12100. lists.get(scene).set(camera, list);
  12101. scene.addEventListener('dispose', onSceneDispose);
  12102. } else {
  12103. list = cameras.get(camera);
  12104. if (list === undefined) {
  12105. list = new WebGLRenderList();
  12106. cameras.set(camera, list);
  12107. }
  12108. }
  12109. return list;
  12110. }
  12111. function dispose() {
  12112. lists = new WeakMap();
  12113. }
  12114. return {
  12115. get: get,
  12116. dispose: dispose
  12117. };
  12118. }
  12119. /**
  12120. * @author mrdoob / http://mrdoob.com/
  12121. */
  12122. function UniformsCache() {
  12123. var lights = {};
  12124. return {
  12125. get: function (light) {
  12126. if (lights[light.id] !== undefined) {
  12127. return lights[light.id];
  12128. }
  12129. var uniforms;
  12130. switch (light.type) {
  12131. case 'DirectionalLight':
  12132. uniforms = {
  12133. direction: new Vector3(),
  12134. color: new Color()
  12135. };
  12136. break;
  12137. case 'SpotLight':
  12138. uniforms = {
  12139. position: new Vector3(),
  12140. direction: new Vector3(),
  12141. color: new Color(),
  12142. distance: 0,
  12143. coneCos: 0,
  12144. penumbraCos: 0,
  12145. decay: 0
  12146. };
  12147. break;
  12148. case 'PointLight':
  12149. uniforms = {
  12150. position: new Vector3(),
  12151. color: new Color(),
  12152. distance: 0,
  12153. decay: 0
  12154. };
  12155. break;
  12156. case 'HemisphereLight':
  12157. uniforms = {
  12158. direction: new Vector3(),
  12159. skyColor: new Color(),
  12160. groundColor: new Color()
  12161. };
  12162. break;
  12163. case 'RectAreaLight':
  12164. uniforms = {
  12165. color: new Color(),
  12166. position: new Vector3(),
  12167. halfWidth: new Vector3(),
  12168. halfHeight: new Vector3()
  12169. };
  12170. break;
  12171. }
  12172. lights[light.id] = uniforms;
  12173. return uniforms;
  12174. }
  12175. };
  12176. }
  12177. function ShadowUniformsCache() {
  12178. var lights = {};
  12179. return {
  12180. get: function (light) {
  12181. if (lights[light.id] !== undefined) {
  12182. return lights[light.id];
  12183. }
  12184. var uniforms;
  12185. switch (light.type) {
  12186. case 'DirectionalLight':
  12187. uniforms = {
  12188. shadowBias: 0,
  12189. shadowRadius: 1,
  12190. shadowMapSize: new Vector2()
  12191. };
  12192. break;
  12193. case 'SpotLight':
  12194. uniforms = {
  12195. shadowBias: 0,
  12196. shadowRadius: 1,
  12197. shadowMapSize: new Vector2()
  12198. };
  12199. break;
  12200. case 'PointLight':
  12201. uniforms = {
  12202. shadowBias: 0,
  12203. shadowRadius: 1,
  12204. shadowMapSize: new Vector2(),
  12205. shadowCameraNear: 1,
  12206. shadowCameraFar: 1000
  12207. };
  12208. break;
  12209. // TODO (abelnation): set RectAreaLight shadow uniforms
  12210. }
  12211. lights[light.id] = uniforms;
  12212. return uniforms;
  12213. }
  12214. };
  12215. }
  12216. var nextVersion = 0;
  12217. function shadowCastingLightsFirst(lightA, lightB) {
  12218. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12219. }
  12220. function WebGLLights() {
  12221. var cache = new UniformsCache();
  12222. var shadowCache = ShadowUniformsCache();
  12223. var state = {
  12224. version: 0,
  12225. hash: {
  12226. directionalLength: -1,
  12227. pointLength: -1,
  12228. spotLength: -1,
  12229. rectAreaLength: -1,
  12230. hemiLength: -1,
  12231. numDirectionalShadows: -1,
  12232. numPointShadows: -1,
  12233. numSpotShadows: -1
  12234. },
  12235. ambient: [0, 0, 0],
  12236. probe: [],
  12237. directional: [],
  12238. directionalShadow: [],
  12239. directionalShadowMap: [],
  12240. directionalShadowMatrix: [],
  12241. spot: [],
  12242. spotShadow: [],
  12243. spotShadowMap: [],
  12244. spotShadowMatrix: [],
  12245. rectArea: [],
  12246. point: [],
  12247. pointShadow: [],
  12248. pointShadowMap: [],
  12249. pointShadowMatrix: [],
  12250. hemi: []
  12251. };
  12252. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  12253. var vector3 = new Vector3();
  12254. var matrix4 = new Matrix4();
  12255. var matrix42 = new Matrix4();
  12256. function setup(lights, shadows, camera) {
  12257. var r = 0,
  12258. g = 0,
  12259. b = 0;
  12260. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12261. var directionalLength = 0;
  12262. var pointLength = 0;
  12263. var spotLength = 0;
  12264. var rectAreaLength = 0;
  12265. var hemiLength = 0;
  12266. var numDirectionalShadows = 0;
  12267. var numPointShadows = 0;
  12268. var numSpotShadows = 0;
  12269. var viewMatrix = camera.matrixWorldInverse;
  12270. lights.sort(shadowCastingLightsFirst);
  12271. for (var i = 0, l = lights.length; i < l; i++) {
  12272. var light = lights[i];
  12273. var color = light.color;
  12274. var intensity = light.intensity;
  12275. var distance = light.distance;
  12276. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12277. if (light.isAmbientLight) {
  12278. r += color.r * intensity;
  12279. g += color.g * intensity;
  12280. b += color.b * intensity;
  12281. } else if (light.isLightProbe) {
  12282. for (var j = 0; j < 9; j++) {
  12283. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12284. }
  12285. } else if (light.isDirectionalLight) {
  12286. var uniforms = cache.get(light);
  12287. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12288. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12289. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12290. uniforms.direction.sub(vector3);
  12291. uniforms.direction.transformDirection(viewMatrix);
  12292. if (light.castShadow) {
  12293. var shadow = light.shadow;
  12294. var shadowUniforms = shadowCache.get(light);
  12295. shadowUniforms.shadowBias = shadow.bias;
  12296. shadowUniforms.shadowRadius = shadow.radius;
  12297. shadowUniforms.shadowMapSize = shadow.mapSize;
  12298. state.directionalShadow[directionalLength] = shadowUniforms;
  12299. state.directionalShadowMap[directionalLength] = shadowMap;
  12300. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12301. numDirectionalShadows++;
  12302. }
  12303. state.directional[directionalLength] = uniforms;
  12304. directionalLength++;
  12305. } else if (light.isSpotLight) {
  12306. var uniforms = cache.get(light);
  12307. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12308. uniforms.position.applyMatrix4(viewMatrix);
  12309. uniforms.color.copy(color).multiplyScalar(intensity);
  12310. uniforms.distance = distance;
  12311. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12312. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12313. uniforms.direction.sub(vector3);
  12314. uniforms.direction.transformDirection(viewMatrix);
  12315. uniforms.coneCos = Math.cos(light.angle);
  12316. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12317. uniforms.decay = light.decay;
  12318. if (light.castShadow) {
  12319. var shadow = light.shadow;
  12320. var shadowUniforms = shadowCache.get(light);
  12321. shadowUniforms.shadowBias = shadow.bias;
  12322. shadowUniforms.shadowRadius = shadow.radius;
  12323. shadowUniforms.shadowMapSize = shadow.mapSize;
  12324. state.spotShadow[spotLength] = shadowUniforms;
  12325. state.spotShadowMap[spotLength] = shadowMap;
  12326. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12327. numSpotShadows++;
  12328. }
  12329. state.spot[spotLength] = uniforms;
  12330. spotLength++;
  12331. } else if (light.isRectAreaLight) {
  12332. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12333. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12334. // (b) intensity is the brightness of the light
  12335. uniforms.color.copy(color).multiplyScalar(intensity);
  12336. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12337. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12338. matrix42.identity();
  12339. matrix4.copy(light.matrixWorld);
  12340. matrix4.premultiply(viewMatrix);
  12341. matrix42.extractRotation(matrix4);
  12342. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12343. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12344. uniforms.halfWidth.applyMatrix4(matrix42);
  12345. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  12346. // uniforms.distance = distance;
  12347. state.rectArea[rectAreaLength] = uniforms;
  12348. rectAreaLength++;
  12349. } else if (light.isPointLight) {
  12350. var uniforms = cache.get(light);
  12351. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12352. uniforms.position.applyMatrix4(viewMatrix);
  12353. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12354. uniforms.distance = light.distance;
  12355. uniforms.decay = light.decay;
  12356. if (light.castShadow) {
  12357. var shadow = light.shadow;
  12358. var shadowUniforms = shadowCache.get(light);
  12359. shadowUniforms.shadowBias = shadow.bias;
  12360. shadowUniforms.shadowRadius = shadow.radius;
  12361. shadowUniforms.shadowMapSize = shadow.mapSize;
  12362. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12363. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12364. state.pointShadow[pointLength] = shadowUniforms;
  12365. state.pointShadowMap[pointLength] = shadowMap;
  12366. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12367. numPointShadows++;
  12368. }
  12369. state.point[pointLength] = uniforms;
  12370. pointLength++;
  12371. } else if (light.isHemisphereLight) {
  12372. var uniforms = cache.get(light);
  12373. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12374. uniforms.direction.transformDirection(viewMatrix);
  12375. uniforms.direction.normalize();
  12376. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  12377. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  12378. state.hemi[hemiLength] = uniforms;
  12379. hemiLength++;
  12380. }
  12381. }
  12382. state.ambient[0] = r;
  12383. state.ambient[1] = g;
  12384. state.ambient[2] = b;
  12385. var hash = state.hash;
  12386. 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) {
  12387. state.directional.length = directionalLength;
  12388. state.spot.length = spotLength;
  12389. state.rectArea.length = rectAreaLength;
  12390. state.point.length = pointLength;
  12391. state.hemi.length = hemiLength;
  12392. state.directionalShadow.length = numDirectionalShadows;
  12393. state.directionalShadowMap.length = numDirectionalShadows;
  12394. state.pointShadow.length = numPointShadows;
  12395. state.pointShadowMap.length = numPointShadows;
  12396. state.spotShadow.length = numSpotShadows;
  12397. state.spotShadowMap.length = numSpotShadows;
  12398. state.directionalShadowMatrix.length = numDirectionalShadows;
  12399. state.pointShadowMatrix.length = numPointShadows;
  12400. state.spotShadowMatrix.length = numSpotShadows;
  12401. hash.directionalLength = directionalLength;
  12402. hash.pointLength = pointLength;
  12403. hash.spotLength = spotLength;
  12404. hash.rectAreaLength = rectAreaLength;
  12405. hash.hemiLength = hemiLength;
  12406. hash.numDirectionalShadows = numDirectionalShadows;
  12407. hash.numPointShadows = numPointShadows;
  12408. hash.numSpotShadows = numSpotShadows;
  12409. state.version = nextVersion++;
  12410. }
  12411. }
  12412. return {
  12413. setup: setup,
  12414. state: state
  12415. };
  12416. }
  12417. /**
  12418. * @author Mugen87 / https://github.com/Mugen87
  12419. */
  12420. function WebGLRenderState() {
  12421. var lights = new WebGLLights();
  12422. var lightsArray = [];
  12423. var shadowsArray = [];
  12424. function init() {
  12425. lightsArray.length = 0;
  12426. shadowsArray.length = 0;
  12427. }
  12428. function pushLight(light) {
  12429. lightsArray.push(light);
  12430. }
  12431. function pushShadow(shadowLight) {
  12432. shadowsArray.push(shadowLight);
  12433. }
  12434. function setupLights(camera) {
  12435. lights.setup(lightsArray, shadowsArray, camera);
  12436. }
  12437. var state = {
  12438. lightsArray: lightsArray,
  12439. shadowsArray: shadowsArray,
  12440. lights: lights
  12441. };
  12442. return {
  12443. init: init,
  12444. state: state,
  12445. setupLights: setupLights,
  12446. pushLight: pushLight,
  12447. pushShadow: pushShadow
  12448. };
  12449. }
  12450. function WebGLRenderStates() {
  12451. var renderStates = new WeakMap();
  12452. function onSceneDispose(event) {
  12453. var scene = event.target;
  12454. scene.removeEventListener('dispose', onSceneDispose);
  12455. renderStates.delete(scene);
  12456. }
  12457. function get(scene, camera) {
  12458. var renderState;
  12459. if (renderStates.has(scene) === false) {
  12460. renderState = new WebGLRenderState();
  12461. renderStates.set(scene, new WeakMap());
  12462. renderStates.get(scene).set(camera, renderState);
  12463. scene.addEventListener('dispose', onSceneDispose);
  12464. } else {
  12465. if (renderStates.get(scene).has(camera) === false) {
  12466. renderState = new WebGLRenderState();
  12467. renderStates.get(scene).set(camera, renderState);
  12468. } else {
  12469. renderState = renderStates.get(scene).get(camera);
  12470. }
  12471. }
  12472. return renderState;
  12473. }
  12474. function dispose() {
  12475. renderStates = new WeakMap();
  12476. }
  12477. return {
  12478. get: get,
  12479. dispose: dispose
  12480. };
  12481. }
  12482. /**
  12483. * @author mrdoob / http://mrdoob.com/
  12484. * @author alteredq / http://alteredqualia.com/
  12485. * @author bhouston / https://clara.io
  12486. * @author WestLangley / http://github.com/WestLangley
  12487. *
  12488. * parameters = {
  12489. *
  12490. * opacity: <float>,
  12491. *
  12492. * map: new THREE.Texture( <Image> ),
  12493. *
  12494. * alphaMap: new THREE.Texture( <Image> ),
  12495. *
  12496. * displacementMap: new THREE.Texture( <Image> ),
  12497. * displacementScale: <float>,
  12498. * displacementBias: <float>,
  12499. *
  12500. * wireframe: <boolean>,
  12501. * wireframeLinewidth: <float>
  12502. * }
  12503. */
  12504. function MeshDepthMaterial(parameters) {
  12505. Material.call(this);
  12506. this.type = 'MeshDepthMaterial';
  12507. this.depthPacking = BasicDepthPacking;
  12508. this.skinning = false;
  12509. this.morphTargets = false;
  12510. this.map = null;
  12511. this.alphaMap = null;
  12512. this.displacementMap = null;
  12513. this.displacementScale = 1;
  12514. this.displacementBias = 0;
  12515. this.wireframe = false;
  12516. this.wireframeLinewidth = 1;
  12517. this.fog = false;
  12518. this.setValues(parameters);
  12519. }
  12520. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12521. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12522. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12523. MeshDepthMaterial.prototype.copy = function (source) {
  12524. Material.prototype.copy.call(this, source);
  12525. this.depthPacking = source.depthPacking;
  12526. this.skinning = source.skinning;
  12527. this.morphTargets = source.morphTargets;
  12528. this.map = source.map;
  12529. this.alphaMap = source.alphaMap;
  12530. this.displacementMap = source.displacementMap;
  12531. this.displacementScale = source.displacementScale;
  12532. this.displacementBias = source.displacementBias;
  12533. this.wireframe = source.wireframe;
  12534. this.wireframeLinewidth = source.wireframeLinewidth;
  12535. return this;
  12536. };
  12537. /**
  12538. * @author WestLangley / http://github.com/WestLangley
  12539. *
  12540. * parameters = {
  12541. *
  12542. * referencePosition: <float>,
  12543. * nearDistance: <float>,
  12544. * farDistance: <float>,
  12545. *
  12546. * skinning: <bool>,
  12547. * morphTargets: <bool>,
  12548. *
  12549. * map: new THREE.Texture( <Image> ),
  12550. *
  12551. * alphaMap: new THREE.Texture( <Image> ),
  12552. *
  12553. * displacementMap: new THREE.Texture( <Image> ),
  12554. * displacementScale: <float>,
  12555. * displacementBias: <float>
  12556. *
  12557. * }
  12558. */
  12559. function MeshDistanceMaterial(parameters) {
  12560. Material.call(this);
  12561. this.type = 'MeshDistanceMaterial';
  12562. this.referencePosition = new Vector3();
  12563. this.nearDistance = 1;
  12564. this.farDistance = 1000;
  12565. this.skinning = false;
  12566. this.morphTargets = false;
  12567. this.map = null;
  12568. this.alphaMap = null;
  12569. this.displacementMap = null;
  12570. this.displacementScale = 1;
  12571. this.displacementBias = 0;
  12572. this.fog = false;
  12573. this.setValues(parameters);
  12574. }
  12575. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12576. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12577. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12578. MeshDistanceMaterial.prototype.copy = function (source) {
  12579. Material.prototype.copy.call(this, source);
  12580. this.referencePosition.copy(source.referencePosition);
  12581. this.nearDistance = source.nearDistance;
  12582. this.farDistance = source.farDistance;
  12583. this.skinning = source.skinning;
  12584. this.morphTargets = source.morphTargets;
  12585. this.map = source.map;
  12586. this.alphaMap = source.alphaMap;
  12587. this.displacementMap = source.displacementMap;
  12588. this.displacementScale = source.displacementScale;
  12589. this.displacementBias = source.displacementBias;
  12590. return this;
  12591. };
  12592. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12593. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12594. /**
  12595. * @author alteredq / http://alteredqualia.com/
  12596. * @author mrdoob / http://mrdoob.com/
  12597. */
  12598. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12599. var _frustum = new Frustum(),
  12600. _shadowMapSize = new Vector2(),
  12601. _viewportSize = new Vector2(),
  12602. _viewport = new Vector4(),
  12603. _depthMaterials = [],
  12604. _distanceMaterials = [],
  12605. _materialCache = {};
  12606. var shadowSide = {
  12607. 0: BackSide,
  12608. 1: FrontSide,
  12609. 2: DoubleSide
  12610. };
  12611. var shadowMaterialVertical = new ShaderMaterial({
  12612. defines: {
  12613. SAMPLE_RATE: 2.0 / 8.0,
  12614. HALF_SAMPLE_RATE: 1.0 / 8.0
  12615. },
  12616. uniforms: {
  12617. shadow_pass: {
  12618. value: null
  12619. },
  12620. resolution: {
  12621. value: new Vector2()
  12622. },
  12623. radius: {
  12624. value: 4.0
  12625. }
  12626. },
  12627. vertexShader: vsm_vert,
  12628. fragmentShader: vsm_frag
  12629. });
  12630. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12631. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12632. var fullScreenTri = new BufferGeometry();
  12633. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12634. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12635. var scope = this;
  12636. this.enabled = false;
  12637. this.autoUpdate = true;
  12638. this.needsUpdate = false;
  12639. this.type = PCFShadowMap;
  12640. this.render = function (lights, scene, camera) {
  12641. if (scope.enabled === false) return;
  12642. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12643. if (lights.length === 0) return;
  12644. var currentRenderTarget = _renderer.getRenderTarget();
  12645. var activeCubeFace = _renderer.getActiveCubeFace();
  12646. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12647. var _state = _renderer.state; // Set GL state for depth map.
  12648. _state.setBlending(NoBlending);
  12649. _state.buffers.color.setClear(1, 1, 1, 1);
  12650. _state.buffers.depth.setTest(true);
  12651. _state.setScissorTest(false); // render depth map
  12652. for (var i = 0, il = lights.length; i < il; i++) {
  12653. var light = lights[i];
  12654. var shadow = light.shadow;
  12655. if (shadow === undefined) {
  12656. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12657. continue;
  12658. }
  12659. _shadowMapSize.copy(shadow.mapSize);
  12660. var shadowFrameExtents = shadow.getFrameExtents();
  12661. _shadowMapSize.multiply(shadowFrameExtents);
  12662. _viewportSize.copy(shadow.mapSize);
  12663. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12664. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  12665. if (_shadowMapSize.x > maxTextureSize) {
  12666. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12667. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12668. shadow.mapSize.x = _viewportSize.x;
  12669. }
  12670. if (_shadowMapSize.y > maxTextureSize) {
  12671. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12672. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12673. shadow.mapSize.y = _viewportSize.y;
  12674. }
  12675. }
  12676. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12677. var pars = {
  12678. minFilter: LinearFilter,
  12679. magFilter: LinearFilter,
  12680. format: RGBAFormat
  12681. };
  12682. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12683. shadow.map.texture.name = light.name + ".shadowMap";
  12684. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12685. shadow.camera.updateProjectionMatrix();
  12686. }
  12687. if (shadow.map === null) {
  12688. var pars = {
  12689. minFilter: NearestFilter,
  12690. magFilter: NearestFilter,
  12691. format: RGBAFormat
  12692. };
  12693. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12694. shadow.map.texture.name = light.name + ".shadowMap";
  12695. shadow.camera.updateProjectionMatrix();
  12696. }
  12697. _renderer.setRenderTarget(shadow.map);
  12698. _renderer.clear();
  12699. var viewportCount = shadow.getViewportCount();
  12700. for (var vp = 0; vp < viewportCount; vp++) {
  12701. var viewport = shadow.getViewport(vp);
  12702. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12703. _state.viewport(_viewport);
  12704. shadow.updateMatrices(light, vp);
  12705. _frustum = shadow.getFrustum();
  12706. renderObject(scene, camera, shadow.camera, light, this.type);
  12707. } // do blur pass for VSM
  12708. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12709. VSMPass(shadow, camera);
  12710. }
  12711. }
  12712. scope.needsUpdate = false;
  12713. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12714. };
  12715. function VSMPass(shadow, camera) {
  12716. var geometry = _objects.update(fullScreenMesh); // vertical pass
  12717. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12718. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12719. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12720. _renderer.setRenderTarget(shadow.mapPass);
  12721. _renderer.clear();
  12722. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12723. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12724. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12725. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12726. _renderer.setRenderTarget(shadow.map);
  12727. _renderer.clear();
  12728. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12729. }
  12730. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12731. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12732. var material = _depthMaterials[index];
  12733. if (material === undefined) {
  12734. material = new MeshDepthMaterial({
  12735. depthPacking: RGBADepthPacking,
  12736. morphTargets: useMorphing,
  12737. skinning: useSkinning
  12738. });
  12739. _depthMaterials[index] = material;
  12740. }
  12741. return material;
  12742. }
  12743. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12744. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12745. var material = _distanceMaterials[index];
  12746. if (material === undefined) {
  12747. material = new MeshDistanceMaterial({
  12748. morphTargets: useMorphing,
  12749. skinning: useSkinning
  12750. });
  12751. _distanceMaterials[index] = material;
  12752. }
  12753. return material;
  12754. }
  12755. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12756. var geometry = object.geometry;
  12757. var result = null;
  12758. var getMaterialVariant = getDepthMaterialVariant;
  12759. var customMaterial = object.customDepthMaterial;
  12760. if (light.isPointLight === true) {
  12761. getMaterialVariant = getDistanceMaterialVariant;
  12762. customMaterial = object.customDistanceMaterial;
  12763. }
  12764. if (customMaterial === undefined) {
  12765. var useMorphing = false;
  12766. if (material.morphTargets === true) {
  12767. if (geometry.isBufferGeometry === true) {
  12768. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12769. } else if (geometry.isGeometry === true) {
  12770. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  12771. }
  12772. }
  12773. var useSkinning = false;
  12774. if (object.isSkinnedMesh === true) {
  12775. if (material.skinning === true) {
  12776. useSkinning = true;
  12777. } else {
  12778. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12779. }
  12780. }
  12781. var useInstancing = object.isInstancedMesh === true;
  12782. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  12783. } else {
  12784. result = customMaterial;
  12785. }
  12786. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12787. // in this case we need a unique material instance reflecting the
  12788. // appropriate state
  12789. var keyA = result.uuid,
  12790. keyB = material.uuid;
  12791. var materialsForVariant = _materialCache[keyA];
  12792. if (materialsForVariant === undefined) {
  12793. materialsForVariant = {};
  12794. _materialCache[keyA] = materialsForVariant;
  12795. }
  12796. var cachedMaterial = materialsForVariant[keyB];
  12797. if (cachedMaterial === undefined) {
  12798. cachedMaterial = result.clone();
  12799. materialsForVariant[keyB] = cachedMaterial;
  12800. }
  12801. result = cachedMaterial;
  12802. }
  12803. result.visible = material.visible;
  12804. result.wireframe = material.wireframe;
  12805. if (type === VSMShadowMap) {
  12806. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12807. } else {
  12808. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12809. }
  12810. result.clipShadows = material.clipShadows;
  12811. result.clippingPlanes = material.clippingPlanes;
  12812. result.clipIntersection = material.clipIntersection;
  12813. result.wireframeLinewidth = material.wireframeLinewidth;
  12814. result.linewidth = material.linewidth;
  12815. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12816. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12817. result.nearDistance = shadowCameraNear;
  12818. result.farDistance = shadowCameraFar;
  12819. }
  12820. return result;
  12821. }
  12822. function renderObject(object, camera, shadowCamera, light, type) {
  12823. if (object.visible === false) return;
  12824. var visible = object.layers.test(camera.layers);
  12825. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12826. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12827. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12828. var geometry = _objects.update(object);
  12829. var material = object.material;
  12830. if (Array.isArray(material)) {
  12831. var groups = geometry.groups;
  12832. for (var k = 0, kl = groups.length; k < kl; k++) {
  12833. var group = groups[k];
  12834. var groupMaterial = material[group.materialIndex];
  12835. if (groupMaterial && groupMaterial.visible) {
  12836. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12837. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12838. }
  12839. }
  12840. } else if (material.visible) {
  12841. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12842. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12843. }
  12844. }
  12845. }
  12846. var children = object.children;
  12847. for (var i = 0, l = children.length; i < l; i++) {
  12848. renderObject(children[i], camera, shadowCamera, light, type);
  12849. }
  12850. }
  12851. }
  12852. /**
  12853. * @author mrdoob / http://mrdoob.com/
  12854. */
  12855. function WebGLState(gl, extensions, capabilities) {
  12856. var isWebGL2 = capabilities.isWebGL2;
  12857. function ColorBuffer() {
  12858. var locked = false;
  12859. var color = new Vector4();
  12860. var currentColorMask = null;
  12861. var currentColorClear = new Vector4(0, 0, 0, 0);
  12862. return {
  12863. setMask: function (colorMask) {
  12864. if (currentColorMask !== colorMask && !locked) {
  12865. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12866. currentColorMask = colorMask;
  12867. }
  12868. },
  12869. setLocked: function (lock) {
  12870. locked = lock;
  12871. },
  12872. setClear: function (r, g, b, a, premultipliedAlpha) {
  12873. if (premultipliedAlpha === true) {
  12874. r *= a;
  12875. g *= a;
  12876. b *= a;
  12877. }
  12878. color.set(r, g, b, a);
  12879. if (currentColorClear.equals(color) === false) {
  12880. gl.clearColor(r, g, b, a);
  12881. currentColorClear.copy(color);
  12882. }
  12883. },
  12884. reset: function () {
  12885. locked = false;
  12886. currentColorMask = null;
  12887. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12888. }
  12889. };
  12890. }
  12891. function DepthBuffer() {
  12892. var locked = false;
  12893. var currentDepthMask = null;
  12894. var currentDepthFunc = null;
  12895. var currentDepthClear = null;
  12896. return {
  12897. setTest: function (depthTest) {
  12898. if (depthTest) {
  12899. enable(2929);
  12900. } else {
  12901. disable(2929);
  12902. }
  12903. },
  12904. setMask: function (depthMask) {
  12905. if (currentDepthMask !== depthMask && !locked) {
  12906. gl.depthMask(depthMask);
  12907. currentDepthMask = depthMask;
  12908. }
  12909. },
  12910. setFunc: function (depthFunc) {
  12911. if (currentDepthFunc !== depthFunc) {
  12912. if (depthFunc) {
  12913. switch (depthFunc) {
  12914. case NeverDepth:
  12915. gl.depthFunc(512);
  12916. break;
  12917. case AlwaysDepth:
  12918. gl.depthFunc(519);
  12919. break;
  12920. case LessDepth:
  12921. gl.depthFunc(513);
  12922. break;
  12923. case LessEqualDepth:
  12924. gl.depthFunc(515);
  12925. break;
  12926. case EqualDepth:
  12927. gl.depthFunc(514);
  12928. break;
  12929. case GreaterEqualDepth:
  12930. gl.depthFunc(518);
  12931. break;
  12932. case GreaterDepth:
  12933. gl.depthFunc(516);
  12934. break;
  12935. case NotEqualDepth:
  12936. gl.depthFunc(517);
  12937. break;
  12938. default:
  12939. gl.depthFunc(515);
  12940. }
  12941. } else {
  12942. gl.depthFunc(515);
  12943. }
  12944. currentDepthFunc = depthFunc;
  12945. }
  12946. },
  12947. setLocked: function (lock) {
  12948. locked = lock;
  12949. },
  12950. setClear: function (depth) {
  12951. if (currentDepthClear !== depth) {
  12952. gl.clearDepth(depth);
  12953. currentDepthClear = depth;
  12954. }
  12955. },
  12956. reset: function () {
  12957. locked = false;
  12958. currentDepthMask = null;
  12959. currentDepthFunc = null;
  12960. currentDepthClear = null;
  12961. }
  12962. };
  12963. }
  12964. function StencilBuffer() {
  12965. var locked = false;
  12966. var currentStencilMask = null;
  12967. var currentStencilFunc = null;
  12968. var currentStencilRef = null;
  12969. var currentStencilFuncMask = null;
  12970. var currentStencilFail = null;
  12971. var currentStencilZFail = null;
  12972. var currentStencilZPass = null;
  12973. var currentStencilClear = null;
  12974. return {
  12975. setTest: function (stencilTest) {
  12976. if (!locked) {
  12977. if (stencilTest) {
  12978. enable(2960);
  12979. } else {
  12980. disable(2960);
  12981. }
  12982. }
  12983. },
  12984. setMask: function (stencilMask) {
  12985. if (currentStencilMask !== stencilMask && !locked) {
  12986. gl.stencilMask(stencilMask);
  12987. currentStencilMask = stencilMask;
  12988. }
  12989. },
  12990. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12991. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12992. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12993. currentStencilFunc = stencilFunc;
  12994. currentStencilRef = stencilRef;
  12995. currentStencilFuncMask = stencilMask;
  12996. }
  12997. },
  12998. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12999. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13000. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13001. currentStencilFail = stencilFail;
  13002. currentStencilZFail = stencilZFail;
  13003. currentStencilZPass = stencilZPass;
  13004. }
  13005. },
  13006. setLocked: function (lock) {
  13007. locked = lock;
  13008. },
  13009. setClear: function (stencil) {
  13010. if (currentStencilClear !== stencil) {
  13011. gl.clearStencil(stencil);
  13012. currentStencilClear = stencil;
  13013. }
  13014. },
  13015. reset: function () {
  13016. locked = false;
  13017. currentStencilMask = null;
  13018. currentStencilFunc = null;
  13019. currentStencilRef = null;
  13020. currentStencilFuncMask = null;
  13021. currentStencilFail = null;
  13022. currentStencilZFail = null;
  13023. currentStencilZPass = null;
  13024. currentStencilClear = null;
  13025. }
  13026. };
  13027. } //
  13028. var colorBuffer = new ColorBuffer();
  13029. var depthBuffer = new DepthBuffer();
  13030. var stencilBuffer = new StencilBuffer();
  13031. var maxVertexAttributes = gl.getParameter(34921);
  13032. var newAttributes = new Uint8Array(maxVertexAttributes);
  13033. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13034. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13035. var enabledCapabilities = {};
  13036. var currentProgram = null;
  13037. var currentBlendingEnabled = null;
  13038. var currentBlending = null;
  13039. var currentBlendEquation = null;
  13040. var currentBlendSrc = null;
  13041. var currentBlendDst = null;
  13042. var currentBlendEquationAlpha = null;
  13043. var currentBlendSrcAlpha = null;
  13044. var currentBlendDstAlpha = null;
  13045. var currentPremultipledAlpha = false;
  13046. var currentFlipSided = null;
  13047. var currentCullFace = null;
  13048. var currentLineWidth = null;
  13049. var currentPolygonOffsetFactor = null;
  13050. var currentPolygonOffsetUnits = null;
  13051. var maxTextures = gl.getParameter(35661);
  13052. var lineWidthAvailable = false;
  13053. var version = 0;
  13054. var glVersion = gl.getParameter(7938);
  13055. if (glVersion.indexOf('WebGL') !== -1) {
  13056. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13057. lineWidthAvailable = version >= 1.0;
  13058. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13059. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13060. lineWidthAvailable = version >= 2.0;
  13061. }
  13062. var currentTextureSlot = null;
  13063. var currentBoundTextures = {};
  13064. var currentScissor = new Vector4();
  13065. var currentViewport = new Vector4();
  13066. function createTexture(type, target, count) {
  13067. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13068. var texture = gl.createTexture();
  13069. gl.bindTexture(type, texture);
  13070. gl.texParameteri(type, 10241, 9728);
  13071. gl.texParameteri(type, 10240, 9728);
  13072. for (var i = 0; i < count; i++) {
  13073. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13074. }
  13075. return texture;
  13076. }
  13077. var emptyTextures = {};
  13078. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13079. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13080. colorBuffer.setClear(0, 0, 0, 1);
  13081. depthBuffer.setClear(1);
  13082. stencilBuffer.setClear(0);
  13083. enable(2929);
  13084. depthBuffer.setFunc(LessEqualDepth);
  13085. setFlipSided(false);
  13086. setCullFace(CullFaceBack);
  13087. enable(2884);
  13088. setBlending(NoBlending); //
  13089. function initAttributes() {
  13090. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13091. newAttributes[i] = 0;
  13092. }
  13093. }
  13094. function enableAttribute(attribute) {
  13095. enableAttributeAndDivisor(attribute, 0);
  13096. }
  13097. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13098. newAttributes[attribute] = 1;
  13099. if (enabledAttributes[attribute] === 0) {
  13100. gl.enableVertexAttribArray(attribute);
  13101. enabledAttributes[attribute] = 1;
  13102. }
  13103. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13104. var extension = isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13105. extension[isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13106. attributeDivisors[attribute] = meshPerAttribute;
  13107. }
  13108. }
  13109. function disableUnusedAttributes() {
  13110. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13111. if (enabledAttributes[i] !== newAttributes[i]) {
  13112. gl.disableVertexAttribArray(i);
  13113. enabledAttributes[i] = 0;
  13114. }
  13115. }
  13116. }
  13117. function enable(id) {
  13118. if (enabledCapabilities[id] !== true) {
  13119. gl.enable(id);
  13120. enabledCapabilities[id] = true;
  13121. }
  13122. }
  13123. function disable(id) {
  13124. if (enabledCapabilities[id] !== false) {
  13125. gl.disable(id);
  13126. enabledCapabilities[id] = false;
  13127. }
  13128. }
  13129. function useProgram(program) {
  13130. if (currentProgram !== program) {
  13131. gl.useProgram(program);
  13132. currentProgram = program;
  13133. return true;
  13134. }
  13135. return false;
  13136. }
  13137. var equationToGL = {
  13138. [AddEquation]: 32774,
  13139. [SubtractEquation]: 32778,
  13140. [ReverseSubtractEquation]: 32779
  13141. };
  13142. if (isWebGL2) {
  13143. equationToGL[MinEquation] = 32775;
  13144. equationToGL[MaxEquation] = 32776;
  13145. } else {
  13146. var extension = extensions.get('EXT_blend_minmax');
  13147. if (extension !== null) {
  13148. equationToGL[MinEquation] = extension.MIN_EXT;
  13149. equationToGL[MaxEquation] = extension.MAX_EXT;
  13150. }
  13151. }
  13152. var factorToGL = {
  13153. [ZeroFactor]: 0,
  13154. [OneFactor]: 1,
  13155. [SrcColorFactor]: 768,
  13156. [SrcAlphaFactor]: 770,
  13157. [SrcAlphaSaturateFactor]: 776,
  13158. [DstColorFactor]: 774,
  13159. [DstAlphaFactor]: 772,
  13160. [OneMinusSrcColorFactor]: 769,
  13161. [OneMinusSrcAlphaFactor]: 771,
  13162. [OneMinusDstColorFactor]: 775,
  13163. [OneMinusDstAlphaFactor]: 773
  13164. };
  13165. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13166. if (blending === NoBlending) {
  13167. if (currentBlendingEnabled) {
  13168. disable(3042);
  13169. currentBlendingEnabled = false;
  13170. }
  13171. return;
  13172. }
  13173. if (!currentBlendingEnabled) {
  13174. enable(3042);
  13175. currentBlendingEnabled = true;
  13176. }
  13177. if (blending !== CustomBlending) {
  13178. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13179. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13180. gl.blendEquation(32774);
  13181. currentBlendEquation = AddEquation;
  13182. currentBlendEquationAlpha = AddEquation;
  13183. }
  13184. if (premultipliedAlpha) {
  13185. switch (blending) {
  13186. case NormalBlending:
  13187. gl.blendFuncSeparate(1, 771, 1, 771);
  13188. break;
  13189. case AdditiveBlending:
  13190. gl.blendFunc(1, 1);
  13191. break;
  13192. case SubtractiveBlending:
  13193. gl.blendFuncSeparate(0, 0, 769, 771);
  13194. break;
  13195. case MultiplyBlending:
  13196. gl.blendFuncSeparate(0, 768, 0, 770);
  13197. break;
  13198. default:
  13199. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13200. break;
  13201. }
  13202. } else {
  13203. switch (blending) {
  13204. case NormalBlending:
  13205. gl.blendFuncSeparate(770, 771, 1, 771);
  13206. break;
  13207. case AdditiveBlending:
  13208. gl.blendFunc(770, 1);
  13209. break;
  13210. case SubtractiveBlending:
  13211. gl.blendFunc(0, 769);
  13212. break;
  13213. case MultiplyBlending:
  13214. gl.blendFunc(0, 768);
  13215. break;
  13216. default:
  13217. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13218. break;
  13219. }
  13220. }
  13221. currentBlendSrc = null;
  13222. currentBlendDst = null;
  13223. currentBlendSrcAlpha = null;
  13224. currentBlendDstAlpha = null;
  13225. currentBlending = blending;
  13226. currentPremultipledAlpha = premultipliedAlpha;
  13227. }
  13228. return;
  13229. } // custom blending
  13230. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13231. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13232. blendDstAlpha = blendDstAlpha || blendDst;
  13233. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13234. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13235. currentBlendEquation = blendEquation;
  13236. currentBlendEquationAlpha = blendEquationAlpha;
  13237. }
  13238. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13239. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13240. currentBlendSrc = blendSrc;
  13241. currentBlendDst = blendDst;
  13242. currentBlendSrcAlpha = blendSrcAlpha;
  13243. currentBlendDstAlpha = blendDstAlpha;
  13244. }
  13245. currentBlending = blending;
  13246. currentPremultipledAlpha = null;
  13247. }
  13248. function setMaterial(material, frontFaceCW) {
  13249. material.side === DoubleSide ? disable(2884) : enable(2884);
  13250. var flipSided = material.side === BackSide;
  13251. if (frontFaceCW) flipSided = !flipSided;
  13252. setFlipSided(flipSided);
  13253. 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);
  13254. depthBuffer.setFunc(material.depthFunc);
  13255. depthBuffer.setTest(material.depthTest);
  13256. depthBuffer.setMask(material.depthWrite);
  13257. colorBuffer.setMask(material.colorWrite);
  13258. var stencilWrite = material.stencilWrite;
  13259. stencilBuffer.setTest(stencilWrite);
  13260. if (stencilWrite) {
  13261. stencilBuffer.setMask(material.stencilWriteMask);
  13262. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13263. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13264. }
  13265. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13266. } //
  13267. function setFlipSided(flipSided) {
  13268. if (currentFlipSided !== flipSided) {
  13269. if (flipSided) {
  13270. gl.frontFace(2304);
  13271. } else {
  13272. gl.frontFace(2305);
  13273. }
  13274. currentFlipSided = flipSided;
  13275. }
  13276. }
  13277. function setCullFace(cullFace) {
  13278. if (cullFace !== CullFaceNone) {
  13279. enable(2884);
  13280. if (cullFace !== currentCullFace) {
  13281. if (cullFace === CullFaceBack) {
  13282. gl.cullFace(1029);
  13283. } else if (cullFace === CullFaceFront) {
  13284. gl.cullFace(1028);
  13285. } else {
  13286. gl.cullFace(1032);
  13287. }
  13288. }
  13289. } else {
  13290. disable(2884);
  13291. }
  13292. currentCullFace = cullFace;
  13293. }
  13294. function setLineWidth(width) {
  13295. if (width !== currentLineWidth) {
  13296. if (lineWidthAvailable) gl.lineWidth(width);
  13297. currentLineWidth = width;
  13298. }
  13299. }
  13300. function setPolygonOffset(polygonOffset, factor, units) {
  13301. if (polygonOffset) {
  13302. enable(32823);
  13303. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13304. gl.polygonOffset(factor, units);
  13305. currentPolygonOffsetFactor = factor;
  13306. currentPolygonOffsetUnits = units;
  13307. }
  13308. } else {
  13309. disable(32823);
  13310. }
  13311. }
  13312. function setScissorTest(scissorTest) {
  13313. if (scissorTest) {
  13314. enable(3089);
  13315. } else {
  13316. disable(3089);
  13317. }
  13318. } // texture
  13319. function activeTexture(webglSlot) {
  13320. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  13321. if (currentTextureSlot !== webglSlot) {
  13322. gl.activeTexture(webglSlot);
  13323. currentTextureSlot = webglSlot;
  13324. }
  13325. }
  13326. function bindTexture(webglType, webglTexture) {
  13327. if (currentTextureSlot === null) {
  13328. activeTexture();
  13329. }
  13330. var boundTexture = currentBoundTextures[currentTextureSlot];
  13331. if (boundTexture === undefined) {
  13332. boundTexture = {
  13333. type: undefined,
  13334. texture: undefined
  13335. };
  13336. currentBoundTextures[currentTextureSlot] = boundTexture;
  13337. }
  13338. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13339. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13340. boundTexture.type = webglType;
  13341. boundTexture.texture = webglTexture;
  13342. }
  13343. }
  13344. function unbindTexture() {
  13345. var boundTexture = currentBoundTextures[currentTextureSlot];
  13346. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13347. gl.bindTexture(boundTexture.type, null);
  13348. boundTexture.type = undefined;
  13349. boundTexture.texture = undefined;
  13350. }
  13351. }
  13352. function compressedTexImage2D() {
  13353. try {
  13354. gl.compressedTexImage2D.apply(gl, arguments);
  13355. } catch (error) {
  13356. console.error('THREE.WebGLState:', error);
  13357. }
  13358. }
  13359. function texImage2D() {
  13360. try {
  13361. gl.texImage2D.apply(gl, arguments);
  13362. } catch (error) {
  13363. console.error('THREE.WebGLState:', error);
  13364. }
  13365. }
  13366. function texImage3D() {
  13367. try {
  13368. gl.texImage3D.apply(gl, arguments);
  13369. } catch (error) {
  13370. console.error('THREE.WebGLState:', error);
  13371. }
  13372. } //
  13373. function scissor(scissor) {
  13374. if (currentScissor.equals(scissor) === false) {
  13375. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13376. currentScissor.copy(scissor);
  13377. }
  13378. }
  13379. function viewport(viewport) {
  13380. if (currentViewport.equals(viewport) === false) {
  13381. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13382. currentViewport.copy(viewport);
  13383. }
  13384. } //
  13385. function reset() {
  13386. for (var i = 0; i < enabledAttributes.length; i++) {
  13387. if (enabledAttributes[i] === 1) {
  13388. gl.disableVertexAttribArray(i);
  13389. enabledAttributes[i] = 0;
  13390. }
  13391. }
  13392. enabledCapabilities = {};
  13393. currentTextureSlot = null;
  13394. currentBoundTextures = {};
  13395. currentProgram = null;
  13396. currentBlending = null;
  13397. currentFlipSided = null;
  13398. currentCullFace = null;
  13399. colorBuffer.reset();
  13400. depthBuffer.reset();
  13401. stencilBuffer.reset();
  13402. }
  13403. return {
  13404. buffers: {
  13405. color: colorBuffer,
  13406. depth: depthBuffer,
  13407. stencil: stencilBuffer
  13408. },
  13409. initAttributes: initAttributes,
  13410. enableAttribute: enableAttribute,
  13411. enableAttributeAndDivisor: enableAttributeAndDivisor,
  13412. disableUnusedAttributes: disableUnusedAttributes,
  13413. enable: enable,
  13414. disable: disable,
  13415. useProgram: useProgram,
  13416. setBlending: setBlending,
  13417. setMaterial: setMaterial,
  13418. setFlipSided: setFlipSided,
  13419. setCullFace: setCullFace,
  13420. setLineWidth: setLineWidth,
  13421. setPolygonOffset: setPolygonOffset,
  13422. setScissorTest: setScissorTest,
  13423. activeTexture: activeTexture,
  13424. bindTexture: bindTexture,
  13425. unbindTexture: unbindTexture,
  13426. compressedTexImage2D: compressedTexImage2D,
  13427. texImage2D: texImage2D,
  13428. texImage3D: texImage3D,
  13429. scissor: scissor,
  13430. viewport: viewport,
  13431. reset: reset
  13432. };
  13433. }
  13434. /**
  13435. * @author mrdoob / http://mrdoob.com/
  13436. */
  13437. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13438. var isWebGL2 = capabilities.isWebGL2;
  13439. var maxTextures = capabilities.maxTextures;
  13440. var maxCubemapSize = capabilities.maxCubemapSize;
  13441. var maxTextureSize = capabilities.maxTextureSize;
  13442. var maxSamples = capabilities.maxSamples;
  13443. var _videoTextures = new WeakMap();
  13444. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13445. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13446. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13447. var useOffscreenCanvas = false;
  13448. try {
  13449. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  13450. } catch (err) {// Ignore any errors
  13451. }
  13452. function createCanvas(width, height) {
  13453. // Use OffscreenCanvas when available. Specially needed in web workers
  13454. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13455. }
  13456. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13457. var scale = 1; // handle case if texture exceeds max size
  13458. if (image.width > maxSize || image.height > maxSize) {
  13459. scale = maxSize / Math.max(image.width, image.height);
  13460. } // only perform resize if necessary
  13461. if (scale < 1 || needsPowerOfTwo === true) {
  13462. // only perform resize for certain image types
  13463. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13464. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  13465. var width = floor(scale * image.width);
  13466. var height = floor(scale * image.height);
  13467. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13468. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13469. canvas.width = width;
  13470. canvas.height = height;
  13471. var context = canvas.getContext('2d');
  13472. context.drawImage(image, 0, 0, width, height);
  13473. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13474. return canvas;
  13475. } else {
  13476. if ('data' in image) {
  13477. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13478. }
  13479. return image;
  13480. }
  13481. }
  13482. return image;
  13483. }
  13484. function isPowerOfTwo(image) {
  13485. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  13486. }
  13487. function textureNeedsPowerOfTwo(texture) {
  13488. if (isWebGL2) return false;
  13489. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13490. }
  13491. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13492. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13493. }
  13494. function generateMipmap(target, texture, width, height) {
  13495. _gl.generateMipmap(target);
  13496. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13497. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13498. }
  13499. function getInternalFormat(internalFormatName, glFormat, glType) {
  13500. if (isWebGL2 === false) return glFormat;
  13501. if (internalFormatName !== null) {
  13502. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13503. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13504. }
  13505. var internalFormat = glFormat;
  13506. if (glFormat === 6403) {
  13507. if (glType === 5126) internalFormat = 33326;
  13508. if (glType === 5131) internalFormat = 33325;
  13509. if (glType === 5121) internalFormat = 33321;
  13510. }
  13511. if (glFormat === 6407) {
  13512. if (glType === 5126) internalFormat = 34837;
  13513. if (glType === 5131) internalFormat = 34843;
  13514. if (glType === 5121) internalFormat = 32849;
  13515. }
  13516. if (glFormat === 6408) {
  13517. if (glType === 5126) internalFormat = 34836;
  13518. if (glType === 5131) internalFormat = 34842;
  13519. if (glType === 5121) internalFormat = 32856;
  13520. }
  13521. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13522. extensions.get('EXT_color_buffer_float');
  13523. }
  13524. return internalFormat;
  13525. } // Fallback filters for non-power-of-2 textures
  13526. function filterFallback(f) {
  13527. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13528. return 9728;
  13529. }
  13530. return 9729;
  13531. } //
  13532. function onTextureDispose(event) {
  13533. var texture = event.target;
  13534. texture.removeEventListener('dispose', onTextureDispose);
  13535. deallocateTexture(texture);
  13536. if (texture.isVideoTexture) {
  13537. _videoTextures.delete(texture);
  13538. }
  13539. info.memory.textures--;
  13540. }
  13541. function onRenderTargetDispose(event) {
  13542. var renderTarget = event.target;
  13543. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13544. deallocateRenderTarget(renderTarget);
  13545. info.memory.textures--;
  13546. } //
  13547. function deallocateTexture(texture) {
  13548. var textureProperties = properties.get(texture);
  13549. if (textureProperties.__webglInit === undefined) return;
  13550. _gl.deleteTexture(textureProperties.__webglTexture);
  13551. properties.remove(texture);
  13552. }
  13553. function deallocateRenderTarget(renderTarget) {
  13554. var renderTargetProperties = properties.get(renderTarget);
  13555. var textureProperties = properties.get(renderTarget.texture);
  13556. if (!renderTarget) return;
  13557. if (textureProperties.__webglTexture !== undefined) {
  13558. _gl.deleteTexture(textureProperties.__webglTexture);
  13559. }
  13560. if (renderTarget.depthTexture) {
  13561. renderTarget.depthTexture.dispose();
  13562. }
  13563. if (renderTarget.isWebGLCubeRenderTarget) {
  13564. for (var i = 0; i < 6; i++) {
  13565. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13566. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13567. }
  13568. } else {
  13569. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13570. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13571. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13572. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13573. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13574. }
  13575. properties.remove(renderTarget.texture);
  13576. properties.remove(renderTarget);
  13577. } //
  13578. var textureUnits = 0;
  13579. function resetTextureUnits() {
  13580. textureUnits = 0;
  13581. }
  13582. function allocateTextureUnit() {
  13583. var textureUnit = textureUnits;
  13584. if (textureUnit >= maxTextures) {
  13585. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13586. }
  13587. textureUnits += 1;
  13588. return textureUnit;
  13589. } //
  13590. function setTexture2D(texture, slot) {
  13591. var textureProperties = properties.get(texture);
  13592. if (texture.isVideoTexture) updateVideoTexture(texture);
  13593. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13594. var image = texture.image;
  13595. if (image === undefined) {
  13596. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13597. } else if (image.complete === false) {
  13598. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13599. } else {
  13600. uploadTexture(textureProperties, texture, slot);
  13601. return;
  13602. }
  13603. }
  13604. state.activeTexture(33984 + slot);
  13605. state.bindTexture(3553, textureProperties.__webglTexture);
  13606. }
  13607. function setTexture2DArray(texture, slot) {
  13608. var textureProperties = properties.get(texture);
  13609. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13610. uploadTexture(textureProperties, texture, slot);
  13611. return;
  13612. }
  13613. state.activeTexture(33984 + slot);
  13614. state.bindTexture(35866, textureProperties.__webglTexture);
  13615. }
  13616. function setTexture3D(texture, slot) {
  13617. var textureProperties = properties.get(texture);
  13618. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13619. uploadTexture(textureProperties, texture, slot);
  13620. return;
  13621. }
  13622. state.activeTexture(33984 + slot);
  13623. state.bindTexture(32879, textureProperties.__webglTexture);
  13624. }
  13625. function setTextureCube(texture, slot) {
  13626. if (texture.image.length !== 6) return;
  13627. var textureProperties = properties.get(texture);
  13628. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13629. initTexture(textureProperties, texture);
  13630. state.activeTexture(33984 + slot);
  13631. state.bindTexture(34067, textureProperties.__webglTexture);
  13632. _gl.pixelStorei(37440, texture.flipY);
  13633. var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13634. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13635. var cubeImage = [];
  13636. for (var i = 0; i < 6; i++) {
  13637. if (!isCompressed && !isDataTexture) {
  13638. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13639. } else {
  13640. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13641. }
  13642. }
  13643. var image = cubeImage[0],
  13644. supportsMips = isPowerOfTwo(image) || isWebGL2,
  13645. glFormat = utils.convert(texture.format),
  13646. glType = utils.convert(texture.type),
  13647. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13648. setTextureParameters(34067, texture, supportsMips);
  13649. var mipmaps;
  13650. if (isCompressed) {
  13651. for (var i = 0; i < 6; i++) {
  13652. mipmaps = cubeImage[i].mipmaps;
  13653. for (var j = 0; j < mipmaps.length; j++) {
  13654. var mipmap = mipmaps[j];
  13655. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13656. if (glFormat !== null) {
  13657. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13658. } else {
  13659. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13660. }
  13661. } else {
  13662. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13663. }
  13664. }
  13665. }
  13666. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13667. } else {
  13668. mipmaps = texture.mipmaps;
  13669. for (var i = 0; i < 6; i++) {
  13670. if (isDataTexture) {
  13671. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13672. for (var j = 0; j < mipmaps.length; j++) {
  13673. var mipmap = mipmaps[j];
  13674. var mipmapImage = mipmap.image[i].image;
  13675. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13676. }
  13677. } else {
  13678. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13679. for (var j = 0; j < mipmaps.length; j++) {
  13680. var mipmap = mipmaps[j];
  13681. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13682. }
  13683. }
  13684. }
  13685. textureProperties.__maxMipLevel = mipmaps.length;
  13686. }
  13687. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13688. // We assume images for cube map have the same size.
  13689. generateMipmap(34067, texture, image.width, image.height);
  13690. }
  13691. textureProperties.__version = texture.version;
  13692. if (texture.onUpdate) texture.onUpdate(texture);
  13693. } else {
  13694. state.activeTexture(33984 + slot);
  13695. state.bindTexture(34067, textureProperties.__webglTexture);
  13696. }
  13697. }
  13698. function setTextureCubeDynamic(texture, slot) {
  13699. state.activeTexture(33984 + slot);
  13700. state.bindTexture(34067, properties.get(texture).__webglTexture);
  13701. }
  13702. var wrappingToGL = {
  13703. [RepeatWrapping]: 10497,
  13704. [ClampToEdgeWrapping]: 33071,
  13705. [MirroredRepeatWrapping]: 33648
  13706. };
  13707. var filterToGL = {
  13708. [NearestFilter]: 9728,
  13709. [NearestMipmapNearestFilter]: 9984,
  13710. [NearestMipmapLinearFilter]: 9986,
  13711. [LinearFilter]: 9729,
  13712. [LinearMipmapNearestFilter]: 9985,
  13713. [LinearMipmapLinearFilter]: 9987
  13714. };
  13715. function setTextureParameters(textureType, texture, supportsMips) {
  13716. if (supportsMips) {
  13717. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  13718. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  13719. if (textureType === 32879 || textureType === 35866) {
  13720. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  13721. }
  13722. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  13723. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  13724. } else {
  13725. _gl.texParameteri(textureType, 10242, 33071);
  13726. _gl.texParameteri(textureType, 10243, 33071);
  13727. if (textureType === 32879 || textureType === 35866) {
  13728. _gl.texParameteri(textureType, 32882, 33071);
  13729. }
  13730. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13731. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13732. }
  13733. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13734. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13735. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13736. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13737. }
  13738. }
  13739. var extension = extensions.get('EXT_texture_filter_anisotropic');
  13740. if (extension) {
  13741. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13742. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13743. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13744. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13745. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13746. }
  13747. }
  13748. }
  13749. function initTexture(textureProperties, texture) {
  13750. if (textureProperties.__webglInit === undefined) {
  13751. textureProperties.__webglInit = true;
  13752. texture.addEventListener('dispose', onTextureDispose);
  13753. textureProperties.__webglTexture = _gl.createTexture();
  13754. info.memory.textures++;
  13755. }
  13756. }
  13757. function uploadTexture(textureProperties, texture, slot) {
  13758. var textureType = 3553;
  13759. if (texture.isDataTexture2DArray) textureType = 35866;
  13760. if (texture.isDataTexture3D) textureType = 32879;
  13761. initTexture(textureProperties, texture);
  13762. state.activeTexture(33984 + slot);
  13763. state.bindTexture(textureType, textureProperties.__webglTexture);
  13764. _gl.pixelStorei(37440, texture.flipY);
  13765. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13766. _gl.pixelStorei(3317, texture.unpackAlignment);
  13767. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13768. var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13769. var supportsMips = isPowerOfTwo(image) || isWebGL2,
  13770. glFormat = utils.convert(texture.format),
  13771. glType = utils.convert(texture.type),
  13772. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13773. setTextureParameters(textureType, texture, supportsMips);
  13774. var mipmap,
  13775. mipmaps = texture.mipmaps;
  13776. if (texture.isDepthTexture) {
  13777. // populate depth texture with dummy data
  13778. glInternalFormat = 6402;
  13779. if (isWebGL2) {
  13780. if (texture.type === FloatType) {
  13781. glInternalFormat = 36012;
  13782. } else if (texture.type === UnsignedIntType) {
  13783. glInternalFormat = 33190;
  13784. } else if (texture.type === UnsignedInt248Type) {
  13785. glInternalFormat = 35056;
  13786. } else {
  13787. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13788. }
  13789. } else {
  13790. if (texture.type === FloatType) {
  13791. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13792. }
  13793. } // validation checks for WebGL 1
  13794. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13795. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13796. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13797. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13798. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13799. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13800. texture.type = UnsignedShortType;
  13801. glType = utils.convert(texture.type);
  13802. }
  13803. }
  13804. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  13805. // Depth stencil textures need the DEPTH_STENCIL internal format
  13806. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13807. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13808. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13809. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13810. if (texture.type !== UnsignedInt248Type) {
  13811. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13812. texture.type = UnsignedInt248Type;
  13813. glType = utils.convert(texture.type);
  13814. }
  13815. } //
  13816. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13817. } else if (texture.isDataTexture) {
  13818. // use manually created mipmaps if available
  13819. // if there are no manual mipmaps
  13820. // set 0 level mipmap and then use GL to generate other mipmap levels
  13821. if (mipmaps.length > 0 && supportsMips) {
  13822. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13823. mipmap = mipmaps[i];
  13824. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13825. }
  13826. texture.generateMipmaps = false;
  13827. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13828. } else {
  13829. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13830. textureProperties.__maxMipLevel = 0;
  13831. }
  13832. } else if (texture.isCompressedTexture) {
  13833. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13834. mipmap = mipmaps[i];
  13835. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13836. if (glFormat !== null) {
  13837. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13838. } else {
  13839. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13840. }
  13841. } else {
  13842. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13843. }
  13844. }
  13845. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13846. } else if (texture.isDataTexture2DArray) {
  13847. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13848. textureProperties.__maxMipLevel = 0;
  13849. } else if (texture.isDataTexture3D) {
  13850. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13851. textureProperties.__maxMipLevel = 0;
  13852. } else {
  13853. // regular Texture (image, video, canvas)
  13854. // use manually created mipmaps if available
  13855. // if there are no manual mipmaps
  13856. // set 0 level mipmap and then use GL to generate other mipmap levels
  13857. if (mipmaps.length > 0 && supportsMips) {
  13858. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13859. mipmap = mipmaps[i];
  13860. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13861. }
  13862. texture.generateMipmaps = false;
  13863. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13864. } else {
  13865. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13866. textureProperties.__maxMipLevel = 0;
  13867. }
  13868. }
  13869. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13870. generateMipmap(textureType, texture, image.width, image.height);
  13871. }
  13872. textureProperties.__version = texture.version;
  13873. if (texture.onUpdate) texture.onUpdate(texture);
  13874. } // Render targets
  13875. // Setup storage for target texture and bind it to correct framebuffer
  13876. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13877. var glFormat = utils.convert(renderTarget.texture.format);
  13878. var glType = utils.convert(renderTarget.texture.type);
  13879. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13880. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13881. _gl.bindFramebuffer(36160, framebuffer);
  13882. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13883. _gl.bindFramebuffer(36160, null);
  13884. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13885. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13886. _gl.bindRenderbuffer(36161, renderbuffer);
  13887. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13888. var glInternalFormat = 33189;
  13889. if (isMultisample) {
  13890. var depthTexture = renderTarget.depthTexture;
  13891. if (depthTexture && depthTexture.isDepthTexture) {
  13892. if (depthTexture.type === FloatType) {
  13893. glInternalFormat = 36012;
  13894. } else if (depthTexture.type === UnsignedIntType) {
  13895. glInternalFormat = 33190;
  13896. }
  13897. }
  13898. var samples = getRenderTargetSamples(renderTarget);
  13899. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13900. } else {
  13901. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13902. }
  13903. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13904. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13905. if (isMultisample) {
  13906. var samples = getRenderTargetSamples(renderTarget);
  13907. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13908. } else {
  13909. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13910. }
  13911. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13912. } else {
  13913. var glFormat = utils.convert(renderTarget.texture.format);
  13914. var glType = utils.convert(renderTarget.texture.type);
  13915. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13916. if (isMultisample) {
  13917. var samples = getRenderTargetSamples(renderTarget);
  13918. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13919. } else {
  13920. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13921. }
  13922. }
  13923. _gl.bindRenderbuffer(36161, null);
  13924. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13925. function setupDepthTexture(framebuffer, renderTarget) {
  13926. var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13927. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13928. _gl.bindFramebuffer(36160, framebuffer);
  13929. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13930. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13931. } // upload an empty depth texture with framebuffer size
  13932. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13933. renderTarget.depthTexture.image.width = renderTarget.width;
  13934. renderTarget.depthTexture.image.height = renderTarget.height;
  13935. renderTarget.depthTexture.needsUpdate = true;
  13936. }
  13937. setTexture2D(renderTarget.depthTexture, 0);
  13938. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13939. if (renderTarget.depthTexture.format === DepthFormat) {
  13940. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13941. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13942. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13943. } else {
  13944. throw new Error('Unknown depthTexture format');
  13945. }
  13946. } // Setup GL resources for a non-texture depth buffer
  13947. function setupDepthRenderbuffer(renderTarget) {
  13948. var renderTargetProperties = properties.get(renderTarget);
  13949. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13950. if (renderTarget.depthTexture) {
  13951. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13952. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13953. } else {
  13954. if (isCube) {
  13955. renderTargetProperties.__webglDepthbuffer = [];
  13956. for (var i = 0; i < 6; i++) {
  13957. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13958. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13959. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13960. }
  13961. } else {
  13962. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13963. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13964. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13965. }
  13966. }
  13967. _gl.bindFramebuffer(36160, null);
  13968. } // Set up GL resources for the render target
  13969. function setupRenderTarget(renderTarget) {
  13970. var renderTargetProperties = properties.get(renderTarget);
  13971. var textureProperties = properties.get(renderTarget.texture);
  13972. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13973. textureProperties.__webglTexture = _gl.createTexture();
  13974. info.memory.textures++;
  13975. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13976. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13977. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13978. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  13979. renderTarget.texture.format = RGBAFormat;
  13980. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13981. } // Setup framebuffer
  13982. if (isCube) {
  13983. renderTargetProperties.__webglFramebuffer = [];
  13984. for (var i = 0; i < 6; i++) {
  13985. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13986. }
  13987. } else {
  13988. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13989. if (isMultisample) {
  13990. if (isWebGL2) {
  13991. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13992. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13993. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13994. var glFormat = utils.convert(renderTarget.texture.format);
  13995. var glType = utils.convert(renderTarget.texture.type);
  13996. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13997. var samples = getRenderTargetSamples(renderTarget);
  13998. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13999. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14000. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14001. _gl.bindRenderbuffer(36161, null);
  14002. if (renderTarget.depthBuffer) {
  14003. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14004. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14005. }
  14006. _gl.bindFramebuffer(36160, null);
  14007. } else {
  14008. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14009. }
  14010. }
  14011. } // Setup color buffer
  14012. if (isCube) {
  14013. state.bindTexture(34067, textureProperties.__webglTexture);
  14014. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14015. for (var i = 0; i < 6; i++) {
  14016. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14017. }
  14018. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14019. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14020. }
  14021. state.bindTexture(34067, null);
  14022. } else {
  14023. state.bindTexture(3553, textureProperties.__webglTexture);
  14024. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14025. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14026. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14027. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14028. }
  14029. state.bindTexture(3553, null);
  14030. } // Setup depth and stencil buffers
  14031. if (renderTarget.depthBuffer) {
  14032. setupDepthRenderbuffer(renderTarget);
  14033. }
  14034. }
  14035. function updateRenderTargetMipmap(renderTarget) {
  14036. var texture = renderTarget.texture;
  14037. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  14038. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14039. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14040. var webglTexture = properties.get(texture).__webglTexture;
  14041. state.bindTexture(target, webglTexture);
  14042. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14043. state.bindTexture(target, null);
  14044. }
  14045. }
  14046. function updateMultisampleRenderTarget(renderTarget) {
  14047. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14048. if (isWebGL2) {
  14049. var renderTargetProperties = properties.get(renderTarget);
  14050. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14051. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14052. var width = renderTarget.width;
  14053. var height = renderTarget.height;
  14054. var mask = 16384;
  14055. if (renderTarget.depthBuffer) mask |= 256;
  14056. if (renderTarget.stencilBuffer) mask |= 1024;
  14057. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14058. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  14059. } else {
  14060. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14061. }
  14062. }
  14063. }
  14064. function getRenderTargetSamples(renderTarget) {
  14065. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  14066. }
  14067. function updateVideoTexture(texture) {
  14068. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14069. if (_videoTextures.get(texture) !== frame) {
  14070. _videoTextures.set(texture, frame);
  14071. texture.update();
  14072. }
  14073. } // backwards compatibility
  14074. var warnedTexture2D = false;
  14075. var warnedTextureCube = false;
  14076. function safeSetTexture2D(texture, slot) {
  14077. if (texture && texture.isWebGLRenderTarget) {
  14078. if (warnedTexture2D === false) {
  14079. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14080. warnedTexture2D = true;
  14081. }
  14082. texture = texture.texture;
  14083. }
  14084. setTexture2D(texture, slot);
  14085. }
  14086. function safeSetTextureCube(texture, slot) {
  14087. if (texture && texture.isWebGLCubeRenderTarget) {
  14088. if (warnedTextureCube === false) {
  14089. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14090. warnedTextureCube = true;
  14091. }
  14092. texture = texture.texture;
  14093. } // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
  14094. // TODO: unify these code paths
  14095. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14096. // CompressedTexture can have Array in image :/
  14097. // this function alone should take care of cube textures
  14098. setTextureCube(texture, slot);
  14099. } else {
  14100. // assumed: texture property of THREE.WebGLCubeRenderTarget
  14101. setTextureCubeDynamic(texture, slot);
  14102. }
  14103. } //
  14104. this.allocateTextureUnit = allocateTextureUnit;
  14105. this.resetTextureUnits = resetTextureUnits;
  14106. this.setTexture2D = setTexture2D;
  14107. this.setTexture2DArray = setTexture2DArray;
  14108. this.setTexture3D = setTexture3D;
  14109. this.setTextureCube = setTextureCube;
  14110. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14111. this.setupRenderTarget = setupRenderTarget;
  14112. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14113. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14114. this.safeSetTexture2D = safeSetTexture2D;
  14115. this.safeSetTextureCube = safeSetTextureCube;
  14116. }
  14117. /**
  14118. * @author thespite / http://www.twitter.com/thespite
  14119. */
  14120. function WebGLUtils(gl, extensions, capabilities) {
  14121. var isWebGL2 = capabilities.isWebGL2;
  14122. function convert(p) {
  14123. var extension;
  14124. if (p === UnsignedByteType) return 5121;
  14125. if (p === UnsignedShort4444Type) return 32819;
  14126. if (p === UnsignedShort5551Type) return 32820;
  14127. if (p === UnsignedShort565Type) return 33635;
  14128. if (p === ByteType) return 5120;
  14129. if (p === ShortType) return 5122;
  14130. if (p === UnsignedShortType) return 5123;
  14131. if (p === IntType) return 5124;
  14132. if (p === UnsignedIntType) return 5125;
  14133. if (p === FloatType) return 5126;
  14134. if (p === HalfFloatType) {
  14135. if (isWebGL2) return 5131;
  14136. extension = extensions.get('OES_texture_half_float');
  14137. if (extension !== null) {
  14138. return extension.HALF_FLOAT_OES;
  14139. } else {
  14140. return null;
  14141. }
  14142. }
  14143. if (p === AlphaFormat) return 6406;
  14144. if (p === RGBFormat) return 6407;
  14145. if (p === RGBAFormat) return 6408;
  14146. if (p === LuminanceFormat) return 6409;
  14147. if (p === LuminanceAlphaFormat) return 6410;
  14148. if (p === DepthFormat) return 6402;
  14149. if (p === DepthStencilFormat) return 34041;
  14150. if (p === RedFormat) return 6403; // WebGL2 formats.
  14151. if (p === RedIntegerFormat) return 36244;
  14152. if (p === RGFormat) return 33319;
  14153. if (p === RGIntegerFormat) return 33320;
  14154. if (p === RGBIntegerFormat) return 36248;
  14155. if (p === RGBAIntegerFormat) return 36249;
  14156. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14157. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14158. if (extension !== null) {
  14159. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14160. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14161. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14162. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14163. } else {
  14164. return null;
  14165. }
  14166. }
  14167. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14168. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14169. if (extension !== null) {
  14170. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14171. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14172. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14173. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14174. } else {
  14175. return null;
  14176. }
  14177. }
  14178. if (p === RGB_ETC1_Format) {
  14179. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14180. if (extension !== null) {
  14181. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14182. } else {
  14183. return null;
  14184. }
  14185. }
  14186. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14187. extension = extensions.get('WEBGL_compressed_texture_etc');
  14188. if (extension !== null) {
  14189. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14190. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14191. }
  14192. }
  14193. 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) {
  14194. extension = extensions.get('WEBGL_compressed_texture_astc');
  14195. if (extension !== null) {
  14196. // TODO Complete?
  14197. return p;
  14198. } else {
  14199. return null;
  14200. }
  14201. }
  14202. if (p === RGBA_BPTC_Format) {
  14203. extension = extensions.get('EXT_texture_compression_bptc');
  14204. if (extension !== null) {
  14205. // TODO Complete?
  14206. return p;
  14207. } else {
  14208. return null;
  14209. }
  14210. }
  14211. if (p === UnsignedInt248Type) {
  14212. if (isWebGL2) return 34042;
  14213. extension = extensions.get('WEBGL_depth_texture');
  14214. if (extension !== null) {
  14215. return extension.UNSIGNED_INT_24_8_WEBGL;
  14216. } else {
  14217. return null;
  14218. }
  14219. }
  14220. }
  14221. return {
  14222. convert: convert
  14223. };
  14224. }
  14225. /**
  14226. * @author mrdoob / http://mrdoob.com/
  14227. */
  14228. function ArrayCamera(array) {
  14229. PerspectiveCamera.call(this);
  14230. this.cameras = array || [];
  14231. }
  14232. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  14233. constructor: ArrayCamera,
  14234. isArrayCamera: true
  14235. });
  14236. /**
  14237. * @author mrdoob / http://mrdoob.com/
  14238. */
  14239. function Group() {
  14240. Object3D.call(this);
  14241. this.type = 'Group';
  14242. }
  14243. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  14244. constructor: Group,
  14245. isGroup: true
  14246. });
  14247. /**
  14248. * @author mrdoob / http://mrdoob.com/
  14249. */
  14250. function WebXRManager(renderer, gl) {
  14251. var scope = this;
  14252. var session = null;
  14253. var framebufferScaleFactor = 1.0;
  14254. var referenceSpace = null;
  14255. var referenceSpaceType = 'local-floor';
  14256. var pose = null;
  14257. var controllers = [];
  14258. var inputSourcesMap = new Map(); //
  14259. var cameraL = new PerspectiveCamera();
  14260. cameraL.layers.enable(1);
  14261. cameraL.viewport = new Vector4();
  14262. var cameraR = new PerspectiveCamera();
  14263. cameraR.layers.enable(2);
  14264. cameraR.viewport = new Vector4();
  14265. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14266. cameraVR.layers.enable(1);
  14267. cameraVR.layers.enable(2);
  14268. var _currentDepthNear = null;
  14269. var _currentDepthFar = null; //
  14270. this.enabled = false;
  14271. this.isPresenting = false;
  14272. this.getController = function (id) {
  14273. var controller = controllers[id];
  14274. if (controller === undefined) {
  14275. controller = {};
  14276. controllers[id] = controller;
  14277. }
  14278. if (controller.targetRay === undefined) {
  14279. controller.targetRay = new Group();
  14280. controller.targetRay.matrixAutoUpdate = false;
  14281. controller.targetRay.visible = false;
  14282. }
  14283. return controller.targetRay;
  14284. };
  14285. this.getControllerGrip = function (id) {
  14286. var controller = controllers[id];
  14287. if (controller === undefined) {
  14288. controller = {};
  14289. controllers[id] = controller;
  14290. }
  14291. if (controller.grip === undefined) {
  14292. controller.grip = new Group();
  14293. controller.grip.matrixAutoUpdate = false;
  14294. controller.grip.visible = false;
  14295. }
  14296. return controller.grip;
  14297. }; //
  14298. function onSessionEvent(event) {
  14299. var controller = inputSourcesMap.get(event.inputSource);
  14300. if (controller) {
  14301. if (controller.targetRay) {
  14302. controller.targetRay.dispatchEvent({
  14303. type: event.type
  14304. });
  14305. }
  14306. if (controller.grip) {
  14307. controller.grip.dispatchEvent({
  14308. type: event.type
  14309. });
  14310. }
  14311. }
  14312. }
  14313. function onSessionEnd() {
  14314. inputSourcesMap.forEach(function (controller, inputSource) {
  14315. if (controller.targetRay) {
  14316. controller.targetRay.dispatchEvent({
  14317. type: 'disconnected',
  14318. data: inputSource
  14319. });
  14320. controller.targetRay.visible = false;
  14321. }
  14322. if (controller.grip) {
  14323. controller.grip.dispatchEvent({
  14324. type: 'disconnected',
  14325. data: inputSource
  14326. });
  14327. controller.grip.visible = false;
  14328. }
  14329. });
  14330. inputSourcesMap.clear(); //
  14331. renderer.setFramebuffer(null);
  14332. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  14333. animation.stop();
  14334. scope.isPresenting = false;
  14335. scope.dispatchEvent({
  14336. type: 'sessionend'
  14337. });
  14338. }
  14339. function onRequestReferenceSpace(value) {
  14340. referenceSpace = value;
  14341. animation.setContext(session);
  14342. animation.start();
  14343. scope.isPresenting = true;
  14344. scope.dispatchEvent({
  14345. type: 'sessionstart'
  14346. });
  14347. }
  14348. this.setFramebufferScaleFactor = function (value) {
  14349. framebufferScaleFactor = value; // Warn if function is used while presenting
  14350. if (scope.isPresenting == true) {
  14351. console.warn("WebXRManager: Cannot change framebuffer scale while presenting VR content");
  14352. }
  14353. };
  14354. this.setReferenceSpaceType = function (value) {
  14355. referenceSpaceType = value;
  14356. };
  14357. this.getReferenceSpace = function () {
  14358. return referenceSpace;
  14359. };
  14360. this.getSession = function () {
  14361. return session;
  14362. };
  14363. this.setSession = function (value) {
  14364. session = value;
  14365. if (session !== null) {
  14366. session.addEventListener('select', onSessionEvent);
  14367. session.addEventListener('selectstart', onSessionEvent);
  14368. session.addEventListener('selectend', onSessionEvent);
  14369. session.addEventListener('squeeze', onSessionEvent);
  14370. session.addEventListener('squeezestart', onSessionEvent);
  14371. session.addEventListener('squeezeend', onSessionEvent);
  14372. session.addEventListener('end', onSessionEnd);
  14373. var attributes = gl.getContextAttributes();
  14374. var layerInit = {
  14375. antialias: attributes.antialias,
  14376. alpha: attributes.alpha,
  14377. depth: attributes.depth,
  14378. stencil: attributes.stencil,
  14379. framebufferScaleFactor: framebufferScaleFactor
  14380. }; // eslint-disable-next-line no-undef
  14381. var baseLayer = new XRWebGLLayer(session, gl, layerInit);
  14382. session.updateRenderState({
  14383. baseLayer: baseLayer
  14384. });
  14385. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14386. session.addEventListener('inputsourceschange', updateInputSources);
  14387. }
  14388. };
  14389. function updateInputSources(event) {
  14390. var inputSources = session.inputSources; // Assign inputSources to available controllers
  14391. for (var i = 0; i < controllers.length; i++) {
  14392. inputSourcesMap.set(inputSources[i], controllers[i]);
  14393. } // Notify disconnected
  14394. for (var i = 0; i < event.removed.length; i++) {
  14395. var inputSource = event.removed[i];
  14396. var controller = inputSourcesMap.get(inputSource);
  14397. if (controller) {
  14398. if (controller.targetRay) {
  14399. controller.targetRay.dispatchEvent({
  14400. type: 'disconnected',
  14401. data: inputSource
  14402. });
  14403. }
  14404. if (controller.grip) {
  14405. controller.grip.dispatchEvent({
  14406. type: 'disconnected',
  14407. data: inputSource
  14408. });
  14409. }
  14410. inputSourcesMap.delete(inputSource);
  14411. }
  14412. } // Notify connected
  14413. for (var i = 0; i < event.added.length; i++) {
  14414. var inputSource = event.added[i];
  14415. var controller = inputSourcesMap.get(inputSource);
  14416. if (controller) {
  14417. if (controller.targetRay) {
  14418. controller.targetRay.dispatchEvent({
  14419. type: 'connected',
  14420. data: inputSource
  14421. });
  14422. }
  14423. if (controller.grip) {
  14424. controller.grip.dispatchEvent({
  14425. type: 'connected',
  14426. data: inputSource
  14427. });
  14428. }
  14429. }
  14430. }
  14431. } //
  14432. var cameraLPos = new Vector3();
  14433. var cameraRPos = new Vector3();
  14434. /**
  14435. * @author jsantell / https://www.jsantell.com/
  14436. *
  14437. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14438. * the cameras' projection and world matrices have already been set.
  14439. * And that near and far planes are identical for both cameras.
  14440. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14441. */
  14442. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14443. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14444. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14445. var ipd = cameraLPos.distanceTo(cameraRPos);
  14446. var projL = cameraL.projectionMatrix.elements;
  14447. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14448. // most likely identical top and bottom frustum extents.
  14449. // Use the left camera for these values.
  14450. var near = projL[14] / (projL[10] - 1);
  14451. var far = projL[14] / (projL[10] + 1);
  14452. var topFov = (projL[9] + 1) / projL[5];
  14453. var bottomFov = (projL[9] - 1) / projL[5];
  14454. var leftFov = (projL[8] - 1) / projL[0];
  14455. var rightFov = (projR[8] + 1) / projR[0];
  14456. var left = near * leftFov;
  14457. var right = near * rightFov; // Calculate the new camera's position offset from the
  14458. // left camera. xOffset should be roughly half `ipd`.
  14459. var zOffset = ipd / (-leftFov + rightFov);
  14460. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14461. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14462. camera.translateX(xOffset);
  14463. camera.translateZ(zOffset);
  14464. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14465. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  14466. // the values so that the near plane's position does not change in world space,
  14467. // although must now be relative to the new union camera.
  14468. var near2 = near + zOffset;
  14469. var far2 = far + zOffset;
  14470. var left2 = left - xOffset;
  14471. var right2 = right + (ipd - xOffset);
  14472. var top2 = topFov * far / far2 * near2;
  14473. var bottom2 = bottomFov * far / far2 * near2;
  14474. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14475. }
  14476. function updateCamera(camera, parent) {
  14477. if (parent === null) {
  14478. camera.matrixWorld.copy(camera.matrix);
  14479. } else {
  14480. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14481. }
  14482. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  14483. }
  14484. this.getCamera = function (camera) {
  14485. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14486. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14487. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14488. // Note that the new renderState won't apply until the next frame. See #18320
  14489. session.updateRenderState({
  14490. depthNear: cameraVR.near,
  14491. depthFar: cameraVR.far
  14492. });
  14493. _currentDepthNear = cameraVR.near;
  14494. _currentDepthFar = cameraVR.far;
  14495. }
  14496. var parent = camera.parent;
  14497. var cameras = cameraVR.cameras;
  14498. updateCamera(cameraVR, parent);
  14499. for (var i = 0; i < cameras.length; i++) {
  14500. updateCamera(cameras[i], parent);
  14501. } // update camera and its children
  14502. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14503. var children = camera.children;
  14504. for (var i = 0, l = children.length; i < l; i++) {
  14505. children[i].updateMatrixWorld(true);
  14506. }
  14507. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14508. return cameraVR;
  14509. }; // Animation Loop
  14510. var onAnimationFrameCallback = null;
  14511. function onAnimationFrame(time, frame) {
  14512. pose = frame.getViewerPose(referenceSpace);
  14513. if (pose !== null) {
  14514. var views = pose.views;
  14515. var baseLayer = session.renderState.baseLayer;
  14516. renderer.setFramebuffer(baseLayer.framebuffer);
  14517. for (var i = 0; i < views.length; i++) {
  14518. var view = views[i];
  14519. var viewport = baseLayer.getViewport(view);
  14520. var camera = cameraVR.cameras[i];
  14521. camera.matrix.fromArray(view.transform.matrix);
  14522. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14523. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14524. if (i === 0) {
  14525. cameraVR.matrix.copy(camera.matrix);
  14526. }
  14527. }
  14528. } //
  14529. var inputSources = session.inputSources;
  14530. for (var i = 0; i < controllers.length; i++) {
  14531. var controller = controllers[i];
  14532. var inputSource = inputSources[i];
  14533. var inputPose = null;
  14534. var gripPose = null;
  14535. if (inputSource) {
  14536. if (controller.targetRay) {
  14537. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14538. if (inputPose !== null) {
  14539. controller.targetRay.matrix.fromArray(inputPose.transform.matrix);
  14540. controller.targetRay.matrix.decompose(controller.targetRay.position, controller.targetRay.rotation, controller.targetRay.scale);
  14541. }
  14542. }
  14543. if (controller.grip && inputSource.gripSpace) {
  14544. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14545. if (gripPose !== null) {
  14546. controller.grip.matrix.fromArray(gripPose.transform.matrix);
  14547. controller.grip.matrix.decompose(controller.grip.position, controller.grip.rotation, controller.grip.scale);
  14548. }
  14549. }
  14550. }
  14551. if (controller.targetRay) {
  14552. controller.targetRay.visible = inputPose !== null;
  14553. }
  14554. if (controller.grip) {
  14555. controller.grip.visible = gripPose !== null;
  14556. }
  14557. }
  14558. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14559. }
  14560. var animation = new WebGLAnimation();
  14561. animation.setAnimationLoop(onAnimationFrame);
  14562. this.setAnimationLoop = function (callback) {
  14563. onAnimationFrameCallback = callback;
  14564. };
  14565. this.dispose = function () {};
  14566. }
  14567. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14568. /**
  14569. * @author supereggbert / http://www.paulbrunt.co.uk/
  14570. * @author mrdoob / http://mrdoob.com/
  14571. * @author alteredq / http://alteredqualia.com/
  14572. * @author szimek / https://github.com/szimek/
  14573. * @author tschw
  14574. */
  14575. function WebGLRenderer(parameters) {
  14576. parameters = parameters || {};
  14577. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  14578. _context = parameters.context !== undefined ? parameters.context : null,
  14579. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14580. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14581. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14582. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14583. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14584. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14585. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14586. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14587. var currentRenderList = null;
  14588. var currentRenderState = null; // public properties
  14589. this.domElement = _canvas; // Debug configuration container
  14590. this.debug = {
  14591. /**
  14592. * Enables error checking and reporting when shader programs are being compiled
  14593. * @type {boolean}
  14594. */
  14595. checkShaderErrors: true
  14596. }; // clearing
  14597. this.autoClear = true;
  14598. this.autoClearColor = true;
  14599. this.autoClearDepth = true;
  14600. this.autoClearStencil = true; // scene graph
  14601. this.sortObjects = true; // user-defined clipping
  14602. this.clippingPlanes = [];
  14603. this.localClippingEnabled = false; // physically based shading
  14604. this.gammaFactor = 2.0; // for backwards compatibility
  14605. this.outputEncoding = LinearEncoding; // physical lights
  14606. this.physicallyCorrectLights = false; // tone mapping
  14607. this.toneMapping = LinearToneMapping;
  14608. this.toneMappingExposure = 1.0;
  14609. this.toneMappingWhitePoint = 1.0; // morphs
  14610. this.maxMorphTargets = 8;
  14611. this.maxMorphNormals = 4; // internal properties
  14612. var _this = this,
  14613. _isContextLost = false,
  14614. // internal state cache
  14615. _framebuffer = null,
  14616. _currentActiveCubeFace = 0,
  14617. _currentActiveMipmapLevel = 0,
  14618. _currentRenderTarget = null,
  14619. _currentFramebuffer = null,
  14620. _currentMaterialId = -1,
  14621. // geometry and program caching
  14622. _currentGeometryProgram = {
  14623. geometry: null,
  14624. program: null,
  14625. wireframe: false
  14626. },
  14627. _currentCamera = null,
  14628. _currentArrayCamera = null,
  14629. _currentViewport = new Vector4(),
  14630. _currentScissor = new Vector4(),
  14631. _currentScissorTest = null,
  14632. //
  14633. _width = _canvas.width,
  14634. _height = _canvas.height,
  14635. _pixelRatio = 1,
  14636. _opaqueSort = null,
  14637. _transparentSort = null,
  14638. _viewport = new Vector4(0, 0, _width, _height),
  14639. _scissor = new Vector4(0, 0, _width, _height),
  14640. _scissorTest = false,
  14641. // frustum
  14642. _frustum = new Frustum(),
  14643. // clipping
  14644. _clipping = new WebGLClipping(),
  14645. _clippingEnabled = false,
  14646. _localClippingEnabled = false,
  14647. // camera matrices cache
  14648. _projScreenMatrix = new Matrix4(),
  14649. _vector3 = new Vector3();
  14650. function getTargetPixelRatio() {
  14651. return _currentRenderTarget === null ? _pixelRatio : 1;
  14652. } // initialize
  14653. var _gl;
  14654. try {
  14655. var contextAttributes = {
  14656. alpha: _alpha,
  14657. depth: _depth,
  14658. stencil: _stencil,
  14659. antialias: _antialias,
  14660. premultipliedAlpha: _premultipliedAlpha,
  14661. preserveDrawingBuffer: _preserveDrawingBuffer,
  14662. powerPreference: _powerPreference,
  14663. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  14664. xrCompatible: true
  14665. }; // event listeners must be registered before WebGL context is created, see #12753
  14666. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14667. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14668. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  14669. if (_gl === null) {
  14670. if (_canvas.getContext('webgl') !== null) {
  14671. throw new Error('Error creating WebGL context with your selected attributes.');
  14672. } else {
  14673. throw new Error('Error creating WebGL context.');
  14674. }
  14675. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14676. if (_gl.getShaderPrecisionFormat === undefined) {
  14677. _gl.getShaderPrecisionFormat = function () {
  14678. return {
  14679. 'rangeMin': 1,
  14680. 'rangeMax': 1,
  14681. 'precision': 1
  14682. };
  14683. };
  14684. }
  14685. } catch (error) {
  14686. console.error('THREE.WebGLRenderer: ' + error.message);
  14687. throw error;
  14688. }
  14689. var extensions, capabilities, state, info;
  14690. var properties, textures, attributes, geometries, objects;
  14691. var programCache, renderLists, renderStates;
  14692. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14693. var utils;
  14694. function initGLContext() {
  14695. extensions = new WebGLExtensions(_gl);
  14696. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14697. if (capabilities.isWebGL2 === false) {
  14698. extensions.get('WEBGL_depth_texture');
  14699. extensions.get('OES_texture_float');
  14700. extensions.get('OES_texture_half_float');
  14701. extensions.get('OES_texture_half_float_linear');
  14702. extensions.get('OES_standard_derivatives');
  14703. extensions.get('OES_element_index_uint');
  14704. extensions.get('ANGLE_instanced_arrays');
  14705. }
  14706. extensions.get('OES_texture_float_linear');
  14707. utils = new WebGLUtils(_gl, extensions, capabilities);
  14708. state = new WebGLState(_gl, extensions, capabilities);
  14709. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14710. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14711. info = new WebGLInfo(_gl);
  14712. properties = new WebGLProperties();
  14713. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14714. attributes = new WebGLAttributes(_gl, capabilities);
  14715. geometries = new WebGLGeometries(_gl, attributes, info);
  14716. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14717. morphtargets = new WebGLMorphtargets(_gl);
  14718. programCache = new WebGLPrograms(_this, extensions, capabilities);
  14719. renderLists = new WebGLRenderLists();
  14720. renderStates = new WebGLRenderStates();
  14721. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  14722. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14723. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14724. info.programs = programCache.programs;
  14725. _this.capabilities = capabilities;
  14726. _this.extensions = extensions;
  14727. _this.properties = properties;
  14728. _this.renderLists = renderLists;
  14729. _this.state = state;
  14730. _this.info = info;
  14731. }
  14732. initGLContext(); // xr
  14733. var xr = new WebXRManager(_this, _gl);
  14734. this.xr = xr; // shadow map
  14735. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14736. this.shadowMap = shadowMap; // API
  14737. this.getContext = function () {
  14738. return _gl;
  14739. };
  14740. this.getContextAttributes = function () {
  14741. return _gl.getContextAttributes();
  14742. };
  14743. this.forceContextLoss = function () {
  14744. var extension = extensions.get('WEBGL_lose_context');
  14745. if (extension) extension.loseContext();
  14746. };
  14747. this.forceContextRestore = function () {
  14748. var extension = extensions.get('WEBGL_lose_context');
  14749. if (extension) extension.restoreContext();
  14750. };
  14751. this.getPixelRatio = function () {
  14752. return _pixelRatio;
  14753. };
  14754. this.setPixelRatio = function (value) {
  14755. if (value === undefined) return;
  14756. _pixelRatio = value;
  14757. this.setSize(_width, _height, false);
  14758. };
  14759. this.getSize = function (target) {
  14760. if (target === undefined) {
  14761. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14762. target = new Vector2();
  14763. }
  14764. return target.set(_width, _height);
  14765. };
  14766. this.setSize = function (width, height, updateStyle) {
  14767. if (xr.isPresenting) {
  14768. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14769. return;
  14770. }
  14771. _width = width;
  14772. _height = height;
  14773. _canvas.width = Math.floor(width * _pixelRatio);
  14774. _canvas.height = Math.floor(height * _pixelRatio);
  14775. if (updateStyle !== false) {
  14776. _canvas.style.width = width + 'px';
  14777. _canvas.style.height = height + 'px';
  14778. }
  14779. this.setViewport(0, 0, width, height);
  14780. };
  14781. this.getDrawingBufferSize = function (target) {
  14782. if (target === undefined) {
  14783. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14784. target = new Vector2();
  14785. }
  14786. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14787. };
  14788. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14789. _width = width;
  14790. _height = height;
  14791. _pixelRatio = pixelRatio;
  14792. _canvas.width = Math.floor(width * pixelRatio);
  14793. _canvas.height = Math.floor(height * pixelRatio);
  14794. this.setViewport(0, 0, width, height);
  14795. };
  14796. this.getCurrentViewport = function (target) {
  14797. if (target === undefined) {
  14798. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14799. target = new Vector4();
  14800. }
  14801. return target.copy(_currentViewport);
  14802. };
  14803. this.getViewport = function (target) {
  14804. return target.copy(_viewport);
  14805. };
  14806. this.setViewport = function (x, y, width, height) {
  14807. if (x.isVector4) {
  14808. _viewport.set(x.x, x.y, x.z, x.w);
  14809. } else {
  14810. _viewport.set(x, y, width, height);
  14811. }
  14812. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14813. };
  14814. this.getScissor = function (target) {
  14815. return target.copy(_scissor);
  14816. };
  14817. this.setScissor = function (x, y, width, height) {
  14818. if (x.isVector4) {
  14819. _scissor.set(x.x, x.y, x.z, x.w);
  14820. } else {
  14821. _scissor.set(x, y, width, height);
  14822. }
  14823. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14824. };
  14825. this.getScissorTest = function () {
  14826. return _scissorTest;
  14827. };
  14828. this.setScissorTest = function (boolean) {
  14829. state.setScissorTest(_scissorTest = boolean);
  14830. };
  14831. this.setOpaqueSort = function (method) {
  14832. _opaqueSort = method;
  14833. };
  14834. this.setTransparentSort = function (method) {
  14835. _transparentSort = method;
  14836. }; // Clearing
  14837. this.getClearColor = function () {
  14838. return background.getClearColor();
  14839. };
  14840. this.setClearColor = function () {
  14841. background.setClearColor.apply(background, arguments);
  14842. };
  14843. this.getClearAlpha = function () {
  14844. return background.getClearAlpha();
  14845. };
  14846. this.setClearAlpha = function () {
  14847. background.setClearAlpha.apply(background, arguments);
  14848. };
  14849. this.clear = function (color, depth, stencil) {
  14850. var bits = 0;
  14851. if (color === undefined || color) bits |= 16384;
  14852. if (depth === undefined || depth) bits |= 256;
  14853. if (stencil === undefined || stencil) bits |= 1024;
  14854. _gl.clear(bits);
  14855. };
  14856. this.clearColor = function () {
  14857. this.clear(true, false, false);
  14858. };
  14859. this.clearDepth = function () {
  14860. this.clear(false, true, false);
  14861. };
  14862. this.clearStencil = function () {
  14863. this.clear(false, false, true);
  14864. }; //
  14865. this.dispose = function () {
  14866. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14867. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14868. renderLists.dispose();
  14869. renderStates.dispose();
  14870. properties.dispose();
  14871. objects.dispose();
  14872. xr.dispose();
  14873. animation.stop();
  14874. this.forceContextLoss();
  14875. }; // Events
  14876. function onContextLost(event) {
  14877. event.preventDefault();
  14878. console.log('THREE.WebGLRenderer: Context Lost.');
  14879. _isContextLost = true;
  14880. }
  14881. function onContextRestore()
  14882. /* event */
  14883. {
  14884. console.log('THREE.WebGLRenderer: Context Restored.');
  14885. _isContextLost = false;
  14886. initGLContext();
  14887. }
  14888. function onMaterialDispose(event) {
  14889. var material = event.target;
  14890. material.removeEventListener('dispose', onMaterialDispose);
  14891. deallocateMaterial(material);
  14892. } // Buffer deallocation
  14893. function deallocateMaterial(material) {
  14894. releaseMaterialProgramReference(material);
  14895. properties.remove(material);
  14896. }
  14897. function releaseMaterialProgramReference(material) {
  14898. var programInfo = properties.get(material).program;
  14899. material.program = undefined;
  14900. if (programInfo !== undefined) {
  14901. programCache.releaseProgram(programInfo);
  14902. }
  14903. } // Buffer rendering
  14904. function renderObjectImmediate(object, program) {
  14905. object.render(function (object) {
  14906. _this.renderBufferImmediate(object, program);
  14907. });
  14908. }
  14909. this.renderBufferImmediate = function (object, program) {
  14910. state.initAttributes();
  14911. var buffers = properties.get(object);
  14912. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14913. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14914. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14915. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14916. var programAttributes = program.getAttributes();
  14917. if (object.hasPositions) {
  14918. _gl.bindBuffer(34962, buffers.position);
  14919. _gl.bufferData(34962, object.positionArray, 35048);
  14920. state.enableAttribute(programAttributes.position);
  14921. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14922. }
  14923. if (object.hasNormals) {
  14924. _gl.bindBuffer(34962, buffers.normal);
  14925. _gl.bufferData(34962, object.normalArray, 35048);
  14926. state.enableAttribute(programAttributes.normal);
  14927. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14928. }
  14929. if (object.hasUvs) {
  14930. _gl.bindBuffer(34962, buffers.uv);
  14931. _gl.bufferData(34962, object.uvArray, 35048);
  14932. state.enableAttribute(programAttributes.uv);
  14933. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14934. }
  14935. if (object.hasColors) {
  14936. _gl.bindBuffer(34962, buffers.color);
  14937. _gl.bufferData(34962, object.colorArray, 35048);
  14938. state.enableAttribute(programAttributes.color);
  14939. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14940. }
  14941. state.disableUnusedAttributes();
  14942. _gl.drawArrays(4, 0, object.count);
  14943. object.count = 0;
  14944. };
  14945. var tempScene = new Scene();
  14946. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14947. if (scene === null) scene = tempScene; // renderBufferDirect second parameter used to be fog (could be null)
  14948. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14949. var program = setProgram(camera, scene, material, object);
  14950. state.setMaterial(material, frontFaceCW);
  14951. var updateBuffers = false;
  14952. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  14953. _currentGeometryProgram.geometry = geometry.id;
  14954. _currentGeometryProgram.program = program.id;
  14955. _currentGeometryProgram.wireframe = material.wireframe === true;
  14956. updateBuffers = true;
  14957. }
  14958. if (material.morphTargets || material.morphNormals) {
  14959. morphtargets.update(object, geometry, material, program);
  14960. updateBuffers = true;
  14961. } //
  14962. var index = geometry.index;
  14963. var position = geometry.attributes.position; //
  14964. if (index === null) {
  14965. if (position === undefined || position.count === 0) return;
  14966. } else if (index.count === 0) {
  14967. return;
  14968. } //
  14969. var rangeFactor = 1;
  14970. if (material.wireframe === true) {
  14971. index = geometries.getWireframeAttribute(geometry);
  14972. rangeFactor = 2;
  14973. }
  14974. var attribute;
  14975. var renderer = bufferRenderer;
  14976. if (index !== null) {
  14977. attribute = attributes.get(index);
  14978. renderer = indexedBufferRenderer;
  14979. renderer.setIndex(attribute);
  14980. }
  14981. if (updateBuffers) {
  14982. setupVertexAttributes(object, geometry, material, program);
  14983. if (index !== null) {
  14984. _gl.bindBuffer(34963, attribute.buffer);
  14985. }
  14986. } //
  14987. var dataCount = index !== null ? index.count : position.count;
  14988. var rangeStart = geometry.drawRange.start * rangeFactor;
  14989. var rangeCount = geometry.drawRange.count * rangeFactor;
  14990. var groupStart = group !== null ? group.start * rangeFactor : 0;
  14991. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14992. var drawStart = Math.max(rangeStart, groupStart);
  14993. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14994. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  14995. if (drawCount === 0) return; //
  14996. if (object.isMesh) {
  14997. if (material.wireframe === true) {
  14998. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14999. renderer.setMode(1);
  15000. } else {
  15001. renderer.setMode(4);
  15002. }
  15003. } else if (object.isLine) {
  15004. var lineWidth = material.linewidth;
  15005. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15006. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15007. if (object.isLineSegments) {
  15008. renderer.setMode(1);
  15009. } else if (object.isLineLoop) {
  15010. renderer.setMode(2);
  15011. } else {
  15012. renderer.setMode(3);
  15013. }
  15014. } else if (object.isPoints) {
  15015. renderer.setMode(0);
  15016. } else if (object.isSprite) {
  15017. renderer.setMode(4);
  15018. }
  15019. if (object.isInstancedMesh) {
  15020. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  15021. } else if (geometry.isInstancedBufferGeometry) {
  15022. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  15023. } else {
  15024. renderer.render(drawStart, drawCount);
  15025. }
  15026. };
  15027. function setupVertexAttributes(object, geometry, material, program) {
  15028. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  15029. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  15030. }
  15031. state.initAttributes();
  15032. var geometryAttributes = geometry.attributes;
  15033. var programAttributes = program.getAttributes();
  15034. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15035. for (var name in programAttributes) {
  15036. var programAttribute = programAttributes[name];
  15037. if (programAttribute >= 0) {
  15038. var geometryAttribute = geometryAttributes[name];
  15039. if (geometryAttribute !== undefined) {
  15040. var normalized = geometryAttribute.normalized;
  15041. var size = geometryAttribute.itemSize;
  15042. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  15043. if (attribute === undefined) continue;
  15044. var buffer = attribute.buffer;
  15045. var type = attribute.type;
  15046. var bytesPerElement = attribute.bytesPerElement;
  15047. if (geometryAttribute.isInterleavedBufferAttribute) {
  15048. var data = geometryAttribute.data;
  15049. var stride = data.stride;
  15050. var offset = geometryAttribute.offset;
  15051. if (data && data.isInstancedInterleavedBuffer) {
  15052. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  15053. if (geometry.maxInstancedCount === undefined) {
  15054. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15055. }
  15056. } else {
  15057. state.enableAttribute(programAttribute);
  15058. }
  15059. _gl.bindBuffer(34962, buffer);
  15060. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  15061. } else {
  15062. if (geometryAttribute.isInstancedBufferAttribute) {
  15063. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  15064. if (geometry.maxInstancedCount === undefined) {
  15065. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15066. }
  15067. } else {
  15068. state.enableAttribute(programAttribute);
  15069. }
  15070. _gl.bindBuffer(34962, buffer);
  15071. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  15072. }
  15073. } else if (name === 'instanceMatrix') {
  15074. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  15075. if (attribute === undefined) continue;
  15076. var buffer = attribute.buffer;
  15077. var type = attribute.type;
  15078. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  15079. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  15080. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  15081. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  15082. _gl.bindBuffer(34962, buffer);
  15083. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  15084. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  15085. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  15086. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  15087. } else if (materialDefaultAttributeValues !== undefined) {
  15088. var value = materialDefaultAttributeValues[name];
  15089. if (value !== undefined) {
  15090. switch (value.length) {
  15091. case 2:
  15092. _gl.vertexAttrib2fv(programAttribute, value);
  15093. break;
  15094. case 3:
  15095. _gl.vertexAttrib3fv(programAttribute, value);
  15096. break;
  15097. case 4:
  15098. _gl.vertexAttrib4fv(programAttribute, value);
  15099. break;
  15100. default:
  15101. _gl.vertexAttrib1fv(programAttribute, value);
  15102. }
  15103. }
  15104. }
  15105. }
  15106. }
  15107. state.disableUnusedAttributes();
  15108. } // Compile
  15109. this.compile = function (scene, camera) {
  15110. currentRenderState = renderStates.get(scene, camera);
  15111. currentRenderState.init();
  15112. scene.traverse(function (object) {
  15113. if (object.isLight) {
  15114. currentRenderState.pushLight(object);
  15115. if (object.castShadow) {
  15116. currentRenderState.pushShadow(object);
  15117. }
  15118. }
  15119. });
  15120. currentRenderState.setupLights(camera);
  15121. var compiled = {};
  15122. scene.traverse(function (object) {
  15123. if (object.material) {
  15124. if (Array.isArray(object.material)) {
  15125. for (var i = 0; i < object.material.length; i++) {
  15126. if (object.material[i].uuid in compiled === false) {
  15127. initMaterial(object.material[i], scene, object);
  15128. compiled[object.material[i].uuid] = true;
  15129. }
  15130. }
  15131. } else if (object.material.uuid in compiled === false) {
  15132. initMaterial(object.material, scene, object);
  15133. compiled[object.material.uuid] = true;
  15134. }
  15135. }
  15136. });
  15137. }; // Animation Loop
  15138. var onAnimationFrameCallback = null;
  15139. function onAnimationFrame(time) {
  15140. if (xr.isPresenting) return;
  15141. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15142. }
  15143. var animation = new WebGLAnimation();
  15144. animation.setAnimationLoop(onAnimationFrame);
  15145. if (typeof window !== 'undefined') animation.setContext(window);
  15146. this.setAnimationLoop = function (callback) {
  15147. onAnimationFrameCallback = callback;
  15148. xr.setAnimationLoop(callback);
  15149. animation.start();
  15150. }; // Rendering
  15151. this.render = function (scene, camera) {
  15152. var renderTarget, forceClear;
  15153. if (arguments[2] !== undefined) {
  15154. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15155. renderTarget = arguments[2];
  15156. }
  15157. if (arguments[3] !== undefined) {
  15158. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15159. forceClear = arguments[3];
  15160. }
  15161. if (!(camera && camera.isCamera)) {
  15162. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15163. return;
  15164. }
  15165. if (_isContextLost) return; // reset caching for this frame
  15166. _currentGeometryProgram.geometry = null;
  15167. _currentGeometryProgram.program = null;
  15168. _currentGeometryProgram.wireframe = false;
  15169. _currentMaterialId = -1;
  15170. _currentCamera = null; // update scene graph
  15171. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15172. if (camera.parent === null) camera.updateMatrixWorld();
  15173. if (xr.enabled && xr.isPresenting) {
  15174. camera = xr.getCamera(camera);
  15175. } //
  15176. currentRenderState = renderStates.get(scene, camera);
  15177. currentRenderState.init();
  15178. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15179. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15180. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15181. _localClippingEnabled = this.localClippingEnabled;
  15182. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15183. currentRenderList = renderLists.get(scene, camera);
  15184. currentRenderList.init();
  15185. projectObject(scene, camera, 0, _this.sortObjects);
  15186. currentRenderList.finish();
  15187. if (_this.sortObjects === true) {
  15188. currentRenderList.sort(_opaqueSort, _transparentSort);
  15189. } //
  15190. if (_clippingEnabled) _clipping.beginShadows();
  15191. var shadowsArray = currentRenderState.state.shadowsArray;
  15192. shadowMap.render(shadowsArray, scene, camera);
  15193. currentRenderState.setupLights(camera);
  15194. if (_clippingEnabled) _clipping.endShadows(); //
  15195. if (this.info.autoReset) this.info.reset();
  15196. if (renderTarget !== undefined) {
  15197. this.setRenderTarget(renderTarget);
  15198. } //
  15199. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15200. var opaqueObjects = currentRenderList.opaque;
  15201. var transparentObjects = currentRenderList.transparent;
  15202. if (scene.overrideMaterial) {
  15203. var overrideMaterial = scene.overrideMaterial;
  15204. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  15205. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  15206. } else {
  15207. // opaque pass (front-to-back order)
  15208. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  15209. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  15210. } //
  15211. scene.onAfterRender(_this, scene, camera); //
  15212. if (_currentRenderTarget !== null) {
  15213. // Generate mipmap if we're using any kind of mipmap filtering
  15214. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15215. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15216. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15217. state.buffers.depth.setTest(true);
  15218. state.buffers.depth.setMask(true);
  15219. state.buffers.color.setMask(true);
  15220. state.setPolygonOffset(false); // _gl.finish();
  15221. currentRenderList = null;
  15222. currentRenderState = null;
  15223. };
  15224. function projectObject(object, camera, groupOrder, sortObjects) {
  15225. if (object.visible === false) return;
  15226. var visible = object.layers.test(camera.layers);
  15227. if (visible) {
  15228. if (object.isGroup) {
  15229. groupOrder = object.renderOrder;
  15230. } else if (object.isLOD) {
  15231. if (object.autoUpdate === true) object.update(camera);
  15232. } else if (object.isLight) {
  15233. currentRenderState.pushLight(object);
  15234. if (object.castShadow) {
  15235. currentRenderState.pushShadow(object);
  15236. }
  15237. } else if (object.isSprite) {
  15238. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15239. if (sortObjects) {
  15240. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15241. }
  15242. var geometry = objects.update(object);
  15243. var material = object.material;
  15244. if (material.visible) {
  15245. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15246. }
  15247. }
  15248. } else if (object.isImmediateRenderObject) {
  15249. if (sortObjects) {
  15250. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15251. }
  15252. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15253. } else if (object.isMesh || object.isLine || object.isPoints) {
  15254. if (object.isSkinnedMesh) {
  15255. // update skeleton only once in a frame
  15256. if (object.skeleton.frame !== info.render.frame) {
  15257. object.skeleton.update();
  15258. object.skeleton.frame = info.render.frame;
  15259. }
  15260. }
  15261. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15262. if (sortObjects) {
  15263. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15264. }
  15265. var geometry = objects.update(object);
  15266. var material = object.material;
  15267. if (Array.isArray(material)) {
  15268. var groups = geometry.groups;
  15269. for (var i = 0, l = groups.length; i < l; i++) {
  15270. var group = groups[i];
  15271. var groupMaterial = material[group.materialIndex];
  15272. if (groupMaterial && groupMaterial.visible) {
  15273. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15274. }
  15275. }
  15276. } else if (material.visible) {
  15277. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15278. }
  15279. }
  15280. }
  15281. }
  15282. var children = object.children;
  15283. for (var i = 0, l = children.length; i < l; i++) {
  15284. projectObject(children[i], camera, groupOrder, sortObjects);
  15285. }
  15286. }
  15287. function renderObjects(renderList, scene, camera, overrideMaterial) {
  15288. for (var i = 0, l = renderList.length; i < l; i++) {
  15289. var renderItem = renderList[i];
  15290. var object = renderItem.object;
  15291. var geometry = renderItem.geometry;
  15292. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15293. var group = renderItem.group;
  15294. if (camera.isArrayCamera) {
  15295. _currentArrayCamera = camera;
  15296. var cameras = camera.cameras;
  15297. for (var j = 0, jl = cameras.length; j < jl; j++) {
  15298. var camera2 = cameras[j];
  15299. if (object.layers.test(camera2.layers)) {
  15300. state.viewport(_currentViewport.copy(camera2.viewport));
  15301. currentRenderState.setupLights(camera2);
  15302. renderObject(object, scene, camera2, geometry, material, group);
  15303. }
  15304. }
  15305. } else {
  15306. _currentArrayCamera = null;
  15307. renderObject(object, scene, camera, geometry, material, group);
  15308. }
  15309. }
  15310. }
  15311. function renderObject(object, scene, camera, geometry, material, group) {
  15312. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15313. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15314. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15315. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15316. if (object.isImmediateRenderObject) {
  15317. var program = setProgram(camera, scene, material, object);
  15318. state.setMaterial(material);
  15319. _currentGeometryProgram.geometry = null;
  15320. _currentGeometryProgram.program = null;
  15321. _currentGeometryProgram.wireframe = false;
  15322. renderObjectImmediate(object, program);
  15323. } else {
  15324. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15325. }
  15326. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15327. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15328. }
  15329. function initMaterial(material, scene, object) {
  15330. var materialProperties = properties.get(material);
  15331. var lights = currentRenderState.state.lights;
  15332. var shadowsArray = currentRenderState.state.shadowsArray;
  15333. var lightsStateVersion = lights.state.version;
  15334. var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object);
  15335. var programCacheKey = programCache.getProgramCacheKey(parameters);
  15336. var program = materialProperties.program;
  15337. var programChange = true;
  15338. if (program === undefined) {
  15339. // new material
  15340. material.addEventListener('dispose', onMaterialDispose);
  15341. } else if (program.cacheKey !== programCacheKey) {
  15342. // changed glsl or parameters
  15343. releaseMaterialProgramReference(material);
  15344. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15345. materialProperties.lightsStateVersion = lightsStateVersion;
  15346. programChange = false;
  15347. } else if (parameters.shaderID !== undefined) {
  15348. // same glsl and uniform list
  15349. return;
  15350. } else {
  15351. // only rebuild uniform list
  15352. programChange = false;
  15353. }
  15354. if (programChange) {
  15355. program = programCache.acquireProgram(parameters, programCacheKey);
  15356. materialProperties.program = program;
  15357. materialProperties.uniforms = parameters.uniforms;
  15358. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15359. materialProperties.outputEncoding = _this.outputEncoding;
  15360. material.program = program;
  15361. }
  15362. var programAttributes = program.getAttributes();
  15363. if (material.morphTargets) {
  15364. material.numSupportedMorphTargets = 0;
  15365. for (var i = 0; i < _this.maxMorphTargets; i++) {
  15366. if (programAttributes['morphTarget' + i] >= 0) {
  15367. material.numSupportedMorphTargets++;
  15368. }
  15369. }
  15370. }
  15371. if (material.morphNormals) {
  15372. material.numSupportedMorphNormals = 0;
  15373. for (var i = 0; i < _this.maxMorphNormals; i++) {
  15374. if (programAttributes['morphNormal' + i] >= 0) {
  15375. material.numSupportedMorphNormals++;
  15376. }
  15377. }
  15378. }
  15379. var uniforms = materialProperties.uniforms;
  15380. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15381. materialProperties.numClippingPlanes = _clipping.numPlanes;
  15382. materialProperties.numIntersection = _clipping.numIntersection;
  15383. uniforms.clippingPlanes = _clipping.uniform;
  15384. }
  15385. materialProperties.fog = scene.fog; // store the light setup it was created for
  15386. materialProperties.needsLights = materialNeedsLights(material);
  15387. materialProperties.lightsStateVersion = lightsStateVersion;
  15388. if (materialProperties.needsLights) {
  15389. // wire up the material to this renderer's lighting state
  15390. uniforms.ambientLightColor.value = lights.state.ambient;
  15391. uniforms.lightProbe.value = lights.state.probe;
  15392. uniforms.directionalLights.value = lights.state.directional;
  15393. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15394. uniforms.spotLights.value = lights.state.spot;
  15395. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15396. uniforms.rectAreaLights.value = lights.state.rectArea;
  15397. uniforms.pointLights.value = lights.state.point;
  15398. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15399. uniforms.hemisphereLights.value = lights.state.hemi;
  15400. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15401. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15402. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15403. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15404. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15405. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15406. }
  15407. var progUniforms = materialProperties.program.getUniforms(),
  15408. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15409. materialProperties.uniformsList = uniformsList;
  15410. }
  15411. function setProgram(camera, scene, material, object) {
  15412. textures.resetTextureUnits();
  15413. var fog = scene.fog;
  15414. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  15415. var materialProperties = properties.get(material);
  15416. var lights = currentRenderState.state.lights;
  15417. if (_clippingEnabled) {
  15418. if (_localClippingEnabled || camera !== _currentCamera) {
  15419. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15420. // object instead of the material, once it becomes feasible
  15421. // (#8465, #8379)
  15422. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  15423. }
  15424. }
  15425. if (material.version === materialProperties.__version) {
  15426. if (materialProperties.program === undefined) {
  15427. initMaterial(material, scene, object);
  15428. } else if (material.fog && materialProperties.fog !== fog) {
  15429. initMaterial(material, scene, object);
  15430. } else if (materialProperties.environment !== environment) {
  15431. initMaterial(material, scene, object);
  15432. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15433. initMaterial(material, scene, object);
  15434. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  15435. initMaterial(material, scene, object);
  15436. } else if (materialProperties.outputEncoding !== _this.outputEncoding) {
  15437. initMaterial(material, scene, object);
  15438. }
  15439. } else {
  15440. initMaterial(material, scene, object);
  15441. materialProperties.__version = material.version;
  15442. }
  15443. var refreshProgram = false;
  15444. var refreshMaterial = false;
  15445. var refreshLights = false;
  15446. var program = materialProperties.program,
  15447. p_uniforms = program.getUniforms(),
  15448. m_uniforms = materialProperties.uniforms;
  15449. if (state.useProgram(program.program)) {
  15450. refreshProgram = true;
  15451. refreshMaterial = true;
  15452. refreshLights = true;
  15453. }
  15454. if (material.id !== _currentMaterialId) {
  15455. _currentMaterialId = material.id;
  15456. refreshMaterial = true;
  15457. }
  15458. if (refreshProgram || _currentCamera !== camera) {
  15459. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15460. if (capabilities.logarithmicDepthBuffer) {
  15461. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15462. }
  15463. if (_currentCamera !== camera) {
  15464. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15465. // now, in case this material supports lights - or later, when
  15466. // the next material that does gets activated:
  15467. refreshMaterial = true; // set to true on material change
  15468. refreshLights = true; // remains set until update done
  15469. } // load material specific uniforms
  15470. // (shader material also gets them for the sake of genericity)
  15471. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15472. var uCamPos = p_uniforms.map.cameraPosition;
  15473. if (uCamPos !== undefined) {
  15474. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15475. }
  15476. }
  15477. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15478. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15479. }
  15480. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  15481. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15482. }
  15483. } // skinning uniforms must be set even if material didn't change
  15484. // auto-setting of texture unit for bone texture must go before other textures
  15485. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15486. if (material.skinning) {
  15487. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15488. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15489. var skeleton = object.skeleton;
  15490. if (skeleton) {
  15491. var bones = skeleton.bones;
  15492. if (capabilities.floatVertexTextures) {
  15493. if (skeleton.boneTexture === undefined) {
  15494. // layout (1 matrix = 4 pixels)
  15495. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15496. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15497. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15498. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15499. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15500. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15501. size = MathUtils.ceilPowerOfTwo(size);
  15502. size = Math.max(size, 4);
  15503. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15504. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15505. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15506. skeleton.boneMatrices = boneMatrices;
  15507. skeleton.boneTexture = boneTexture;
  15508. skeleton.boneTextureSize = size;
  15509. }
  15510. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15511. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15512. } else {
  15513. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15514. }
  15515. }
  15516. }
  15517. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15518. materialProperties.receiveShadow = object.receiveShadow;
  15519. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15520. }
  15521. if (refreshMaterial) {
  15522. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15523. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  15524. if (materialProperties.needsLights) {
  15525. // the current material requires lighting info
  15526. // note: all lighting uniforms are always set correctly
  15527. // they simply reference the renderer's state for their
  15528. // values
  15529. //
  15530. // use the current material's .needsUpdate flags to set
  15531. // the GL state when required
  15532. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15533. } // refresh uniforms common to several materials
  15534. if (fog && material.fog) {
  15535. refreshUniformsFog(m_uniforms, fog);
  15536. }
  15537. if (material.isMeshBasicMaterial) {
  15538. refreshUniformsCommon(m_uniforms, material);
  15539. } else if (material.isMeshLambertMaterial) {
  15540. refreshUniformsCommon(m_uniforms, material);
  15541. refreshUniformsLambert(m_uniforms, material);
  15542. } else if (material.isMeshToonMaterial) {
  15543. refreshUniformsCommon(m_uniforms, material);
  15544. refreshUniformsToon(m_uniforms, material);
  15545. } else if (material.isMeshPhongMaterial) {
  15546. refreshUniformsCommon(m_uniforms, material);
  15547. refreshUniformsPhong(m_uniforms, material);
  15548. } else if (material.isMeshStandardMaterial) {
  15549. refreshUniformsCommon(m_uniforms, material, environment);
  15550. if (material.isMeshPhysicalMaterial) {
  15551. refreshUniformsPhysical(m_uniforms, material, environment);
  15552. } else {
  15553. refreshUniformsStandard(m_uniforms, material, environment);
  15554. }
  15555. } else if (material.isMeshMatcapMaterial) {
  15556. refreshUniformsCommon(m_uniforms, material);
  15557. refreshUniformsMatcap(m_uniforms, material);
  15558. } else if (material.isMeshDepthMaterial) {
  15559. refreshUniformsCommon(m_uniforms, material);
  15560. refreshUniformsDepth(m_uniforms, material);
  15561. } else if (material.isMeshDistanceMaterial) {
  15562. refreshUniformsCommon(m_uniforms, material);
  15563. refreshUniformsDistance(m_uniforms, material);
  15564. } else if (material.isMeshNormalMaterial) {
  15565. refreshUniformsCommon(m_uniforms, material);
  15566. refreshUniformsNormal(m_uniforms, material);
  15567. } else if (material.isLineBasicMaterial) {
  15568. refreshUniformsLine(m_uniforms, material);
  15569. if (material.isLineDashedMaterial) {
  15570. refreshUniformsDash(m_uniforms, material);
  15571. }
  15572. } else if (material.isPointsMaterial) {
  15573. refreshUniformsPoints(m_uniforms, material);
  15574. } else if (material.isSpriteMaterial) {
  15575. refreshUniformsSprites(m_uniforms, material);
  15576. } else if (material.isShadowMaterial) {
  15577. m_uniforms.color.value.copy(material.color);
  15578. m_uniforms.opacity.value = material.opacity;
  15579. } // RectAreaLight Texture
  15580. // TODO (mrdoob): Find a nicer implementation
  15581. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  15582. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  15583. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15584. if (material.isShaderMaterial) {
  15585. material.uniformsNeedUpdate = false; // #15581
  15586. }
  15587. }
  15588. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15589. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15590. material.uniformsNeedUpdate = false;
  15591. }
  15592. if (material.isSpriteMaterial) {
  15593. p_uniforms.setValue(_gl, 'center', object.center);
  15594. } // common matrices
  15595. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15596. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15597. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15598. return program;
  15599. } // Uniforms (refresh uniforms objects)
  15600. function refreshUniformsCommon(uniforms, material, environment) {
  15601. uniforms.opacity.value = material.opacity;
  15602. if (material.color) {
  15603. uniforms.diffuse.value.copy(material.color);
  15604. }
  15605. if (material.emissive) {
  15606. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15607. }
  15608. if (material.map) {
  15609. uniforms.map.value = material.map;
  15610. }
  15611. if (material.alphaMap) {
  15612. uniforms.alphaMap.value = material.alphaMap;
  15613. }
  15614. if (material.specularMap) {
  15615. uniforms.specularMap.value = material.specularMap;
  15616. }
  15617. var envMap = material.envMap || environment;
  15618. if (envMap) {
  15619. uniforms.envMap.value = envMap;
  15620. uniforms.flipEnvMap.value = envMap.isCubeTexture ? -1 : 1;
  15621. uniforms.reflectivity.value = material.reflectivity;
  15622. uniforms.refractionRatio.value = material.refractionRatio;
  15623. uniforms.maxMipLevel.value = properties.get(envMap).__maxMipLevel;
  15624. }
  15625. if (material.lightMap) {
  15626. uniforms.lightMap.value = material.lightMap;
  15627. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15628. }
  15629. if (material.aoMap) {
  15630. uniforms.aoMap.value = material.aoMap;
  15631. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15632. } // uv repeat and offset setting priorities
  15633. // 1. color map
  15634. // 2. specular map
  15635. // 3. normal map
  15636. // 4. bump map
  15637. // 5. alpha map
  15638. // 6. emissive map
  15639. var uvScaleMap;
  15640. if (material.map) {
  15641. uvScaleMap = material.map;
  15642. } else if (material.specularMap) {
  15643. uvScaleMap = material.specularMap;
  15644. } else if (material.displacementMap) {
  15645. uvScaleMap = material.displacementMap;
  15646. } else if (material.normalMap) {
  15647. uvScaleMap = material.normalMap;
  15648. } else if (material.bumpMap) {
  15649. uvScaleMap = material.bumpMap;
  15650. } else if (material.roughnessMap) {
  15651. uvScaleMap = material.roughnessMap;
  15652. } else if (material.metalnessMap) {
  15653. uvScaleMap = material.metalnessMap;
  15654. } else if (material.alphaMap) {
  15655. uvScaleMap = material.alphaMap;
  15656. } else if (material.emissiveMap) {
  15657. uvScaleMap = material.emissiveMap;
  15658. }
  15659. if (uvScaleMap !== undefined) {
  15660. // backwards compatibility
  15661. if (uvScaleMap.isWebGLRenderTarget) {
  15662. uvScaleMap = uvScaleMap.texture;
  15663. }
  15664. if (uvScaleMap.matrixAutoUpdate === true) {
  15665. uvScaleMap.updateMatrix();
  15666. }
  15667. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15668. } // uv repeat and offset setting priorities for uv2
  15669. // 1. ao map
  15670. // 2. light map
  15671. var uv2ScaleMap;
  15672. if (material.aoMap) {
  15673. uv2ScaleMap = material.aoMap;
  15674. } else if (material.lightMap) {
  15675. uv2ScaleMap = material.lightMap;
  15676. }
  15677. if (uv2ScaleMap !== undefined) {
  15678. // backwards compatibility
  15679. if (uv2ScaleMap.isWebGLRenderTarget) {
  15680. uv2ScaleMap = uv2ScaleMap.texture;
  15681. }
  15682. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15683. uv2ScaleMap.updateMatrix();
  15684. }
  15685. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15686. }
  15687. }
  15688. function refreshUniformsLine(uniforms, material) {
  15689. uniforms.diffuse.value.copy(material.color);
  15690. uniforms.opacity.value = material.opacity;
  15691. }
  15692. function refreshUniformsDash(uniforms, material) {
  15693. uniforms.dashSize.value = material.dashSize;
  15694. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15695. uniforms.scale.value = material.scale;
  15696. }
  15697. function refreshUniformsPoints(uniforms, material) {
  15698. uniforms.diffuse.value.copy(material.color);
  15699. uniforms.opacity.value = material.opacity;
  15700. uniforms.size.value = material.size * _pixelRatio;
  15701. uniforms.scale.value = _height * 0.5;
  15702. if (material.map) {
  15703. uniforms.map.value = material.map;
  15704. }
  15705. if (material.alphaMap) {
  15706. uniforms.alphaMap.value = material.alphaMap;
  15707. } // uv repeat and offset setting priorities
  15708. // 1. color map
  15709. // 2. alpha map
  15710. var uvScaleMap;
  15711. if (material.map) {
  15712. uvScaleMap = material.map;
  15713. } else if (material.alphaMap) {
  15714. uvScaleMap = material.alphaMap;
  15715. }
  15716. if (uvScaleMap !== undefined) {
  15717. if (uvScaleMap.matrixAutoUpdate === true) {
  15718. uvScaleMap.updateMatrix();
  15719. }
  15720. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15721. }
  15722. }
  15723. function refreshUniformsSprites(uniforms, material) {
  15724. uniforms.diffuse.value.copy(material.color);
  15725. uniforms.opacity.value = material.opacity;
  15726. uniforms.rotation.value = material.rotation;
  15727. if (material.map) {
  15728. uniforms.map.value = material.map;
  15729. }
  15730. if (material.alphaMap) {
  15731. uniforms.alphaMap.value = material.alphaMap;
  15732. } // uv repeat and offset setting priorities
  15733. // 1. color map
  15734. // 2. alpha map
  15735. var uvScaleMap;
  15736. if (material.map) {
  15737. uvScaleMap = material.map;
  15738. } else if (material.alphaMap) {
  15739. uvScaleMap = material.alphaMap;
  15740. }
  15741. if (uvScaleMap !== undefined) {
  15742. if (uvScaleMap.matrixAutoUpdate === true) {
  15743. uvScaleMap.updateMatrix();
  15744. }
  15745. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15746. }
  15747. }
  15748. function refreshUniformsFog(uniforms, fog) {
  15749. uniforms.fogColor.value.copy(fog.color);
  15750. if (fog.isFog) {
  15751. uniforms.fogNear.value = fog.near;
  15752. uniforms.fogFar.value = fog.far;
  15753. } else if (fog.isFogExp2) {
  15754. uniforms.fogDensity.value = fog.density;
  15755. }
  15756. }
  15757. function refreshUniformsLambert(uniforms, material) {
  15758. if (material.emissiveMap) {
  15759. uniforms.emissiveMap.value = material.emissiveMap;
  15760. }
  15761. }
  15762. function refreshUniformsPhong(uniforms, material) {
  15763. uniforms.specular.value.copy(material.specular);
  15764. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15765. if (material.emissiveMap) {
  15766. uniforms.emissiveMap.value = material.emissiveMap;
  15767. }
  15768. if (material.bumpMap) {
  15769. uniforms.bumpMap.value = material.bumpMap;
  15770. uniforms.bumpScale.value = material.bumpScale;
  15771. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15772. }
  15773. if (material.normalMap) {
  15774. uniforms.normalMap.value = material.normalMap;
  15775. uniforms.normalScale.value.copy(material.normalScale);
  15776. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15777. }
  15778. if (material.displacementMap) {
  15779. uniforms.displacementMap.value = material.displacementMap;
  15780. uniforms.displacementScale.value = material.displacementScale;
  15781. uniforms.displacementBias.value = material.displacementBias;
  15782. }
  15783. }
  15784. function refreshUniformsToon(uniforms, material) {
  15785. uniforms.specular.value.copy(material.specular);
  15786. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15787. if (material.gradientMap) {
  15788. uniforms.gradientMap.value = material.gradientMap;
  15789. }
  15790. if (material.emissiveMap) {
  15791. uniforms.emissiveMap.value = material.emissiveMap;
  15792. }
  15793. if (material.bumpMap) {
  15794. uniforms.bumpMap.value = material.bumpMap;
  15795. uniforms.bumpScale.value = material.bumpScale;
  15796. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15797. }
  15798. if (material.normalMap) {
  15799. uniforms.normalMap.value = material.normalMap;
  15800. uniforms.normalScale.value.copy(material.normalScale);
  15801. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15802. }
  15803. if (material.displacementMap) {
  15804. uniforms.displacementMap.value = material.displacementMap;
  15805. uniforms.displacementScale.value = material.displacementScale;
  15806. uniforms.displacementBias.value = material.displacementBias;
  15807. }
  15808. }
  15809. function refreshUniformsStandard(uniforms, material, environment) {
  15810. uniforms.roughness.value = material.roughness;
  15811. uniforms.metalness.value = material.metalness;
  15812. if (material.roughnessMap) {
  15813. uniforms.roughnessMap.value = material.roughnessMap;
  15814. }
  15815. if (material.metalnessMap) {
  15816. uniforms.metalnessMap.value = material.metalnessMap;
  15817. }
  15818. if (material.emissiveMap) {
  15819. uniforms.emissiveMap.value = material.emissiveMap;
  15820. }
  15821. if (material.bumpMap) {
  15822. uniforms.bumpMap.value = material.bumpMap;
  15823. uniforms.bumpScale.value = material.bumpScale;
  15824. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15825. }
  15826. if (material.normalMap) {
  15827. uniforms.normalMap.value = material.normalMap;
  15828. uniforms.normalScale.value.copy(material.normalScale);
  15829. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15830. }
  15831. if (material.displacementMap) {
  15832. uniforms.displacementMap.value = material.displacementMap;
  15833. uniforms.displacementScale.value = material.displacementScale;
  15834. uniforms.displacementBias.value = material.displacementBias;
  15835. }
  15836. if (material.envMap || environment) {
  15837. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15838. uniforms.envMapIntensity.value = material.envMapIntensity;
  15839. }
  15840. }
  15841. function refreshUniformsPhysical(uniforms, material, environment) {
  15842. refreshUniformsStandard(uniforms, material, environment);
  15843. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  15844. uniforms.clearcoat.value = material.clearcoat;
  15845. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15846. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  15847. if (material.clearcoatMap) {
  15848. uniforms.clearcoatMap.value = material.clearcoatMap;
  15849. }
  15850. if (material.clearcoatRoughnessMap) {
  15851. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15852. }
  15853. if (material.clearcoatNormalMap) {
  15854. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15855. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15856. if (material.side === BackSide) {
  15857. uniforms.clearcoatNormalScale.value.negate();
  15858. }
  15859. }
  15860. uniforms.transparency.value = material.transparency;
  15861. }
  15862. function refreshUniformsMatcap(uniforms, material) {
  15863. if (material.matcap) {
  15864. uniforms.matcap.value = material.matcap;
  15865. }
  15866. if (material.bumpMap) {
  15867. uniforms.bumpMap.value = material.bumpMap;
  15868. uniforms.bumpScale.value = material.bumpScale;
  15869. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15870. }
  15871. if (material.normalMap) {
  15872. uniforms.normalMap.value = material.normalMap;
  15873. uniforms.normalScale.value.copy(material.normalScale);
  15874. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15875. }
  15876. if (material.displacementMap) {
  15877. uniforms.displacementMap.value = material.displacementMap;
  15878. uniforms.displacementScale.value = material.displacementScale;
  15879. uniforms.displacementBias.value = material.displacementBias;
  15880. }
  15881. }
  15882. function refreshUniformsDepth(uniforms, material) {
  15883. if (material.displacementMap) {
  15884. uniforms.displacementMap.value = material.displacementMap;
  15885. uniforms.displacementScale.value = material.displacementScale;
  15886. uniforms.displacementBias.value = material.displacementBias;
  15887. }
  15888. }
  15889. function refreshUniformsDistance(uniforms, material) {
  15890. if (material.displacementMap) {
  15891. uniforms.displacementMap.value = material.displacementMap;
  15892. uniforms.displacementScale.value = material.displacementScale;
  15893. uniforms.displacementBias.value = material.displacementBias;
  15894. }
  15895. uniforms.referencePosition.value.copy(material.referencePosition);
  15896. uniforms.nearDistance.value = material.nearDistance;
  15897. uniforms.farDistance.value = material.farDistance;
  15898. }
  15899. function refreshUniformsNormal(uniforms, material) {
  15900. if (material.bumpMap) {
  15901. uniforms.bumpMap.value = material.bumpMap;
  15902. uniforms.bumpScale.value = material.bumpScale;
  15903. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15904. }
  15905. if (material.normalMap) {
  15906. uniforms.normalMap.value = material.normalMap;
  15907. uniforms.normalScale.value.copy(material.normalScale);
  15908. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15909. }
  15910. if (material.displacementMap) {
  15911. uniforms.displacementMap.value = material.displacementMap;
  15912. uniforms.displacementScale.value = material.displacementScale;
  15913. uniforms.displacementBias.value = material.displacementBias;
  15914. }
  15915. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15916. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15917. uniforms.ambientLightColor.needsUpdate = value;
  15918. uniforms.lightProbe.needsUpdate = value;
  15919. uniforms.directionalLights.needsUpdate = value;
  15920. uniforms.directionalLightShadows.needsUpdate = value;
  15921. uniforms.pointLights.needsUpdate = value;
  15922. uniforms.pointLightShadows.needsUpdate = value;
  15923. uniforms.spotLights.needsUpdate = value;
  15924. uniforms.spotLightShadows.needsUpdate = value;
  15925. uniforms.rectAreaLights.needsUpdate = value;
  15926. uniforms.hemisphereLights.needsUpdate = value;
  15927. }
  15928. function materialNeedsLights(material) {
  15929. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15930. } //
  15931. this.setFramebuffer = function (value) {
  15932. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  15933. _framebuffer = value;
  15934. };
  15935. this.getActiveCubeFace = function () {
  15936. return _currentActiveCubeFace;
  15937. };
  15938. this.getActiveMipmapLevel = function () {
  15939. return _currentActiveMipmapLevel;
  15940. };
  15941. this.getRenderTarget = function () {
  15942. return _currentRenderTarget;
  15943. };
  15944. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  15945. _currentRenderTarget = renderTarget;
  15946. _currentActiveCubeFace = activeCubeFace;
  15947. _currentActiveMipmapLevel = activeMipmapLevel;
  15948. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15949. textures.setupRenderTarget(renderTarget);
  15950. }
  15951. var framebuffer = _framebuffer;
  15952. var isCube = false;
  15953. if (renderTarget) {
  15954. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15955. if (renderTarget.isWebGLCubeRenderTarget) {
  15956. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  15957. isCube = true;
  15958. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15959. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15960. } else {
  15961. framebuffer = __webglFramebuffer;
  15962. }
  15963. _currentViewport.copy(renderTarget.viewport);
  15964. _currentScissor.copy(renderTarget.scissor);
  15965. _currentScissorTest = renderTarget.scissorTest;
  15966. } else {
  15967. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15968. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15969. _currentScissorTest = _scissorTest;
  15970. }
  15971. if (_currentFramebuffer !== framebuffer) {
  15972. _gl.bindFramebuffer(36160, framebuffer);
  15973. _currentFramebuffer = framebuffer;
  15974. }
  15975. state.viewport(_currentViewport);
  15976. state.scissor(_currentScissor);
  15977. state.setScissorTest(_currentScissorTest);
  15978. if (isCube) {
  15979. var textureProperties = properties.get(renderTarget.texture);
  15980. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  15981. }
  15982. };
  15983. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15984. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15985. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15986. return;
  15987. }
  15988. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15989. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15990. framebuffer = framebuffer[activeCubeFaceIndex];
  15991. }
  15992. if (framebuffer) {
  15993. var restore = false;
  15994. if (framebuffer !== _currentFramebuffer) {
  15995. _gl.bindFramebuffer(36160, framebuffer);
  15996. restore = true;
  15997. }
  15998. try {
  15999. var texture = renderTarget.texture;
  16000. var textureFormat = texture.format;
  16001. var textureType = texture.type;
  16002. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16003. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16004. return;
  16005. }
  16006. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16007. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16008. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16009. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16010. return;
  16011. }
  16012. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16013. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16014. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16015. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16016. }
  16017. } else {
  16018. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16019. }
  16020. } finally {
  16021. if (restore) {
  16022. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16023. }
  16024. }
  16025. }
  16026. };
  16027. this.copyFramebufferToTexture = function (position, texture, level) {
  16028. if (level === undefined) level = 0;
  16029. var levelScale = Math.pow(2, -level);
  16030. var width = Math.floor(texture.image.width * levelScale);
  16031. var height = Math.floor(texture.image.height * levelScale);
  16032. var glFormat = utils.convert(texture.format);
  16033. textures.setTexture2D(texture, 0);
  16034. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  16035. state.unbindTexture();
  16036. };
  16037. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16038. var width = srcTexture.image.width;
  16039. var height = srcTexture.image.height;
  16040. var glFormat = utils.convert(dstTexture.format);
  16041. var glType = utils.convert(dstTexture.type);
  16042. textures.setTexture2D(dstTexture, 0);
  16043. if (srcTexture.isDataTexture) {
  16044. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16045. } else {
  16046. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  16047. }
  16048. state.unbindTexture();
  16049. };
  16050. this.initTexture = function (texture) {
  16051. textures.setTexture2D(texture, 0);
  16052. state.unbindTexture();
  16053. };
  16054. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16055. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16056. detail: this
  16057. })); // eslint-disable-line no-undef
  16058. }
  16059. }
  16060. /**
  16061. * @author mrdoob / http://mrdoob.com/
  16062. * @author alteredq / http://alteredqualia.com/
  16063. */
  16064. function FogExp2(color, density) {
  16065. this.name = '';
  16066. this.color = new Color(color);
  16067. this.density = density !== undefined ? density : 0.00025;
  16068. }
  16069. Object.assign(FogExp2.prototype, {
  16070. isFogExp2: true,
  16071. clone: function () {
  16072. return new FogExp2(this.color, this.density);
  16073. },
  16074. toJSON: function ()
  16075. /* meta */
  16076. {
  16077. return {
  16078. type: 'FogExp2',
  16079. color: this.color.getHex(),
  16080. density: this.density
  16081. };
  16082. }
  16083. });
  16084. /**
  16085. * @author mrdoob / http://mrdoob.com/
  16086. * @author alteredq / http://alteredqualia.com/
  16087. */
  16088. function Fog(color, near, far) {
  16089. this.name = '';
  16090. this.color = new Color(color);
  16091. this.near = near !== undefined ? near : 1;
  16092. this.far = far !== undefined ? far : 1000;
  16093. }
  16094. Object.assign(Fog.prototype, {
  16095. isFog: true,
  16096. clone: function () {
  16097. return new Fog(this.color, this.near, this.far);
  16098. },
  16099. toJSON: function ()
  16100. /* meta */
  16101. {
  16102. return {
  16103. type: 'Fog',
  16104. color: this.color.getHex(),
  16105. near: this.near,
  16106. far: this.far
  16107. };
  16108. }
  16109. });
  16110. /**
  16111. * @author benaadams / https://twitter.com/ben_a_adams
  16112. */
  16113. function InterleavedBuffer(array, stride) {
  16114. this.array = array;
  16115. this.stride = stride;
  16116. this.count = array !== undefined ? array.length / stride : 0;
  16117. this.usage = StaticDrawUsage;
  16118. this.updateRange = {
  16119. offset: 0,
  16120. count: -1
  16121. };
  16122. this.version = 0;
  16123. }
  16124. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  16125. set: function (value) {
  16126. if (value === true) this.version++;
  16127. }
  16128. });
  16129. Object.assign(InterleavedBuffer.prototype, {
  16130. isInterleavedBuffer: true,
  16131. onUploadCallback: function () {},
  16132. setUsage: function (value) {
  16133. this.usage = value;
  16134. return this;
  16135. },
  16136. copy: function (source) {
  16137. this.array = new source.array.constructor(source.array);
  16138. this.count = source.count;
  16139. this.stride = source.stride;
  16140. this.usage = source.usage;
  16141. return this;
  16142. },
  16143. copyAt: function (index1, attribute, index2) {
  16144. index1 *= this.stride;
  16145. index2 *= attribute.stride;
  16146. for (var i = 0, l = this.stride; i < l; i++) {
  16147. this.array[index1 + i] = attribute.array[index2 + i];
  16148. }
  16149. return this;
  16150. },
  16151. set: function (value, offset) {
  16152. if (offset === undefined) offset = 0;
  16153. this.array.set(value, offset);
  16154. return this;
  16155. },
  16156. clone: function () {
  16157. return new this.constructor().copy(this);
  16158. },
  16159. onUpload: function (callback) {
  16160. this.onUploadCallback = callback;
  16161. return this;
  16162. }
  16163. });
  16164. /**
  16165. * @author benaadams / https://twitter.com/ben_a_adams
  16166. */
  16167. var _vector$6 = new Vector3();
  16168. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  16169. this.data = interleavedBuffer;
  16170. this.itemSize = itemSize;
  16171. this.offset = offset;
  16172. this.normalized = normalized === true;
  16173. }
  16174. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  16175. count: {
  16176. get: function () {
  16177. return this.data.count;
  16178. }
  16179. },
  16180. array: {
  16181. get: function () {
  16182. return this.data.array;
  16183. }
  16184. }
  16185. });
  16186. Object.assign(InterleavedBufferAttribute.prototype, {
  16187. isInterleavedBufferAttribute: true,
  16188. applyMatrix4: function (m) {
  16189. for (var i = 0, l = this.data.count; i < l; i++) {
  16190. _vector$6.x = this.getX(i);
  16191. _vector$6.y = this.getY(i);
  16192. _vector$6.z = this.getZ(i);
  16193. _vector$6.applyMatrix4(m);
  16194. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16195. }
  16196. return this;
  16197. },
  16198. setX: function (index, x) {
  16199. this.data.array[index * this.data.stride + this.offset] = x;
  16200. return this;
  16201. },
  16202. setY: function (index, y) {
  16203. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16204. return this;
  16205. },
  16206. setZ: function (index, z) {
  16207. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16208. return this;
  16209. },
  16210. setW: function (index, w) {
  16211. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16212. return this;
  16213. },
  16214. getX: function (index) {
  16215. return this.data.array[index * this.data.stride + this.offset];
  16216. },
  16217. getY: function (index) {
  16218. return this.data.array[index * this.data.stride + this.offset + 1];
  16219. },
  16220. getZ: function (index) {
  16221. return this.data.array[index * this.data.stride + this.offset + 2];
  16222. },
  16223. getW: function (index) {
  16224. return this.data.array[index * this.data.stride + this.offset + 3];
  16225. },
  16226. setXY: function (index, x, y) {
  16227. index = index * this.data.stride + this.offset;
  16228. this.data.array[index + 0] = x;
  16229. this.data.array[index + 1] = y;
  16230. return this;
  16231. },
  16232. setXYZ: function (index, x, y, z) {
  16233. index = index * this.data.stride + this.offset;
  16234. this.data.array[index + 0] = x;
  16235. this.data.array[index + 1] = y;
  16236. this.data.array[index + 2] = z;
  16237. return this;
  16238. },
  16239. setXYZW: function (index, x, y, z, w) {
  16240. index = index * this.data.stride + this.offset;
  16241. this.data.array[index + 0] = x;
  16242. this.data.array[index + 1] = y;
  16243. this.data.array[index + 2] = z;
  16244. this.data.array[index + 3] = w;
  16245. return this;
  16246. }
  16247. });
  16248. /**
  16249. * @author alteredq / http://alteredqualia.com/
  16250. *
  16251. * parameters = {
  16252. * color: <hex>,
  16253. * map: new THREE.Texture( <Image> ),
  16254. * alphaMap: new THREE.Texture( <Image> ),
  16255. * rotation: <float>,
  16256. * sizeAttenuation: <bool>
  16257. * }
  16258. */
  16259. function SpriteMaterial(parameters) {
  16260. Material.call(this);
  16261. this.type = 'SpriteMaterial';
  16262. this.color = new Color(0xffffff);
  16263. this.map = null;
  16264. this.alphaMap = null;
  16265. this.rotation = 0;
  16266. this.sizeAttenuation = true;
  16267. this.transparent = true;
  16268. this.setValues(parameters);
  16269. }
  16270. SpriteMaterial.prototype = Object.create(Material.prototype);
  16271. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16272. SpriteMaterial.prototype.isSpriteMaterial = true;
  16273. SpriteMaterial.prototype.copy = function (source) {
  16274. Material.prototype.copy.call(this, source);
  16275. this.color.copy(source.color);
  16276. this.map = source.map;
  16277. this.alphaMap = source.alphaMap;
  16278. this.rotation = source.rotation;
  16279. this.sizeAttenuation = source.sizeAttenuation;
  16280. return this;
  16281. };
  16282. /**
  16283. * @author mikael emtinger / http://gomo.se/
  16284. * @author alteredq / http://alteredqualia.com/
  16285. */
  16286. var _geometry;
  16287. var _intersectPoint = new Vector3();
  16288. var _worldScale = new Vector3();
  16289. var _mvPosition = new Vector3();
  16290. var _alignedPosition = new Vector2();
  16291. var _rotatedPosition = new Vector2();
  16292. var _viewWorldMatrix = new Matrix4();
  16293. var _vA$1 = new Vector3();
  16294. var _vB$1 = new Vector3();
  16295. var _vC$1 = new Vector3();
  16296. var _uvA$1 = new Vector2();
  16297. var _uvB$1 = new Vector2();
  16298. var _uvC$1 = new Vector2();
  16299. function Sprite(material) {
  16300. Object3D.call(this);
  16301. this.type = 'Sprite';
  16302. if (_geometry === undefined) {
  16303. _geometry = new BufferGeometry();
  16304. var 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]);
  16305. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16306. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16307. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16308. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16309. }
  16310. this.geometry = _geometry;
  16311. this.material = material !== undefined ? material : new SpriteMaterial();
  16312. this.center = new Vector2(0.5, 0.5);
  16313. }
  16314. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  16315. constructor: Sprite,
  16316. isSprite: true,
  16317. raycast: function (raycaster, intersects) {
  16318. if (raycaster.camera === null) {
  16319. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16320. }
  16321. _worldScale.setFromMatrixScale(this.matrixWorld);
  16322. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16323. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16324. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16325. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16326. _worldScale.multiplyScalar(-_mvPosition.z);
  16327. }
  16328. var rotation = this.material.rotation;
  16329. var sin, cos;
  16330. if (rotation !== 0) {
  16331. cos = Math.cos(rotation);
  16332. sin = Math.sin(rotation);
  16333. }
  16334. var center = this.center;
  16335. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16336. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16337. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16338. _uvA$1.set(0, 0);
  16339. _uvB$1.set(1, 0);
  16340. _uvC$1.set(1, 1); // check first triangle
  16341. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  16342. if (intersect === null) {
  16343. // check second triangle
  16344. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16345. _uvB$1.set(0, 1);
  16346. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  16347. if (intersect === null) {
  16348. return;
  16349. }
  16350. }
  16351. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16352. if (distance < raycaster.near || distance > raycaster.far) return;
  16353. intersects.push({
  16354. distance: distance,
  16355. point: _intersectPoint.clone(),
  16356. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16357. face: null,
  16358. object: this
  16359. });
  16360. },
  16361. clone: function () {
  16362. return new this.constructor(this.material).copy(this);
  16363. },
  16364. copy: function (source) {
  16365. Object3D.prototype.copy.call(this, source);
  16366. if (source.center !== undefined) this.center.copy(source.center);
  16367. return this;
  16368. }
  16369. });
  16370. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16371. // compute position in camera space
  16372. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16373. if (sin !== undefined) {
  16374. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16375. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16376. } else {
  16377. _rotatedPosition.copy(_alignedPosition);
  16378. }
  16379. vertexPosition.copy(mvPosition);
  16380. vertexPosition.x += _rotatedPosition.x;
  16381. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16382. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16383. }
  16384. /**
  16385. * @author mikael emtinger / http://gomo.se/
  16386. * @author alteredq / http://alteredqualia.com/
  16387. * @author mrdoob / http://mrdoob.com/
  16388. */
  16389. var _v1$4 = new Vector3();
  16390. var _v2$2 = new Vector3();
  16391. function LOD() {
  16392. Object3D.call(this);
  16393. this._currentLevel = 0;
  16394. this.type = 'LOD';
  16395. Object.defineProperties(this, {
  16396. levels: {
  16397. enumerable: true,
  16398. value: []
  16399. }
  16400. });
  16401. this.autoUpdate = true;
  16402. }
  16403. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16404. constructor: LOD,
  16405. isLOD: true,
  16406. copy: function (source) {
  16407. Object3D.prototype.copy.call(this, source, false);
  16408. var levels = source.levels;
  16409. for (var i = 0, l = levels.length; i < l; i++) {
  16410. var level = levels[i];
  16411. this.addLevel(level.object.clone(), level.distance);
  16412. }
  16413. this.autoUpdate = source.autoUpdate;
  16414. return this;
  16415. },
  16416. addLevel: function (object, distance) {
  16417. if (distance === undefined) distance = 0;
  16418. distance = Math.abs(distance);
  16419. var levels = this.levels;
  16420. for (var l = 0; l < levels.length; l++) {
  16421. if (distance < levels[l].distance) {
  16422. break;
  16423. }
  16424. }
  16425. levels.splice(l, 0, {
  16426. distance: distance,
  16427. object: object
  16428. });
  16429. this.add(object);
  16430. return this;
  16431. },
  16432. getCurrentLevel: function () {
  16433. return this._currentLevel;
  16434. },
  16435. getObjectForDistance: function (distance) {
  16436. var levels = this.levels;
  16437. if (levels.length > 0) {
  16438. for (var i = 1, l = levels.length; i < l; i++) {
  16439. if (distance < levels[i].distance) {
  16440. break;
  16441. }
  16442. }
  16443. return levels[i - 1].object;
  16444. }
  16445. return null;
  16446. },
  16447. raycast: function (raycaster, intersects) {
  16448. var levels = this.levels;
  16449. if (levels.length > 0) {
  16450. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16451. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  16452. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16453. }
  16454. },
  16455. update: function (camera) {
  16456. var levels = this.levels;
  16457. if (levels.length > 1) {
  16458. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16459. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16460. var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  16461. levels[0].object.visible = true;
  16462. for (var i = 1, l = levels.length; i < l; i++) {
  16463. if (distance >= levels[i].distance) {
  16464. levels[i - 1].object.visible = false;
  16465. levels[i].object.visible = true;
  16466. } else {
  16467. break;
  16468. }
  16469. }
  16470. this._currentLevel = i - 1;
  16471. for (; i < l; i++) {
  16472. levels[i].object.visible = false;
  16473. }
  16474. }
  16475. },
  16476. toJSON: function (meta) {
  16477. var data = Object3D.prototype.toJSON.call(this, meta);
  16478. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16479. data.object.levels = [];
  16480. var levels = this.levels;
  16481. for (var i = 0, l = levels.length; i < l; i++) {
  16482. var level = levels[i];
  16483. data.object.levels.push({
  16484. object: level.object.uuid,
  16485. distance: level.distance
  16486. });
  16487. }
  16488. return data;
  16489. }
  16490. });
  16491. /**
  16492. * @author mikael emtinger / http://gomo.se/
  16493. * @author alteredq / http://alteredqualia.com/
  16494. * @author ikerr / http://verold.com
  16495. */
  16496. function SkinnedMesh(geometry, material) {
  16497. if (geometry && geometry.isGeometry) {
  16498. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16499. }
  16500. Mesh.call(this, geometry, material);
  16501. this.type = 'SkinnedMesh';
  16502. this.bindMode = 'attached';
  16503. this.bindMatrix = new Matrix4();
  16504. this.bindMatrixInverse = new Matrix4();
  16505. }
  16506. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16507. constructor: SkinnedMesh,
  16508. isSkinnedMesh: true,
  16509. bind: function (skeleton, bindMatrix) {
  16510. this.skeleton = skeleton;
  16511. if (bindMatrix === undefined) {
  16512. this.updateMatrixWorld(true);
  16513. this.skeleton.calculateInverses();
  16514. bindMatrix = this.matrixWorld;
  16515. }
  16516. this.bindMatrix.copy(bindMatrix);
  16517. this.bindMatrixInverse.getInverse(bindMatrix);
  16518. },
  16519. pose: function () {
  16520. this.skeleton.pose();
  16521. },
  16522. normalizeSkinWeights: function () {
  16523. var vector = new Vector4();
  16524. var skinWeight = this.geometry.attributes.skinWeight;
  16525. for (var i = 0, l = skinWeight.count; i < l; i++) {
  16526. vector.x = skinWeight.getX(i);
  16527. vector.y = skinWeight.getY(i);
  16528. vector.z = skinWeight.getZ(i);
  16529. vector.w = skinWeight.getW(i);
  16530. var scale = 1.0 / vector.manhattanLength();
  16531. if (scale !== Infinity) {
  16532. vector.multiplyScalar(scale);
  16533. } else {
  16534. vector.set(1, 0, 0, 0); // do something reasonable
  16535. }
  16536. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16537. }
  16538. },
  16539. updateMatrixWorld: function (force) {
  16540. Mesh.prototype.updateMatrixWorld.call(this, force);
  16541. if (this.bindMode === 'attached') {
  16542. this.bindMatrixInverse.getInverse(this.matrixWorld);
  16543. } else if (this.bindMode === 'detached') {
  16544. this.bindMatrixInverse.getInverse(this.bindMatrix);
  16545. } else {
  16546. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16547. }
  16548. },
  16549. clone: function () {
  16550. return new this.constructor(this.geometry, this.material).copy(this);
  16551. }
  16552. });
  16553. /**
  16554. * @author mikael emtinger / http://gomo.se/
  16555. * @author alteredq / http://alteredqualia.com/
  16556. * @author michael guerrero / http://realitymeltdown.com
  16557. * @author ikerr / http://verold.com
  16558. */
  16559. var _offsetMatrix = new Matrix4();
  16560. var _identityMatrix = new Matrix4();
  16561. function Skeleton(bones, boneInverses) {
  16562. // copy the bone array
  16563. bones = bones || [];
  16564. this.bones = bones.slice(0);
  16565. this.boneMatrices = new Float32Array(this.bones.length * 16);
  16566. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  16567. if (boneInverses === undefined) {
  16568. this.calculateInverses();
  16569. } else {
  16570. if (this.bones.length === boneInverses.length) {
  16571. this.boneInverses = boneInverses.slice(0);
  16572. } else {
  16573. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  16574. this.boneInverses = [];
  16575. for (var i = 0, il = this.bones.length; i < il; i++) {
  16576. this.boneInverses.push(new Matrix4());
  16577. }
  16578. }
  16579. }
  16580. }
  16581. Object.assign(Skeleton.prototype, {
  16582. calculateInverses: function () {
  16583. this.boneInverses = [];
  16584. for (var i = 0, il = this.bones.length; i < il; i++) {
  16585. var inverse = new Matrix4();
  16586. if (this.bones[i]) {
  16587. inverse.getInverse(this.bones[i].matrixWorld);
  16588. }
  16589. this.boneInverses.push(inverse);
  16590. }
  16591. },
  16592. pose: function () {
  16593. var bone, i, il; // recover the bind-time world matrices
  16594. for (i = 0, il = this.bones.length; i < il; i++) {
  16595. bone = this.bones[i];
  16596. if (bone) {
  16597. bone.matrixWorld.getInverse(this.boneInverses[i]);
  16598. }
  16599. } // compute the local matrices, positions, rotations and scales
  16600. for (i = 0, il = this.bones.length; i < il; i++) {
  16601. bone = this.bones[i];
  16602. if (bone) {
  16603. if (bone.parent && bone.parent.isBone) {
  16604. bone.matrix.getInverse(bone.parent.matrixWorld);
  16605. bone.matrix.multiply(bone.matrixWorld);
  16606. } else {
  16607. bone.matrix.copy(bone.matrixWorld);
  16608. }
  16609. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16610. }
  16611. }
  16612. },
  16613. update: function () {
  16614. var bones = this.bones;
  16615. var boneInverses = this.boneInverses;
  16616. var boneMatrices = this.boneMatrices;
  16617. var boneTexture = this.boneTexture; // flatten bone matrices to array
  16618. for (var i = 0, il = bones.length; i < il; i++) {
  16619. // compute the offset between the current and the original transform
  16620. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16621. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16622. _offsetMatrix.toArray(boneMatrices, i * 16);
  16623. }
  16624. if (boneTexture !== undefined) {
  16625. boneTexture.needsUpdate = true;
  16626. }
  16627. },
  16628. clone: function () {
  16629. return new Skeleton(this.bones, this.boneInverses);
  16630. },
  16631. getBoneByName: function (name) {
  16632. for (var i = 0, il = this.bones.length; i < il; i++) {
  16633. var bone = this.bones[i];
  16634. if (bone.name === name) {
  16635. return bone;
  16636. }
  16637. }
  16638. return undefined;
  16639. },
  16640. dispose: function () {
  16641. if (this.boneTexture) {
  16642. this.boneTexture.dispose();
  16643. this.boneTexture = undefined;
  16644. }
  16645. }
  16646. });
  16647. /**
  16648. * @author mikael emtinger / http://gomo.se/
  16649. * @author alteredq / http://alteredqualia.com/
  16650. * @author ikerr / http://verold.com
  16651. */
  16652. function Bone() {
  16653. Object3D.call(this);
  16654. this.type = 'Bone';
  16655. }
  16656. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16657. constructor: Bone,
  16658. isBone: true
  16659. });
  16660. /**
  16661. * @author mrdoob / http://mrdoob.com/
  16662. */
  16663. var _instanceLocalMatrix = new Matrix4();
  16664. var _instanceWorldMatrix = new Matrix4();
  16665. var _instanceIntersects = [];
  16666. var _mesh = new Mesh();
  16667. function InstancedMesh(geometry, material, count) {
  16668. Mesh.call(this, geometry, material);
  16669. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16670. this.count = count;
  16671. this.frustumCulled = false;
  16672. }
  16673. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16674. constructor: InstancedMesh,
  16675. isInstancedMesh: true,
  16676. getMatrixAt: function (index, matrix) {
  16677. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16678. },
  16679. raycast: function (raycaster, intersects) {
  16680. var matrixWorld = this.matrixWorld;
  16681. var raycastTimes = this.count;
  16682. _mesh.geometry = this.geometry;
  16683. _mesh.material = this.material;
  16684. if (_mesh.material === undefined) return;
  16685. for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16686. // calculate the world matrix for each instance
  16687. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16688. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16689. _mesh.matrixWorld = _instanceWorldMatrix;
  16690. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16691. if (_instanceIntersects.length > 0) {
  16692. _instanceIntersects[0].instanceId = instanceId;
  16693. _instanceIntersects[0].object = this;
  16694. intersects.push(_instanceIntersects[0]);
  16695. _instanceIntersects.length = 0;
  16696. }
  16697. }
  16698. },
  16699. setMatrixAt: function (index, matrix) {
  16700. matrix.toArray(this.instanceMatrix.array, index * 16);
  16701. },
  16702. updateMorphTargets: function () {}
  16703. });
  16704. /**
  16705. * @author mrdoob / http://mrdoob.com/
  16706. * @author alteredq / http://alteredqualia.com/
  16707. *
  16708. * parameters = {
  16709. * color: <hex>,
  16710. * opacity: <float>,
  16711. *
  16712. * linewidth: <float>,
  16713. * linecap: "round",
  16714. * linejoin: "round"
  16715. * }
  16716. */
  16717. function LineBasicMaterial(parameters) {
  16718. Material.call(this);
  16719. this.type = 'LineBasicMaterial';
  16720. this.color = new Color(0xffffff);
  16721. this.linewidth = 1;
  16722. this.linecap = 'round';
  16723. this.linejoin = 'round';
  16724. this.setValues(parameters);
  16725. }
  16726. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16727. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16728. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16729. LineBasicMaterial.prototype.copy = function (source) {
  16730. Material.prototype.copy.call(this, source);
  16731. this.color.copy(source.color);
  16732. this.linewidth = source.linewidth;
  16733. this.linecap = source.linecap;
  16734. this.linejoin = source.linejoin;
  16735. return this;
  16736. };
  16737. /**
  16738. * @author mrdoob / http://mrdoob.com/
  16739. */
  16740. var _start = new Vector3();
  16741. var _end = new Vector3();
  16742. var _inverseMatrix$1 = new Matrix4();
  16743. var _ray$1 = new Ray();
  16744. var _sphere$2 = new Sphere();
  16745. function Line(geometry, material, mode) {
  16746. if (mode === 1) {
  16747. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16748. }
  16749. Object3D.call(this);
  16750. this.type = 'Line';
  16751. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16752. this.material = material !== undefined ? material : new LineBasicMaterial();
  16753. }
  16754. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16755. constructor: Line,
  16756. isLine: true,
  16757. computeLineDistances: function () {
  16758. var geometry = this.geometry;
  16759. if (geometry.isBufferGeometry) {
  16760. // we assume non-indexed geometry
  16761. if (geometry.index === null) {
  16762. var positionAttribute = geometry.attributes.position;
  16763. var lineDistances = [0];
  16764. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  16765. _start.fromBufferAttribute(positionAttribute, i - 1);
  16766. _end.fromBufferAttribute(positionAttribute, i);
  16767. lineDistances[i] = lineDistances[i - 1];
  16768. lineDistances[i] += _start.distanceTo(_end);
  16769. }
  16770. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16771. } else {
  16772. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16773. }
  16774. } else if (geometry.isGeometry) {
  16775. var vertices = geometry.vertices;
  16776. var lineDistances = geometry.lineDistances;
  16777. lineDistances[0] = 0;
  16778. for (var i = 1, l = vertices.length; i < l; i++) {
  16779. lineDistances[i] = lineDistances[i - 1];
  16780. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16781. }
  16782. }
  16783. return this;
  16784. },
  16785. raycast: function (raycaster, intersects) {
  16786. var geometry = this.geometry;
  16787. var matrixWorld = this.matrixWorld;
  16788. var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  16789. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16790. _sphere$2.copy(geometry.boundingSphere);
  16791. _sphere$2.applyMatrix4(matrixWorld);
  16792. _sphere$2.radius += threshold;
  16793. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16794. _inverseMatrix$1.getInverse(matrixWorld);
  16795. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16796. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16797. var localThresholdSq = localThreshold * localThreshold;
  16798. var vStart = new Vector3();
  16799. var vEnd = new Vector3();
  16800. var interSegment = new Vector3();
  16801. var interRay = new Vector3();
  16802. var step = this && this.isLineSegments ? 2 : 1;
  16803. if (geometry.isBufferGeometry) {
  16804. var index = geometry.index;
  16805. var attributes = geometry.attributes;
  16806. var positions = attributes.position.array;
  16807. if (index !== null) {
  16808. var indices = index.array;
  16809. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  16810. var a = indices[i];
  16811. var b = indices[i + 1];
  16812. vStart.fromArray(positions, a * 3);
  16813. vEnd.fromArray(positions, b * 3);
  16814. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16815. if (distSq > localThresholdSq) continue;
  16816. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16817. var distance = raycaster.ray.origin.distanceTo(interRay);
  16818. if (distance < raycaster.near || distance > raycaster.far) continue;
  16819. intersects.push({
  16820. distance: distance,
  16821. // What do we want? intersection point on the ray or on the segment??
  16822. // point: raycaster.ray.at( distance ),
  16823. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16824. index: i,
  16825. face: null,
  16826. faceIndex: null,
  16827. object: this
  16828. });
  16829. }
  16830. } else {
  16831. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  16832. vStart.fromArray(positions, 3 * i);
  16833. vEnd.fromArray(positions, 3 * i + 3);
  16834. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16835. if (distSq > localThresholdSq) continue;
  16836. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16837. var distance = raycaster.ray.origin.distanceTo(interRay);
  16838. if (distance < raycaster.near || distance > raycaster.far) continue;
  16839. intersects.push({
  16840. distance: distance,
  16841. // What do we want? intersection point on the ray or on the segment??
  16842. // point: raycaster.ray.at( distance ),
  16843. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16844. index: i,
  16845. face: null,
  16846. faceIndex: null,
  16847. object: this
  16848. });
  16849. }
  16850. }
  16851. } else if (geometry.isGeometry) {
  16852. var vertices = geometry.vertices;
  16853. var nbVertices = vertices.length;
  16854. for (var i = 0; i < nbVertices - 1; i += step) {
  16855. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16856. if (distSq > localThresholdSq) continue;
  16857. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16858. var distance = raycaster.ray.origin.distanceTo(interRay);
  16859. if (distance < raycaster.near || distance > raycaster.far) continue;
  16860. intersects.push({
  16861. distance: distance,
  16862. // What do we want? intersection point on the ray or on the segment??
  16863. // point: raycaster.ray.at( distance ),
  16864. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16865. index: i,
  16866. face: null,
  16867. faceIndex: null,
  16868. object: this
  16869. });
  16870. }
  16871. }
  16872. },
  16873. clone: function () {
  16874. return new this.constructor(this.geometry, this.material).copy(this);
  16875. }
  16876. });
  16877. /**
  16878. * @author mrdoob / http://mrdoob.com/
  16879. */
  16880. var _start$1 = new Vector3();
  16881. var _end$1 = new Vector3();
  16882. function LineSegments(geometry, material) {
  16883. Line.call(this, geometry, material);
  16884. this.type = 'LineSegments';
  16885. }
  16886. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16887. constructor: LineSegments,
  16888. isLineSegments: true,
  16889. computeLineDistances: function () {
  16890. var geometry = this.geometry;
  16891. if (geometry.isBufferGeometry) {
  16892. // we assume non-indexed geometry
  16893. if (geometry.index === null) {
  16894. var positionAttribute = geometry.attributes.position;
  16895. var lineDistances = [];
  16896. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  16897. _start$1.fromBufferAttribute(positionAttribute, i);
  16898. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16899. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16900. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16901. }
  16902. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16903. } else {
  16904. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16905. }
  16906. } else if (geometry.isGeometry) {
  16907. var vertices = geometry.vertices;
  16908. var lineDistances = geometry.lineDistances;
  16909. for (var i = 0, l = vertices.length; i < l; i += 2) {
  16910. _start$1.copy(vertices[i]);
  16911. _end$1.copy(vertices[i + 1]);
  16912. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16913. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16914. }
  16915. }
  16916. return this;
  16917. }
  16918. });
  16919. /**
  16920. * @author mgreter / http://github.com/mgreter
  16921. */
  16922. function LineLoop(geometry, material) {
  16923. Line.call(this, geometry, material);
  16924. this.type = 'LineLoop';
  16925. }
  16926. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16927. constructor: LineLoop,
  16928. isLineLoop: true
  16929. });
  16930. /**
  16931. * @author mrdoob / http://mrdoob.com/
  16932. * @author alteredq / http://alteredqualia.com/
  16933. *
  16934. * parameters = {
  16935. * color: <hex>,
  16936. * opacity: <float>,
  16937. * map: new THREE.Texture( <Image> ),
  16938. * alphaMap: new THREE.Texture( <Image> ),
  16939. *
  16940. * size: <float>,
  16941. * sizeAttenuation: <bool>
  16942. *
  16943. * morphTargets: <bool>
  16944. * }
  16945. */
  16946. function PointsMaterial(parameters) {
  16947. Material.call(this);
  16948. this.type = 'PointsMaterial';
  16949. this.color = new Color(0xffffff);
  16950. this.map = null;
  16951. this.alphaMap = null;
  16952. this.size = 1;
  16953. this.sizeAttenuation = true;
  16954. this.morphTargets = false;
  16955. this.setValues(parameters);
  16956. }
  16957. PointsMaterial.prototype = Object.create(Material.prototype);
  16958. PointsMaterial.prototype.constructor = PointsMaterial;
  16959. PointsMaterial.prototype.isPointsMaterial = true;
  16960. PointsMaterial.prototype.copy = function (source) {
  16961. Material.prototype.copy.call(this, source);
  16962. this.color.copy(source.color);
  16963. this.map = source.map;
  16964. this.alphaMap = source.alphaMap;
  16965. this.size = source.size;
  16966. this.sizeAttenuation = source.sizeAttenuation;
  16967. this.morphTargets = source.morphTargets;
  16968. return this;
  16969. };
  16970. /**
  16971. * @author alteredq / http://alteredqualia.com/
  16972. */
  16973. var _inverseMatrix$2 = new Matrix4();
  16974. var _ray$2 = new Ray();
  16975. var _sphere$3 = new Sphere();
  16976. var _position$1 = new Vector3();
  16977. function Points(geometry, material) {
  16978. Object3D.call(this);
  16979. this.type = 'Points';
  16980. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16981. this.material = material !== undefined ? material : new PointsMaterial();
  16982. this.updateMorphTargets();
  16983. }
  16984. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16985. constructor: Points,
  16986. isPoints: true,
  16987. raycast: function (raycaster, intersects) {
  16988. var geometry = this.geometry;
  16989. var matrixWorld = this.matrixWorld;
  16990. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16991. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16992. _sphere$3.copy(geometry.boundingSphere);
  16993. _sphere$3.applyMatrix4(matrixWorld);
  16994. _sphere$3.radius += threshold;
  16995. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16996. _inverseMatrix$2.getInverse(matrixWorld);
  16997. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16998. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16999. var localThresholdSq = localThreshold * localThreshold;
  17000. if (geometry.isBufferGeometry) {
  17001. var index = geometry.index;
  17002. var attributes = geometry.attributes;
  17003. var positions = attributes.position.array;
  17004. if (index !== null) {
  17005. var indices = index.array;
  17006. for (var i = 0, il = indices.length; i < il; i++) {
  17007. var a = indices[i];
  17008. _position$1.fromArray(positions, a * 3);
  17009. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17010. }
  17011. } else {
  17012. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17013. _position$1.fromArray(positions, i * 3);
  17014. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17015. }
  17016. }
  17017. } else {
  17018. var vertices = geometry.vertices;
  17019. for (var i = 0, l = vertices.length; i < l; i++) {
  17020. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17021. }
  17022. }
  17023. },
  17024. updateMorphTargets: function () {
  17025. var geometry = this.geometry;
  17026. var m, ml, name;
  17027. if (geometry.isBufferGeometry) {
  17028. var morphAttributes = geometry.morphAttributes;
  17029. var keys = Object.keys(morphAttributes);
  17030. if (keys.length > 0) {
  17031. var morphAttribute = morphAttributes[keys[0]];
  17032. if (morphAttribute !== undefined) {
  17033. this.morphTargetInfluences = [];
  17034. this.morphTargetDictionary = {};
  17035. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17036. name = morphAttribute[m].name || String(m);
  17037. this.morphTargetInfluences.push(0);
  17038. this.morphTargetDictionary[name] = m;
  17039. }
  17040. }
  17041. }
  17042. } else {
  17043. var morphTargets = geometry.morphTargets;
  17044. if (morphTargets !== undefined && morphTargets.length > 0) {
  17045. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17046. }
  17047. }
  17048. },
  17049. clone: function () {
  17050. return new this.constructor(this.geometry, this.material).copy(this);
  17051. }
  17052. });
  17053. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17054. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17055. if (rayPointDistanceSq < localThresholdSq) {
  17056. var intersectPoint = new Vector3();
  17057. _ray$2.closestPointToPoint(point, intersectPoint);
  17058. intersectPoint.applyMatrix4(matrixWorld);
  17059. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17060. if (distance < raycaster.near || distance > raycaster.far) return;
  17061. intersects.push({
  17062. distance: distance,
  17063. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17064. point: intersectPoint,
  17065. index: index,
  17066. face: null,
  17067. object: object
  17068. });
  17069. }
  17070. }
  17071. /**
  17072. * @author mrdoob / http://mrdoob.com/
  17073. */
  17074. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17075. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17076. this.format = format !== undefined ? format : RGBFormat;
  17077. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17078. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17079. this.generateMipmaps = false;
  17080. }
  17081. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17082. constructor: VideoTexture,
  17083. isVideoTexture: true,
  17084. update: function () {
  17085. var video = this.image;
  17086. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17087. this.needsUpdate = true;
  17088. }
  17089. }
  17090. });
  17091. /**
  17092. * @author alteredq / http://alteredqualia.com/
  17093. */
  17094. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17095. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17096. this.image = {
  17097. width: width,
  17098. height: height
  17099. };
  17100. this.mipmaps = mipmaps; // no flipping for cube textures
  17101. // (also flipping doesn't work for compressed textures )
  17102. this.flipY = false; // can't generate mipmaps for compressed textures
  17103. // mips must be embedded in DDS files
  17104. this.generateMipmaps = false;
  17105. }
  17106. CompressedTexture.prototype = Object.create(Texture.prototype);
  17107. CompressedTexture.prototype.constructor = CompressedTexture;
  17108. CompressedTexture.prototype.isCompressedTexture = true;
  17109. /**
  17110. * @author mrdoob / http://mrdoob.com/
  17111. */
  17112. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17113. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17114. this.needsUpdate = true;
  17115. }
  17116. CanvasTexture.prototype = Object.create(Texture.prototype);
  17117. CanvasTexture.prototype.constructor = CanvasTexture;
  17118. CanvasTexture.prototype.isCanvasTexture = true;
  17119. /**
  17120. * @author Matt DesLauriers / @mattdesl
  17121. * @author atix / arthursilber.de
  17122. */
  17123. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17124. format = format !== undefined ? format : DepthFormat;
  17125. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17126. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17127. }
  17128. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17129. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17130. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17131. this.image = {
  17132. width: width,
  17133. height: height
  17134. };
  17135. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17136. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17137. this.flipY = false;
  17138. this.generateMipmaps = false;
  17139. }
  17140. DepthTexture.prototype = Object.create(Texture.prototype);
  17141. DepthTexture.prototype.constructor = DepthTexture;
  17142. DepthTexture.prototype.isDepthTexture = true;
  17143. /**
  17144. * @author mrdoob / http://mrdoob.com/
  17145. * @author Mugen87 / https://github.com/Mugen87
  17146. */
  17147. function WireframeGeometry(geometry) {
  17148. BufferGeometry.call(this);
  17149. this.type = 'WireframeGeometry'; // buffer
  17150. var vertices = []; // helper variables
  17151. var i, j, l, o, ol;
  17152. var edge = [0, 0],
  17153. edges = {},
  17154. e,
  17155. edge1,
  17156. edge2;
  17157. var key,
  17158. keys = ['a', 'b', 'c'];
  17159. var vertex; // different logic for Geometry and BufferGeometry
  17160. if (geometry && geometry.isGeometry) {
  17161. // create a data structure that contains all edges without duplicates
  17162. var faces = geometry.faces;
  17163. for (i = 0, l = faces.length; i < l; i++) {
  17164. var face = faces[i];
  17165. for (j = 0; j < 3; j++) {
  17166. edge1 = face[keys[j]];
  17167. edge2 = face[keys[(j + 1) % 3]];
  17168. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17169. edge[1] = Math.max(edge1, edge2);
  17170. key = edge[0] + ',' + edge[1];
  17171. if (edges[key] === undefined) {
  17172. edges[key] = {
  17173. index1: edge[0],
  17174. index2: edge[1]
  17175. };
  17176. }
  17177. }
  17178. } // generate vertices
  17179. for (key in edges) {
  17180. e = edges[key];
  17181. vertex = geometry.vertices[e.index1];
  17182. vertices.push(vertex.x, vertex.y, vertex.z);
  17183. vertex = geometry.vertices[e.index2];
  17184. vertices.push(vertex.x, vertex.y, vertex.z);
  17185. }
  17186. } else if (geometry && geometry.isBufferGeometry) {
  17187. var position, indices, groups;
  17188. var group, start, count;
  17189. var index1, index2;
  17190. vertex = new Vector3();
  17191. if (geometry.index !== null) {
  17192. // indexed BufferGeometry
  17193. position = geometry.attributes.position;
  17194. indices = geometry.index;
  17195. groups = geometry.groups;
  17196. if (groups.length === 0) {
  17197. groups = [{
  17198. start: 0,
  17199. count: indices.count,
  17200. materialIndex: 0
  17201. }];
  17202. } // create a data structure that contains all eges without duplicates
  17203. for (o = 0, ol = groups.length; o < ol; ++o) {
  17204. group = groups[o];
  17205. start = group.start;
  17206. count = group.count;
  17207. for (i = start, l = start + count; i < l; i += 3) {
  17208. for (j = 0; j < 3; j++) {
  17209. edge1 = indices.getX(i + j);
  17210. edge2 = indices.getX(i + (j + 1) % 3);
  17211. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17212. edge[1] = Math.max(edge1, edge2);
  17213. key = edge[0] + ',' + edge[1];
  17214. if (edges[key] === undefined) {
  17215. edges[key] = {
  17216. index1: edge[0],
  17217. index2: edge[1]
  17218. };
  17219. }
  17220. }
  17221. }
  17222. } // generate vertices
  17223. for (key in edges) {
  17224. e = edges[key];
  17225. vertex.fromBufferAttribute(position, e.index1);
  17226. vertices.push(vertex.x, vertex.y, vertex.z);
  17227. vertex.fromBufferAttribute(position, e.index2);
  17228. vertices.push(vertex.x, vertex.y, vertex.z);
  17229. }
  17230. } else {
  17231. // non-indexed BufferGeometry
  17232. position = geometry.attributes.position;
  17233. for (i = 0, l = position.count / 3; i < l; i++) {
  17234. for (j = 0; j < 3; j++) {
  17235. // three edges per triangle, an edge is represented as (index1, index2)
  17236. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  17237. index1 = 3 * i + j;
  17238. vertex.fromBufferAttribute(position, index1);
  17239. vertices.push(vertex.x, vertex.y, vertex.z);
  17240. index2 = 3 * i + (j + 1) % 3;
  17241. vertex.fromBufferAttribute(position, index2);
  17242. vertices.push(vertex.x, vertex.y, vertex.z);
  17243. }
  17244. }
  17245. }
  17246. } // build geometry
  17247. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17248. }
  17249. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  17250. WireframeGeometry.prototype.constructor = WireframeGeometry;
  17251. /**
  17252. * @author zz85 / https://github.com/zz85
  17253. * @author Mugen87 / https://github.com/Mugen87
  17254. *
  17255. * Parametric Surfaces Geometry
  17256. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17257. */
  17258. // ParametricGeometry
  17259. function ParametricGeometry(func, slices, stacks) {
  17260. Geometry.call(this);
  17261. this.type = 'ParametricGeometry';
  17262. this.parameters = {
  17263. func: func,
  17264. slices: slices,
  17265. stacks: stacks
  17266. };
  17267. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  17268. this.mergeVertices();
  17269. }
  17270. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  17271. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  17272. function ParametricBufferGeometry(func, slices, stacks) {
  17273. BufferGeometry.call(this);
  17274. this.type = 'ParametricBufferGeometry';
  17275. this.parameters = {
  17276. func: func,
  17277. slices: slices,
  17278. stacks: stacks
  17279. }; // buffers
  17280. var indices = [];
  17281. var vertices = [];
  17282. var normals = [];
  17283. var uvs = [];
  17284. var EPS = 0.00001;
  17285. var normal = new Vector3();
  17286. var p0 = new Vector3(),
  17287. p1 = new Vector3();
  17288. var pu = new Vector3(),
  17289. pv = new Vector3();
  17290. var i, j;
  17291. if (func.length < 3) {
  17292. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17293. } // generate vertices, normals and uvs
  17294. var sliceCount = slices + 1;
  17295. for (i = 0; i <= stacks; i++) {
  17296. var v = i / stacks;
  17297. for (j = 0; j <= slices; j++) {
  17298. var u = j / slices; // vertex
  17299. func(u, v, p0);
  17300. vertices.push(p0.x, p0.y, p0.z); // normal
  17301. // approximate tangent vectors via finite differences
  17302. if (u - EPS >= 0) {
  17303. func(u - EPS, v, p1);
  17304. pu.subVectors(p0, p1);
  17305. } else {
  17306. func(u + EPS, v, p1);
  17307. pu.subVectors(p1, p0);
  17308. }
  17309. if (v - EPS >= 0) {
  17310. func(u, v - EPS, p1);
  17311. pv.subVectors(p0, p1);
  17312. } else {
  17313. func(u, v + EPS, p1);
  17314. pv.subVectors(p1, p0);
  17315. } // cross product of tangent vectors returns surface normal
  17316. normal.crossVectors(pu, pv).normalize();
  17317. normals.push(normal.x, normal.y, normal.z); // uv
  17318. uvs.push(u, v);
  17319. }
  17320. } // generate indices
  17321. for (i = 0; i < stacks; i++) {
  17322. for (j = 0; j < slices; j++) {
  17323. var a = i * sliceCount + j;
  17324. var b = i * sliceCount + j + 1;
  17325. var c = (i + 1) * sliceCount + j + 1;
  17326. var d = (i + 1) * sliceCount + j; // faces one and two
  17327. indices.push(a, b, d);
  17328. indices.push(b, c, d);
  17329. }
  17330. } // build geometry
  17331. this.setIndex(indices);
  17332. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17333. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17334. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17335. }
  17336. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17337. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  17338. /**
  17339. * @author clockworkgeek / https://github.com/clockworkgeek
  17340. * @author timothypratley / https://github.com/timothypratley
  17341. * @author WestLangley / http://github.com/WestLangley
  17342. * @author Mugen87 / https://github.com/Mugen87
  17343. */
  17344. // PolyhedronGeometry
  17345. function PolyhedronGeometry(vertices, indices, radius, detail) {
  17346. Geometry.call(this);
  17347. this.type = 'PolyhedronGeometry';
  17348. this.parameters = {
  17349. vertices: vertices,
  17350. indices: indices,
  17351. radius: radius,
  17352. detail: detail
  17353. };
  17354. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  17355. this.mergeVertices();
  17356. }
  17357. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  17358. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  17359. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  17360. BufferGeometry.call(this);
  17361. this.type = 'PolyhedronBufferGeometry';
  17362. this.parameters = {
  17363. vertices: vertices,
  17364. indices: indices,
  17365. radius: radius,
  17366. detail: detail
  17367. };
  17368. radius = radius || 1;
  17369. detail = detail || 0; // default buffer data
  17370. var vertexBuffer = [];
  17371. var uvBuffer = []; // the subdivision creates the vertex buffer data
  17372. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17373. applyRadius(radius); // finally, create the uv data
  17374. generateUVs(); // build non-indexed geometry
  17375. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17376. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17377. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17378. if (detail === 0) {
  17379. this.computeVertexNormals(); // flat normals
  17380. } else {
  17381. this.normalizeNormals(); // smooth normals
  17382. } // helper functions
  17383. function subdivide(detail) {
  17384. var a = new Vector3();
  17385. var b = new Vector3();
  17386. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17387. for (var i = 0; i < indices.length; i += 3) {
  17388. // get the vertices of the face
  17389. getVertexByIndex(indices[i + 0], a);
  17390. getVertexByIndex(indices[i + 1], b);
  17391. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17392. subdivideFace(a, b, c, detail);
  17393. }
  17394. }
  17395. function subdivideFace(a, b, c, detail) {
  17396. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  17397. var v = [];
  17398. var i, j; // construct all of the vertices for this subdivision
  17399. for (i = 0; i <= cols; i++) {
  17400. v[i] = [];
  17401. var aj = a.clone().lerp(c, i / cols);
  17402. var bj = b.clone().lerp(c, i / cols);
  17403. var rows = cols - i;
  17404. for (j = 0; j <= rows; j++) {
  17405. if (j === 0 && i === cols) {
  17406. v[i][j] = aj;
  17407. } else {
  17408. v[i][j] = aj.clone().lerp(bj, j / rows);
  17409. }
  17410. }
  17411. } // construct all of the faces
  17412. for (i = 0; i < cols; i++) {
  17413. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  17414. var k = Math.floor(j / 2);
  17415. if (j % 2 === 0) {
  17416. pushVertex(v[i][k + 1]);
  17417. pushVertex(v[i + 1][k]);
  17418. pushVertex(v[i][k]);
  17419. } else {
  17420. pushVertex(v[i][k + 1]);
  17421. pushVertex(v[i + 1][k + 1]);
  17422. pushVertex(v[i + 1][k]);
  17423. }
  17424. }
  17425. }
  17426. }
  17427. function applyRadius(radius) {
  17428. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17429. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17430. vertex.x = vertexBuffer[i + 0];
  17431. vertex.y = vertexBuffer[i + 1];
  17432. vertex.z = vertexBuffer[i + 2];
  17433. vertex.normalize().multiplyScalar(radius);
  17434. vertexBuffer[i + 0] = vertex.x;
  17435. vertexBuffer[i + 1] = vertex.y;
  17436. vertexBuffer[i + 2] = vertex.z;
  17437. }
  17438. }
  17439. function generateUVs() {
  17440. var vertex = new Vector3();
  17441. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17442. vertex.x = vertexBuffer[i + 0];
  17443. vertex.y = vertexBuffer[i + 1];
  17444. vertex.z = vertexBuffer[i + 2];
  17445. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17446. var v = inclination(vertex) / Math.PI + 0.5;
  17447. uvBuffer.push(u, 1 - v);
  17448. }
  17449. correctUVs();
  17450. correctSeam();
  17451. }
  17452. function correctSeam() {
  17453. // handle case when face straddles the seam, see #3269
  17454. for (var i = 0; i < uvBuffer.length; i += 6) {
  17455. // uv data of a single face
  17456. var x0 = uvBuffer[i + 0];
  17457. var x1 = uvBuffer[i + 2];
  17458. var x2 = uvBuffer[i + 4];
  17459. var max = Math.max(x0, x1, x2);
  17460. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17461. if (max > 0.9 && min < 0.1) {
  17462. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17463. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17464. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17465. }
  17466. }
  17467. }
  17468. function pushVertex(vertex) {
  17469. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17470. }
  17471. function getVertexByIndex(index, vertex) {
  17472. var stride = index * 3;
  17473. vertex.x = vertices[stride + 0];
  17474. vertex.y = vertices[stride + 1];
  17475. vertex.z = vertices[stride + 2];
  17476. }
  17477. function correctUVs() {
  17478. var a = new Vector3();
  17479. var b = new Vector3();
  17480. var c = new Vector3();
  17481. var centroid = new Vector3();
  17482. var uvA = new Vector2();
  17483. var uvB = new Vector2();
  17484. var uvC = new Vector2();
  17485. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17486. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17487. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17488. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17489. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17490. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17491. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17492. centroid.copy(a).add(b).add(c).divideScalar(3);
  17493. var azi = azimuth(centroid);
  17494. correctUV(uvA, j + 0, a, azi);
  17495. correctUV(uvB, j + 2, b, azi);
  17496. correctUV(uvC, j + 4, c, azi);
  17497. }
  17498. }
  17499. function correctUV(uv, stride, vector, azimuth) {
  17500. if (azimuth < 0 && uv.x === 1) {
  17501. uvBuffer[stride] = uv.x - 1;
  17502. }
  17503. if (vector.x === 0 && vector.z === 0) {
  17504. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17505. }
  17506. } // Angle around the Y axis, counter-clockwise when looking from above.
  17507. function azimuth(vector) {
  17508. return Math.atan2(vector.z, -vector.x);
  17509. } // Angle above the XZ plane.
  17510. function inclination(vector) {
  17511. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17512. }
  17513. }
  17514. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17515. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  17516. /**
  17517. * @author timothypratley / https://github.com/timothypratley
  17518. * @author Mugen87 / https://github.com/Mugen87
  17519. */
  17520. // TetrahedronGeometry
  17521. function TetrahedronGeometry(radius, detail) {
  17522. Geometry.call(this);
  17523. this.type = 'TetrahedronGeometry';
  17524. this.parameters = {
  17525. radius: radius,
  17526. detail: detail
  17527. };
  17528. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  17529. this.mergeVertices();
  17530. }
  17531. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  17532. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  17533. function TetrahedronBufferGeometry(radius, detail) {
  17534. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  17535. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  17536. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17537. this.type = 'TetrahedronBufferGeometry';
  17538. this.parameters = {
  17539. radius: radius,
  17540. detail: detail
  17541. };
  17542. }
  17543. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17544. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  17545. /**
  17546. * @author timothypratley / https://github.com/timothypratley
  17547. * @author Mugen87 / https://github.com/Mugen87
  17548. */
  17549. // OctahedronGeometry
  17550. function OctahedronGeometry(radius, detail) {
  17551. Geometry.call(this);
  17552. this.type = 'OctahedronGeometry';
  17553. this.parameters = {
  17554. radius: radius,
  17555. detail: detail
  17556. };
  17557. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  17558. this.mergeVertices();
  17559. }
  17560. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  17561. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  17562. function OctahedronBufferGeometry(radius, detail) {
  17563. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17564. var 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];
  17565. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17566. this.type = 'OctahedronBufferGeometry';
  17567. this.parameters = {
  17568. radius: radius,
  17569. detail: detail
  17570. };
  17571. }
  17572. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17573. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  17574. /**
  17575. * @author timothypratley / https://github.com/timothypratley
  17576. * @author Mugen87 / https://github.com/Mugen87
  17577. */
  17578. // IcosahedronGeometry
  17579. function IcosahedronGeometry(radius, detail) {
  17580. Geometry.call(this);
  17581. this.type = 'IcosahedronGeometry';
  17582. this.parameters = {
  17583. radius: radius,
  17584. detail: detail
  17585. };
  17586. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  17587. this.mergeVertices();
  17588. }
  17589. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  17590. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  17591. function IcosahedronBufferGeometry(radius, detail) {
  17592. var t = (1 + Math.sqrt(5)) / 2;
  17593. var 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];
  17594. var 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];
  17595. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17596. this.type = 'IcosahedronBufferGeometry';
  17597. this.parameters = {
  17598. radius: radius,
  17599. detail: detail
  17600. };
  17601. }
  17602. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17603. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  17604. /**
  17605. * @author Abe Pazos / https://hamoid.com
  17606. * @author Mugen87 / https://github.com/Mugen87
  17607. */
  17608. // DodecahedronGeometry
  17609. function DodecahedronGeometry(radius, detail) {
  17610. Geometry.call(this);
  17611. this.type = 'DodecahedronGeometry';
  17612. this.parameters = {
  17613. radius: radius,
  17614. detail: detail
  17615. };
  17616. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  17617. this.mergeVertices();
  17618. }
  17619. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  17620. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  17621. function DodecahedronBufferGeometry(radius, detail) {
  17622. var t = (1 + Math.sqrt(5)) / 2;
  17623. var r = 1 / t;
  17624. var vertices = [// (±1, ±1, ±1)
  17625. -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/φ, ±φ)
  17626. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17627. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17628. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17629. var 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];
  17630. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17631. this.type = 'DodecahedronBufferGeometry';
  17632. this.parameters = {
  17633. radius: radius,
  17634. detail: detail
  17635. };
  17636. }
  17637. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17638. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  17639. /**
  17640. * @author oosmoxiecode / https://github.com/oosmoxiecode
  17641. * @author WestLangley / https://github.com/WestLangley
  17642. * @author zz85 / https://github.com/zz85
  17643. * @author miningold / https://github.com/miningold
  17644. * @author jonobr1 / https://github.com/jonobr1
  17645. * @author Mugen87 / https://github.com/Mugen87
  17646. *
  17647. */
  17648. // TubeGeometry
  17649. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  17650. Geometry.call(this);
  17651. this.type = 'TubeGeometry';
  17652. this.parameters = {
  17653. path: path,
  17654. tubularSegments: tubularSegments,
  17655. radius: radius,
  17656. radialSegments: radialSegments,
  17657. closed: closed
  17658. };
  17659. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  17660. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  17661. this.tangents = bufferGeometry.tangents;
  17662. this.normals = bufferGeometry.normals;
  17663. this.binormals = bufferGeometry.binormals; // create geometry
  17664. this.fromBufferGeometry(bufferGeometry);
  17665. this.mergeVertices();
  17666. }
  17667. TubeGeometry.prototype = Object.create(Geometry.prototype);
  17668. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  17669. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  17670. BufferGeometry.call(this);
  17671. this.type = 'TubeBufferGeometry';
  17672. this.parameters = {
  17673. path: path,
  17674. tubularSegments: tubularSegments,
  17675. radius: radius,
  17676. radialSegments: radialSegments,
  17677. closed: closed
  17678. };
  17679. tubularSegments = tubularSegments || 64;
  17680. radius = radius || 1;
  17681. radialSegments = radialSegments || 8;
  17682. closed = closed || false;
  17683. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  17684. this.tangents = frames.tangents;
  17685. this.normals = frames.normals;
  17686. this.binormals = frames.binormals; // helper variables
  17687. var vertex = new Vector3();
  17688. var normal = new Vector3();
  17689. var uv = new Vector2();
  17690. var P = new Vector3();
  17691. var i, j; // buffer
  17692. var vertices = [];
  17693. var normals = [];
  17694. var uvs = [];
  17695. var indices = []; // create buffer data
  17696. generateBufferData(); // build geometry
  17697. this.setIndex(indices);
  17698. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17699. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17700. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  17701. function generateBufferData() {
  17702. for (i = 0; i < tubularSegments; i++) {
  17703. generateSegment(i);
  17704. } // if the geometry is not closed, generate the last row of vertices and normals
  17705. // at the regular position on the given path
  17706. //
  17707. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  17708. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  17709. // this makes it easy compute correct values for closed geometries
  17710. generateUVs(); // finally create faces
  17711. generateIndices();
  17712. }
  17713. function generateSegment(i) {
  17714. // we use getPointAt to sample evenly distributed points from the given path
  17715. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  17716. var N = frames.normals[i];
  17717. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  17718. for (j = 0; j <= radialSegments; j++) {
  17719. var v = j / radialSegments * Math.PI * 2;
  17720. var sin = Math.sin(v);
  17721. var cos = -Math.cos(v); // normal
  17722. normal.x = cos * N.x + sin * B.x;
  17723. normal.y = cos * N.y + sin * B.y;
  17724. normal.z = cos * N.z + sin * B.z;
  17725. normal.normalize();
  17726. normals.push(normal.x, normal.y, normal.z); // vertex
  17727. vertex.x = P.x + radius * normal.x;
  17728. vertex.y = P.y + radius * normal.y;
  17729. vertex.z = P.z + radius * normal.z;
  17730. vertices.push(vertex.x, vertex.y, vertex.z);
  17731. }
  17732. }
  17733. function generateIndices() {
  17734. for (j = 1; j <= tubularSegments; j++) {
  17735. for (i = 1; i <= radialSegments; i++) {
  17736. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17737. var b = (radialSegments + 1) * j + (i - 1);
  17738. var c = (radialSegments + 1) * j + i;
  17739. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17740. indices.push(a, b, d);
  17741. indices.push(b, c, d);
  17742. }
  17743. }
  17744. }
  17745. function generateUVs() {
  17746. for (i = 0; i <= tubularSegments; i++) {
  17747. for (j = 0; j <= radialSegments; j++) {
  17748. uv.x = i / tubularSegments;
  17749. uv.y = j / radialSegments;
  17750. uvs.push(uv.x, uv.y);
  17751. }
  17752. }
  17753. }
  17754. }
  17755. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17756. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  17757. TubeBufferGeometry.prototype.toJSON = function () {
  17758. var data = BufferGeometry.prototype.toJSON.call(this);
  17759. data.path = this.parameters.path.toJSON();
  17760. return data;
  17761. };
  17762. /**
  17763. * @author oosmoxiecode
  17764. * @author Mugen87 / https://github.com/Mugen87
  17765. *
  17766. * based on http://www.blackpawn.com/texts/pqtorus/
  17767. */
  17768. // TorusKnotGeometry
  17769. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  17770. Geometry.call(this);
  17771. this.type = 'TorusKnotGeometry';
  17772. this.parameters = {
  17773. radius: radius,
  17774. tube: tube,
  17775. tubularSegments: tubularSegments,
  17776. radialSegments: radialSegments,
  17777. p: p,
  17778. q: q
  17779. };
  17780. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  17781. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  17782. this.mergeVertices();
  17783. }
  17784. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  17785. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  17786. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  17787. BufferGeometry.call(this);
  17788. this.type = 'TorusKnotBufferGeometry';
  17789. this.parameters = {
  17790. radius: radius,
  17791. tube: tube,
  17792. tubularSegments: tubularSegments,
  17793. radialSegments: radialSegments,
  17794. p: p,
  17795. q: q
  17796. };
  17797. radius = radius || 1;
  17798. tube = tube || 0.4;
  17799. tubularSegments = Math.floor(tubularSegments) || 64;
  17800. radialSegments = Math.floor(radialSegments) || 8;
  17801. p = p || 2;
  17802. q = q || 3; // buffers
  17803. var indices = [];
  17804. var vertices = [];
  17805. var normals = [];
  17806. var uvs = []; // helper variables
  17807. var i, j;
  17808. var vertex = new Vector3();
  17809. var normal = new Vector3();
  17810. var P1 = new Vector3();
  17811. var P2 = new Vector3();
  17812. var B = new Vector3();
  17813. var T = new Vector3();
  17814. var N = new Vector3(); // generate vertices, normals and uvs
  17815. for (i = 0; i <= tubularSegments; ++i) {
  17816. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17817. var 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.
  17818. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17819. calculatePositionOnCurve(u, p, q, radius, P1);
  17820. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  17821. T.subVectors(P2, P1);
  17822. N.addVectors(P2, P1);
  17823. B.crossVectors(T, N);
  17824. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  17825. B.normalize();
  17826. N.normalize();
  17827. for (j = 0; j <= radialSegments; ++j) {
  17828. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17829. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17830. var v = j / radialSegments * Math.PI * 2;
  17831. var cx = -tube * Math.cos(v);
  17832. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  17833. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17834. vertex.x = P1.x + (cx * N.x + cy * B.x);
  17835. vertex.y = P1.y + (cx * N.y + cy * B.y);
  17836. vertex.z = P1.z + (cx * N.z + cy * B.z);
  17837. 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)
  17838. normal.subVectors(vertex, P1).normalize();
  17839. normals.push(normal.x, normal.y, normal.z); // uv
  17840. uvs.push(i / tubularSegments);
  17841. uvs.push(j / radialSegments);
  17842. }
  17843. } // generate indices
  17844. for (j = 1; j <= tubularSegments; j++) {
  17845. for (i = 1; i <= radialSegments; i++) {
  17846. // indices
  17847. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17848. var b = (radialSegments + 1) * j + (i - 1);
  17849. var c = (radialSegments + 1) * j + i;
  17850. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17851. indices.push(a, b, d);
  17852. indices.push(b, c, d);
  17853. }
  17854. } // build geometry
  17855. this.setIndex(indices);
  17856. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17857. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17858. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  17859. function calculatePositionOnCurve(u, p, q, radius, position) {
  17860. var cu = Math.cos(u);
  17861. var su = Math.sin(u);
  17862. var quOverP = q / p * u;
  17863. var cs = Math.cos(quOverP);
  17864. position.x = radius * (2 + cs) * 0.5 * cu;
  17865. position.y = radius * (2 + cs) * su * 0.5;
  17866. position.z = radius * Math.sin(quOverP) * 0.5;
  17867. }
  17868. }
  17869. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17870. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  17871. /**
  17872. * @author oosmoxiecode
  17873. * @author mrdoob / http://mrdoob.com/
  17874. * @author Mugen87 / https://github.com/Mugen87
  17875. */
  17876. // TorusGeometry
  17877. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17878. Geometry.call(this);
  17879. this.type = 'TorusGeometry';
  17880. this.parameters = {
  17881. radius: radius,
  17882. tube: tube,
  17883. radialSegments: radialSegments,
  17884. tubularSegments: tubularSegments,
  17885. arc: arc
  17886. };
  17887. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  17888. this.mergeVertices();
  17889. }
  17890. TorusGeometry.prototype = Object.create(Geometry.prototype);
  17891. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  17892. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17893. BufferGeometry.call(this);
  17894. this.type = 'TorusBufferGeometry';
  17895. this.parameters = {
  17896. radius: radius,
  17897. tube: tube,
  17898. radialSegments: radialSegments,
  17899. tubularSegments: tubularSegments,
  17900. arc: arc
  17901. };
  17902. radius = radius || 1;
  17903. tube = tube || 0.4;
  17904. radialSegments = Math.floor(radialSegments) || 8;
  17905. tubularSegments = Math.floor(tubularSegments) || 6;
  17906. arc = arc || Math.PI * 2; // buffers
  17907. var indices = [];
  17908. var vertices = [];
  17909. var normals = [];
  17910. var uvs = []; // helper variables
  17911. var center = new Vector3();
  17912. var vertex = new Vector3();
  17913. var normal = new Vector3();
  17914. var j, i; // generate vertices, normals and uvs
  17915. for (j = 0; j <= radialSegments; j++) {
  17916. for (i = 0; i <= tubularSegments; i++) {
  17917. var u = i / tubularSegments * arc;
  17918. var v = j / radialSegments * Math.PI * 2; // vertex
  17919. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  17920. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  17921. vertex.z = tube * Math.sin(v);
  17922. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17923. center.x = radius * Math.cos(u);
  17924. center.y = radius * Math.sin(u);
  17925. normal.subVectors(vertex, center).normalize();
  17926. normals.push(normal.x, normal.y, normal.z); // uv
  17927. uvs.push(i / tubularSegments);
  17928. uvs.push(j / radialSegments);
  17929. }
  17930. } // generate indices
  17931. for (j = 1; j <= radialSegments; j++) {
  17932. for (i = 1; i <= tubularSegments; i++) {
  17933. // indices
  17934. var a = (tubularSegments + 1) * j + i - 1;
  17935. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  17936. var c = (tubularSegments + 1) * (j - 1) + i;
  17937. var d = (tubularSegments + 1) * j + i; // faces
  17938. indices.push(a, b, d);
  17939. indices.push(b, c, d);
  17940. }
  17941. } // build geometry
  17942. this.setIndex(indices);
  17943. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17944. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17945. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17946. }
  17947. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17948. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  17949. /**
  17950. * @author Mugen87 / https://github.com/Mugen87
  17951. * Port from https://github.com/mapbox/earcut (v2.1.5)
  17952. */
  17953. var Earcut = {
  17954. triangulate: function (data, holeIndices, dim) {
  17955. dim = dim || 2;
  17956. var hasHoles = holeIndices && holeIndices.length,
  17957. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  17958. outerNode = linkedList(data, 0, outerLen, dim, true),
  17959. triangles = [];
  17960. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17961. var minX, minY, maxX, maxY, x, y, invSize;
  17962. 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
  17963. if (data.length > 80 * dim) {
  17964. minX = maxX = data[0];
  17965. minY = maxY = data[1];
  17966. for (var i = dim; i < outerLen; i += dim) {
  17967. x = data[i];
  17968. y = data[i + 1];
  17969. if (x < minX) minX = x;
  17970. if (y < minY) minY = y;
  17971. if (x > maxX) maxX = x;
  17972. if (y > maxY) maxY = y;
  17973. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17974. invSize = Math.max(maxX - minX, maxY - minY);
  17975. invSize = invSize !== 0 ? 1 / invSize : 0;
  17976. }
  17977. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17978. return triangles;
  17979. }
  17980. }; // create a circular doubly linked list from polygon points in the specified winding order
  17981. function linkedList(data, start, end, dim, clockwise) {
  17982. var i, last;
  17983. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17984. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17985. } else {
  17986. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17987. }
  17988. if (last && equals(last, last.next)) {
  17989. removeNode(last);
  17990. last = last.next;
  17991. }
  17992. return last;
  17993. } // eliminate colinear or duplicate points
  17994. function filterPoints(start, end) {
  17995. if (!start) return start;
  17996. if (!end) end = start;
  17997. var p = start,
  17998. again;
  17999. do {
  18000. again = false;
  18001. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18002. removeNode(p);
  18003. p = end = p.prev;
  18004. if (p === p.next) break;
  18005. again = true;
  18006. } else {
  18007. p = p.next;
  18008. }
  18009. } while (again || p !== end);
  18010. return end;
  18011. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18012. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18013. if (!ear) return; // interlink polygon nodes in z-order
  18014. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18015. var stop = ear,
  18016. prev,
  18017. next; // iterate through ears, slicing them one by one
  18018. while (ear.prev !== ear.next) {
  18019. prev = ear.prev;
  18020. next = ear.next;
  18021. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18022. // cut off the triangle
  18023. triangles.push(prev.i / dim);
  18024. triangles.push(ear.i / dim);
  18025. triangles.push(next.i / dim);
  18026. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18027. ear = next.next;
  18028. stop = next.next;
  18029. continue;
  18030. }
  18031. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18032. if (ear === stop) {
  18033. // try filtering points and slicing again
  18034. if (!pass) {
  18035. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18036. } else if (pass === 1) {
  18037. ear = cureLocalIntersections(ear, triangles, dim);
  18038. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18039. } else if (pass === 2) {
  18040. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18041. }
  18042. break;
  18043. }
  18044. }
  18045. } // check whether a polygon node forms a valid ear with adjacent nodes
  18046. function isEar(ear) {
  18047. var a = ear.prev,
  18048. b = ear,
  18049. c = ear.next;
  18050. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18051. // now make sure we don't have other points inside the potential ear
  18052. var p = ear.next.next;
  18053. while (p !== ear.prev) {
  18054. 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;
  18055. p = p.next;
  18056. }
  18057. return true;
  18058. }
  18059. function isEarHashed(ear, minX, minY, invSize) {
  18060. var a = ear.prev,
  18061. b = ear,
  18062. c = ear.next;
  18063. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18064. // triangle bbox; min & max are calculated like this for speed
  18065. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18066. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18067. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18068. 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;
  18069. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18070. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18071. var p = ear.prevZ,
  18072. n = ear.nextZ; // look for points inside the triangle in both directions
  18073. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18074. 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;
  18075. p = p.prevZ;
  18076. 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;
  18077. n = n.nextZ;
  18078. } // look for remaining points in decreasing z-order
  18079. while (p && p.z >= minZ) {
  18080. 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;
  18081. p = p.prevZ;
  18082. } // look for remaining points in increasing z-order
  18083. while (n && n.z <= maxZ) {
  18084. 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;
  18085. n = n.nextZ;
  18086. }
  18087. return true;
  18088. } // go through all polygon nodes and cure small local self-intersections
  18089. function cureLocalIntersections(start, triangles, dim) {
  18090. var p = start;
  18091. do {
  18092. var a = p.prev,
  18093. b = p.next.next;
  18094. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18095. triangles.push(a.i / dim);
  18096. triangles.push(p.i / dim);
  18097. triangles.push(b.i / dim); // remove two nodes involved
  18098. removeNode(p);
  18099. removeNode(p.next);
  18100. p = start = b;
  18101. }
  18102. p = p.next;
  18103. } while (p !== start);
  18104. return p;
  18105. } // try splitting polygon into two and triangulate them independently
  18106. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18107. // look for a valid diagonal that divides the polygon into two
  18108. var a = start;
  18109. do {
  18110. var b = a.next.next;
  18111. while (b !== a.prev) {
  18112. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18113. // split the polygon in two by the diagonal
  18114. var c = splitPolygon(a, b); // filter colinear points around the cuts
  18115. a = filterPoints(a, a.next);
  18116. c = filterPoints(c, c.next); // run earcut on each half
  18117. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18118. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18119. return;
  18120. }
  18121. b = b.next;
  18122. }
  18123. a = a.next;
  18124. } while (a !== start);
  18125. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18126. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18127. var queue = [],
  18128. i,
  18129. len,
  18130. start,
  18131. end,
  18132. list;
  18133. for (i = 0, len = holeIndices.length; i < len; i++) {
  18134. start = holeIndices[i] * dim;
  18135. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18136. list = linkedList(data, start, end, dim, false);
  18137. if (list === list.next) list.steiner = true;
  18138. queue.push(getLeftmost(list));
  18139. }
  18140. queue.sort(compareX); // process holes from left to right
  18141. for (i = 0; i < queue.length; i++) {
  18142. eliminateHole(queue[i], outerNode);
  18143. outerNode = filterPoints(outerNode, outerNode.next);
  18144. }
  18145. return outerNode;
  18146. }
  18147. function compareX(a, b) {
  18148. return a.x - b.x;
  18149. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18150. function eliminateHole(hole, outerNode) {
  18151. outerNode = findHoleBridge(hole, outerNode);
  18152. if (outerNode) {
  18153. var b = splitPolygon(outerNode, hole);
  18154. filterPoints(b, b.next);
  18155. }
  18156. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18157. function findHoleBridge(hole, outerNode) {
  18158. var p = outerNode,
  18159. hx = hole.x,
  18160. hy = hole.y,
  18161. qx = -Infinity,
  18162. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18163. // segment's endpoint with lesser x will be potential connection point
  18164. do {
  18165. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18166. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18167. if (x <= hx && x > qx) {
  18168. qx = x;
  18169. if (x === hx) {
  18170. if (hy === p.y) return p;
  18171. if (hy === p.next.y) return p.next;
  18172. }
  18173. m = p.x < p.next.x ? p : p.next;
  18174. }
  18175. }
  18176. p = p.next;
  18177. } while (p !== outerNode);
  18178. if (!m) return null;
  18179. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  18180. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18181. // if there are no points found, we have a valid connection;
  18182. // otherwise choose the point of the minimum angle with the ray as connection point
  18183. var stop = m,
  18184. mx = m.x,
  18185. my = m.y,
  18186. tanMin = Infinity,
  18187. tan;
  18188. p = m.next;
  18189. while (p !== stop) {
  18190. 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)) {
  18191. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18192. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  18193. m = p;
  18194. tanMin = tan;
  18195. }
  18196. }
  18197. p = p.next;
  18198. }
  18199. return m;
  18200. } // interlink polygon nodes in z-order
  18201. function indexCurve(start, minX, minY, invSize) {
  18202. var p = start;
  18203. do {
  18204. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18205. p.prevZ = p.prev;
  18206. p.nextZ = p.next;
  18207. p = p.next;
  18208. } while (p !== start);
  18209. p.prevZ.nextZ = null;
  18210. p.prevZ = null;
  18211. sortLinked(p);
  18212. } // Simon Tatham's linked list merge sort algorithm
  18213. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18214. function sortLinked(list) {
  18215. var i,
  18216. p,
  18217. q,
  18218. e,
  18219. tail,
  18220. numMerges,
  18221. pSize,
  18222. qSize,
  18223. inSize = 1;
  18224. do {
  18225. p = list;
  18226. list = null;
  18227. tail = null;
  18228. numMerges = 0;
  18229. while (p) {
  18230. numMerges++;
  18231. q = p;
  18232. pSize = 0;
  18233. for (i = 0; i < inSize; i++) {
  18234. pSize++;
  18235. q = q.nextZ;
  18236. if (!q) break;
  18237. }
  18238. qSize = inSize;
  18239. while (pSize > 0 || qSize > 0 && q) {
  18240. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18241. e = p;
  18242. p = p.nextZ;
  18243. pSize--;
  18244. } else {
  18245. e = q;
  18246. q = q.nextZ;
  18247. qSize--;
  18248. }
  18249. if (tail) tail.nextZ = e;else list = e;
  18250. e.prevZ = tail;
  18251. tail = e;
  18252. }
  18253. p = q;
  18254. }
  18255. tail.nextZ = null;
  18256. inSize *= 2;
  18257. } while (numMerges > 1);
  18258. return list;
  18259. } // z-order of a point given coords and inverse of the longer side of data bbox
  18260. function zOrder(x, y, minX, minY, invSize) {
  18261. // coords are transformed into non-negative 15-bit integer range
  18262. x = 32767 * (x - minX) * invSize;
  18263. y = 32767 * (y - minY) * invSize;
  18264. x = (x | x << 8) & 0x00FF00FF;
  18265. x = (x | x << 4) & 0x0F0F0F0F;
  18266. x = (x | x << 2) & 0x33333333;
  18267. x = (x | x << 1) & 0x55555555;
  18268. y = (y | y << 8) & 0x00FF00FF;
  18269. y = (y | y << 4) & 0x0F0F0F0F;
  18270. y = (y | y << 2) & 0x33333333;
  18271. y = (y | y << 1) & 0x55555555;
  18272. return x | y << 1;
  18273. } // find the leftmost node of a polygon ring
  18274. function getLeftmost(start) {
  18275. var p = start,
  18276. leftmost = start;
  18277. do {
  18278. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18279. p = p.next;
  18280. } while (p !== start);
  18281. return leftmost;
  18282. } // check if a point lies within a convex triangle
  18283. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18284. 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;
  18285. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18286. function isValidDiagonal(a, b) {
  18287. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  18288. } // signed area of a triangle
  18289. function area(p, q, r) {
  18290. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18291. } // check if two points are equal
  18292. function equals(p1, p2) {
  18293. return p1.x === p2.x && p1.y === p2.y;
  18294. } // check if two segments intersect
  18295. function intersects(p1, q1, p2, q2) {
  18296. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  18297. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  18298. } // check if a polygon diagonal intersects any polygon segments
  18299. function intersectsPolygon(a, b) {
  18300. var p = a;
  18301. do {
  18302. 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;
  18303. p = p.next;
  18304. } while (p !== a);
  18305. return false;
  18306. } // check if a polygon diagonal is locally inside the polygon
  18307. function locallyInside(a, b) {
  18308. 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;
  18309. } // check if the middle point of a polygon diagonal is inside the polygon
  18310. function middleInside(a, b) {
  18311. var p = a,
  18312. inside = false,
  18313. px = (a.x + b.x) / 2,
  18314. py = (a.y + b.y) / 2;
  18315. do {
  18316. 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;
  18317. p = p.next;
  18318. } while (p !== a);
  18319. return inside;
  18320. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18321. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18322. function splitPolygon(a, b) {
  18323. var a2 = new Node(a.i, a.x, a.y),
  18324. b2 = new Node(b.i, b.x, b.y),
  18325. an = a.next,
  18326. bp = b.prev;
  18327. a.next = b;
  18328. b.prev = a;
  18329. a2.next = an;
  18330. an.prev = a2;
  18331. b2.next = a2;
  18332. a2.prev = b2;
  18333. bp.next = b2;
  18334. b2.prev = bp;
  18335. return b2;
  18336. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18337. function insertNode(i, x, y, last) {
  18338. var p = new Node(i, x, y);
  18339. if (!last) {
  18340. p.prev = p;
  18341. p.next = p;
  18342. } else {
  18343. p.next = last.next;
  18344. p.prev = last;
  18345. last.next.prev = p;
  18346. last.next = p;
  18347. }
  18348. return p;
  18349. }
  18350. function removeNode(p) {
  18351. p.next.prev = p.prev;
  18352. p.prev.next = p.next;
  18353. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18354. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18355. }
  18356. function Node(i, x, y) {
  18357. // vertex index in coordinates array
  18358. this.i = i; // vertex coordinates
  18359. this.x = x;
  18360. this.y = y; // previous and next vertex nodes in a polygon ring
  18361. this.prev = null;
  18362. this.next = null; // z-order curve value
  18363. this.z = null; // previous and next nodes in z-order
  18364. this.prevZ = null;
  18365. this.nextZ = null; // indicates whether this is a steiner point
  18366. this.steiner = false;
  18367. }
  18368. function signedArea(data, start, end, dim) {
  18369. var sum = 0;
  18370. for (var i = start, j = end - dim; i < end; i += dim) {
  18371. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18372. j = i;
  18373. }
  18374. return sum;
  18375. }
  18376. /**
  18377. * @author zz85 / http://www.lab4games.net/zz85/blog
  18378. */
  18379. var ShapeUtils = {
  18380. // calculate area of the contour polygon
  18381. area: function (contour) {
  18382. var n = contour.length;
  18383. var a = 0.0;
  18384. for (var p = n - 1, q = 0; q < n; p = q++) {
  18385. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18386. }
  18387. return a * 0.5;
  18388. },
  18389. isClockWise: function (pts) {
  18390. return ShapeUtils.area(pts) < 0;
  18391. },
  18392. triangulateShape: function (contour, holes) {
  18393. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18394. var holeIndices = []; // array of hole indices
  18395. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18396. removeDupEndPts(contour);
  18397. addContour(vertices, contour); //
  18398. var holeIndex = contour.length;
  18399. holes.forEach(removeDupEndPts);
  18400. for (var i = 0; i < holes.length; i++) {
  18401. holeIndices.push(holeIndex);
  18402. holeIndex += holes[i].length;
  18403. addContour(vertices, holes[i]);
  18404. } //
  18405. var triangles = Earcut.triangulate(vertices, holeIndices); //
  18406. for (var i = 0; i < triangles.length; i += 3) {
  18407. faces.push(triangles.slice(i, i + 3));
  18408. }
  18409. return faces;
  18410. }
  18411. };
  18412. exports.ShapeUtils = ShapeUtils;
  18413. function removeDupEndPts(points) {
  18414. var l = points.length;
  18415. if (l > 2 && points[l - 1].equals(points[0])) {
  18416. points.pop();
  18417. }
  18418. }
  18419. function addContour(vertices, contour) {
  18420. for (var i = 0; i < contour.length; i++) {
  18421. vertices.push(contour[i].x);
  18422. vertices.push(contour[i].y);
  18423. }
  18424. }
  18425. /**
  18426. * @author zz85 / http://www.lab4games.net/zz85/blog
  18427. *
  18428. * Creates extruded geometry from a path shape.
  18429. *
  18430. * parameters = {
  18431. *
  18432. * curveSegments: <int>, // number of points on the curves
  18433. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18434. * depth: <float>, // Depth to extrude the shape
  18435. *
  18436. * bevelEnabled: <bool>, // turn on bevel
  18437. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18438. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18439. * bevelOffset: <float>, // how far from shape outline does bevel start
  18440. * bevelSegments: <int>, // number of bevel layers
  18441. *
  18442. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18443. *
  18444. * UVGenerator: <Object> // object that provides UV generator functions
  18445. *
  18446. * }
  18447. */
  18448. // ExtrudeGeometry
  18449. function ExtrudeGeometry(shapes, options) {
  18450. Geometry.call(this);
  18451. this.type = 'ExtrudeGeometry';
  18452. this.parameters = {
  18453. shapes: shapes,
  18454. options: options
  18455. };
  18456. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  18457. this.mergeVertices();
  18458. }
  18459. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  18460. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18461. ExtrudeGeometry.prototype.toJSON = function () {
  18462. var data = Geometry.prototype.toJSON.call(this);
  18463. var shapes = this.parameters.shapes;
  18464. var options = this.parameters.options;
  18465. return toJSON(shapes, options, data);
  18466. }; // ExtrudeBufferGeometry
  18467. function ExtrudeBufferGeometry(shapes, options) {
  18468. BufferGeometry.call(this);
  18469. this.type = 'ExtrudeBufferGeometry';
  18470. this.parameters = {
  18471. shapes: shapes,
  18472. options: options
  18473. };
  18474. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18475. var scope = this;
  18476. var verticesArray = [];
  18477. var uvArray = [];
  18478. for (var i = 0, l = shapes.length; i < l; i++) {
  18479. var shape = shapes[i];
  18480. addShape(shape);
  18481. } // build geometry
  18482. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18483. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18484. this.computeVertexNormals(); // functions
  18485. function addShape(shape) {
  18486. var placeholder = []; // options
  18487. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18488. var steps = options.steps !== undefined ? options.steps : 1;
  18489. var depth = options.depth !== undefined ? options.depth : 100;
  18490. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18491. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18492. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18493. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18494. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18495. var extrudePath = options.extrudePath;
  18496. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18497. if (options.amount !== undefined) {
  18498. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18499. depth = options.amount;
  18500. } //
  18501. var extrudePts,
  18502. extrudeByPath = false;
  18503. var splineTube, binormal, normal, position2;
  18504. if (extrudePath) {
  18505. extrudePts = extrudePath.getSpacedPoints(steps);
  18506. extrudeByPath = true;
  18507. bevelEnabled = false; // bevels not supported for path extrusion
  18508. // SETUP TNB variables
  18509. // TODO1 - have a .isClosed in spline?
  18510. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18511. binormal = new Vector3();
  18512. normal = new Vector3();
  18513. position2 = new Vector3();
  18514. } // Safeguards if bevels are not enabled
  18515. if (!bevelEnabled) {
  18516. bevelSegments = 0;
  18517. bevelThickness = 0;
  18518. bevelSize = 0;
  18519. bevelOffset = 0;
  18520. } // Variables initialization
  18521. var ahole, h, hl; // looping of holes
  18522. var shapePoints = shape.extractPoints(curveSegments);
  18523. var vertices = shapePoints.shape;
  18524. var holes = shapePoints.holes;
  18525. var reverse = !ShapeUtils.isClockWise(vertices);
  18526. if (reverse) {
  18527. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18528. for (h = 0, hl = holes.length; h < hl; h++) {
  18529. ahole = holes[h];
  18530. if (ShapeUtils.isClockWise(ahole)) {
  18531. holes[h] = ahole.reverse();
  18532. }
  18533. }
  18534. }
  18535. var faces = ShapeUtils.triangulateShape(vertices, holes);
  18536. /* Vertices */
  18537. var contour = vertices; // vertices has all points but contour has only points of circumference
  18538. for (h = 0, hl = holes.length; h < hl; h++) {
  18539. ahole = holes[h];
  18540. vertices = vertices.concat(ahole);
  18541. }
  18542. function scalePt2(pt, vec, size) {
  18543. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18544. return vec.clone().multiplyScalar(size).add(pt);
  18545. }
  18546. var b,
  18547. bs,
  18548. t,
  18549. z,
  18550. vert,
  18551. vlen = vertices.length,
  18552. face,
  18553. flen = faces.length; // Find directions for point movement
  18554. function getBevelVec(inPt, inPrev, inNext) {
  18555. // computes for inPt the corresponding point inPt' on a new contour
  18556. // shifted by 1 unit (length of normalized vector) to the left
  18557. // if we walk along contour clockwise, this new contour is outside the old one
  18558. //
  18559. // inPt' is the intersection of the two lines parallel to the two
  18560. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18561. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18562. // good reading for geometry algorithms (here: line-line intersection)
  18563. // http://geomalgorithms.com/a05-_intersect-1.html
  18564. var v_prev_x = inPt.x - inPrev.x,
  18565. v_prev_y = inPt.y - inPrev.y;
  18566. var v_next_x = inNext.x - inPt.x,
  18567. v_next_y = inNext.y - inPt.y;
  18568. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18569. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18570. if (Math.abs(collinear0) > Number.EPSILON) {
  18571. // not collinear
  18572. // length of vectors for normalizing
  18573. var v_prev_len = Math.sqrt(v_prev_lensq);
  18574. var 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
  18575. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18576. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18577. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18578. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18579. var 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
  18580. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18581. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18582. // but prevent crazy spikes
  18583. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18584. if (v_trans_lensq <= 2) {
  18585. return new Vector2(v_trans_x, v_trans_y);
  18586. } else {
  18587. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18588. }
  18589. } else {
  18590. // handle special case of collinear edges
  18591. var direction_eq = false; // assumes: opposite
  18592. if (v_prev_x > Number.EPSILON) {
  18593. if (v_next_x > Number.EPSILON) {
  18594. direction_eq = true;
  18595. }
  18596. } else {
  18597. if (v_prev_x < -Number.EPSILON) {
  18598. if (v_next_x < -Number.EPSILON) {
  18599. direction_eq = true;
  18600. }
  18601. } else {
  18602. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18603. direction_eq = true;
  18604. }
  18605. }
  18606. }
  18607. if (direction_eq) {
  18608. // console.log("Warning: lines are a straight sequence");
  18609. v_trans_x = -v_prev_y;
  18610. v_trans_y = v_prev_x;
  18611. shrink_by = Math.sqrt(v_prev_lensq);
  18612. } else {
  18613. // console.log("Warning: lines are a straight spike");
  18614. v_trans_x = v_prev_x;
  18615. v_trans_y = v_prev_y;
  18616. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18617. }
  18618. }
  18619. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18620. }
  18621. var contourMovements = [];
  18622. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18623. if (j === il) j = 0;
  18624. if (k === il) k = 0; // (j)---(i)---(k)
  18625. // console.log('i,j,k', i, j , k)
  18626. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18627. }
  18628. var holesMovements = [],
  18629. oneHoleMovements,
  18630. verticesMovements = contourMovements.concat();
  18631. for (h = 0, hl = holes.length; h < hl; h++) {
  18632. ahole = holes[h];
  18633. oneHoleMovements = [];
  18634. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18635. if (j === il) j = 0;
  18636. if (k === il) k = 0; // (j)---(i)---(k)
  18637. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18638. }
  18639. holesMovements.push(oneHoleMovements);
  18640. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18641. } // Loop bevelSegments, 1 for the front, 1 for the back
  18642. for (b = 0; b < bevelSegments; b++) {
  18643. //for ( b = bevelSegments; b > 0; b -- ) {
  18644. t = b / bevelSegments;
  18645. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18646. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18647. for (i = 0, il = contour.length; i < il; i++) {
  18648. vert = scalePt2(contour[i], contourMovements[i], bs);
  18649. v(vert.x, vert.y, -z);
  18650. } // expand holes
  18651. for (h = 0, hl = holes.length; h < hl; h++) {
  18652. ahole = holes[h];
  18653. oneHoleMovements = holesMovements[h];
  18654. for (i = 0, il = ahole.length; i < il; i++) {
  18655. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18656. v(vert.x, vert.y, -z);
  18657. }
  18658. }
  18659. }
  18660. bs = bevelSize + bevelOffset; // Back facing vertices
  18661. for (i = 0; i < vlen; i++) {
  18662. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18663. if (!extrudeByPath) {
  18664. v(vert.x, vert.y, 0);
  18665. } else {
  18666. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18667. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18668. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18669. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18670. v(position2.x, position2.y, position2.z);
  18671. }
  18672. } // Add stepped vertices...
  18673. // Including front facing vertices
  18674. var s;
  18675. for (s = 1; s <= steps; s++) {
  18676. for (i = 0; i < vlen; i++) {
  18677. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18678. if (!extrudeByPath) {
  18679. v(vert.x, vert.y, depth / steps * s);
  18680. } else {
  18681. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18682. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18683. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18684. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18685. v(position2.x, position2.y, position2.z);
  18686. }
  18687. }
  18688. } // Add bevel segments planes
  18689. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18690. for (b = bevelSegments - 1; b >= 0; b--) {
  18691. t = b / bevelSegments;
  18692. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18693. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18694. for (i = 0, il = contour.length; i < il; i++) {
  18695. vert = scalePt2(contour[i], contourMovements[i], bs);
  18696. v(vert.x, vert.y, depth + z);
  18697. } // expand holes
  18698. for (h = 0, hl = holes.length; h < hl; h++) {
  18699. ahole = holes[h];
  18700. oneHoleMovements = holesMovements[h];
  18701. for (i = 0, il = ahole.length; i < il; i++) {
  18702. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18703. if (!extrudeByPath) {
  18704. v(vert.x, vert.y, depth + z);
  18705. } else {
  18706. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18707. }
  18708. }
  18709. }
  18710. }
  18711. /* Faces */
  18712. // Top and bottom faces
  18713. buildLidFaces(); // Sides faces
  18714. buildSideFaces(); ///// Internal functions
  18715. function buildLidFaces() {
  18716. var start = verticesArray.length / 3;
  18717. if (bevelEnabled) {
  18718. var layer = 0; // steps + 1
  18719. var offset = vlen * layer; // Bottom faces
  18720. for (i = 0; i < flen; i++) {
  18721. face = faces[i];
  18722. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18723. }
  18724. layer = steps + bevelSegments * 2;
  18725. offset = vlen * layer; // Top faces
  18726. for (i = 0; i < flen; i++) {
  18727. face = faces[i];
  18728. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18729. }
  18730. } else {
  18731. // Bottom faces
  18732. for (i = 0; i < flen; i++) {
  18733. face = faces[i];
  18734. f3(face[2], face[1], face[0]);
  18735. } // Top faces
  18736. for (i = 0; i < flen; i++) {
  18737. face = faces[i];
  18738. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18739. }
  18740. }
  18741. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18742. } // Create faces for the z-sides of the shape
  18743. function buildSideFaces() {
  18744. var start = verticesArray.length / 3;
  18745. var layeroffset = 0;
  18746. sidewalls(contour, layeroffset);
  18747. layeroffset += contour.length;
  18748. for (h = 0, hl = holes.length; h < hl; h++) {
  18749. ahole = holes[h];
  18750. sidewalls(ahole, layeroffset); //, true
  18751. layeroffset += ahole.length;
  18752. }
  18753. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18754. }
  18755. function sidewalls(contour, layeroffset) {
  18756. var j, k;
  18757. i = contour.length;
  18758. while (--i >= 0) {
  18759. j = i;
  18760. k = i - 1;
  18761. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18762. var s = 0,
  18763. sl = steps + bevelSegments * 2;
  18764. for (s = 0; s < sl; s++) {
  18765. var slen1 = vlen * s;
  18766. var slen2 = vlen * (s + 1);
  18767. var a = layeroffset + j + slen1,
  18768. b = layeroffset + k + slen1,
  18769. c = layeroffset + k + slen2,
  18770. d = layeroffset + j + slen2;
  18771. f4(a, b, c, d);
  18772. }
  18773. }
  18774. }
  18775. function v(x, y, z) {
  18776. placeholder.push(x);
  18777. placeholder.push(y);
  18778. placeholder.push(z);
  18779. }
  18780. function f3(a, b, c) {
  18781. addVertex(a);
  18782. addVertex(b);
  18783. addVertex(c);
  18784. var nextIndex = verticesArray.length / 3;
  18785. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18786. addUV(uvs[0]);
  18787. addUV(uvs[1]);
  18788. addUV(uvs[2]);
  18789. }
  18790. function f4(a, b, c, d) {
  18791. addVertex(a);
  18792. addVertex(b);
  18793. addVertex(d);
  18794. addVertex(b);
  18795. addVertex(c);
  18796. addVertex(d);
  18797. var nextIndex = verticesArray.length / 3;
  18798. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18799. addUV(uvs[0]);
  18800. addUV(uvs[1]);
  18801. addUV(uvs[3]);
  18802. addUV(uvs[1]);
  18803. addUV(uvs[2]);
  18804. addUV(uvs[3]);
  18805. }
  18806. function addVertex(index) {
  18807. verticesArray.push(placeholder[index * 3 + 0]);
  18808. verticesArray.push(placeholder[index * 3 + 1]);
  18809. verticesArray.push(placeholder[index * 3 + 2]);
  18810. }
  18811. function addUV(vector2) {
  18812. uvArray.push(vector2.x);
  18813. uvArray.push(vector2.y);
  18814. }
  18815. }
  18816. }
  18817. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18818. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  18819. ExtrudeBufferGeometry.prototype.toJSON = function () {
  18820. var data = BufferGeometry.prototype.toJSON.call(this);
  18821. var shapes = this.parameters.shapes;
  18822. var options = this.parameters.options;
  18823. return toJSON(shapes, options, data);
  18824. }; //
  18825. var WorldUVGenerator = {
  18826. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18827. var a_x = vertices[indexA * 3];
  18828. var a_y = vertices[indexA * 3 + 1];
  18829. var b_x = vertices[indexB * 3];
  18830. var b_y = vertices[indexB * 3 + 1];
  18831. var c_x = vertices[indexC * 3];
  18832. var c_y = vertices[indexC * 3 + 1];
  18833. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18834. },
  18835. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18836. var a_x = vertices[indexA * 3];
  18837. var a_y = vertices[indexA * 3 + 1];
  18838. var a_z = vertices[indexA * 3 + 2];
  18839. var b_x = vertices[indexB * 3];
  18840. var b_y = vertices[indexB * 3 + 1];
  18841. var b_z = vertices[indexB * 3 + 2];
  18842. var c_x = vertices[indexC * 3];
  18843. var c_y = vertices[indexC * 3 + 1];
  18844. var c_z = vertices[indexC * 3 + 2];
  18845. var d_x = vertices[indexD * 3];
  18846. var d_y = vertices[indexD * 3 + 1];
  18847. var d_z = vertices[indexD * 3 + 2];
  18848. if (Math.abs(a_y - b_y) < 0.01) {
  18849. 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)];
  18850. } else {
  18851. 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)];
  18852. }
  18853. }
  18854. };
  18855. function toJSON(shapes, options, data) {
  18856. //
  18857. data.shapes = [];
  18858. if (Array.isArray(shapes)) {
  18859. for (var i = 0, l = shapes.length; i < l; i++) {
  18860. var shape = shapes[i];
  18861. data.shapes.push(shape.uuid);
  18862. }
  18863. } else {
  18864. data.shapes.push(shapes.uuid);
  18865. } //
  18866. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18867. return data;
  18868. }
  18869. /**
  18870. * @author zz85 / http://www.lab4games.net/zz85/blog
  18871. * @author alteredq / http://alteredqualia.com/
  18872. *
  18873. * Text = 3D Text
  18874. *
  18875. * parameters = {
  18876. * font: <THREE.Font>, // font
  18877. *
  18878. * size: <float>, // size of the text
  18879. * height: <float>, // thickness to extrude text
  18880. * curveSegments: <int>, // number of points on the curves
  18881. *
  18882. * bevelEnabled: <bool>, // turn on bevel
  18883. * bevelThickness: <float>, // how deep into text bevel goes
  18884. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18885. * bevelOffset: <float> // how far from text outline does bevel start
  18886. * }
  18887. */
  18888. // TextGeometry
  18889. function TextGeometry(text, parameters) {
  18890. Geometry.call(this);
  18891. this.type = 'TextGeometry';
  18892. this.parameters = {
  18893. text: text,
  18894. parameters: parameters
  18895. };
  18896. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  18897. this.mergeVertices();
  18898. }
  18899. TextGeometry.prototype = Object.create(Geometry.prototype);
  18900. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  18901. function TextBufferGeometry(text, parameters) {
  18902. parameters = parameters || {};
  18903. var font = parameters.font;
  18904. if (!(font && font.isFont)) {
  18905. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18906. return new Geometry();
  18907. }
  18908. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18909. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18910. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18911. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18912. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18913. ExtrudeBufferGeometry.call(this, shapes, parameters);
  18914. this.type = 'TextBufferGeometry';
  18915. }
  18916. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  18917. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  18918. /**
  18919. * @author mrdoob / http://mrdoob.com/
  18920. * @author benaadams / https://twitter.com/ben_a_adams
  18921. * @author Mugen87 / https://github.com/Mugen87
  18922. */
  18923. // SphereGeometry
  18924. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18925. Geometry.call(this);
  18926. this.type = 'SphereGeometry';
  18927. this.parameters = {
  18928. radius: radius,
  18929. widthSegments: widthSegments,
  18930. heightSegments: heightSegments,
  18931. phiStart: phiStart,
  18932. phiLength: phiLength,
  18933. thetaStart: thetaStart,
  18934. thetaLength: thetaLength
  18935. };
  18936. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  18937. this.mergeVertices();
  18938. }
  18939. SphereGeometry.prototype = Object.create(Geometry.prototype);
  18940. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  18941. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18942. BufferGeometry.call(this);
  18943. this.type = 'SphereBufferGeometry';
  18944. this.parameters = {
  18945. radius: radius,
  18946. widthSegments: widthSegments,
  18947. heightSegments: heightSegments,
  18948. phiStart: phiStart,
  18949. phiLength: phiLength,
  18950. thetaStart: thetaStart,
  18951. thetaLength: thetaLength
  18952. };
  18953. radius = radius || 1;
  18954. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  18955. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  18956. phiStart = phiStart !== undefined ? phiStart : 0;
  18957. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18958. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18959. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18960. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18961. var ix, iy;
  18962. var index = 0;
  18963. var grid = [];
  18964. var vertex = new Vector3();
  18965. var normal = new Vector3(); // buffers
  18966. var indices = [];
  18967. var vertices = [];
  18968. var normals = [];
  18969. var uvs = []; // generate vertices, normals and uvs
  18970. for (iy = 0; iy <= heightSegments; iy++) {
  18971. var verticesRow = [];
  18972. var v = iy / heightSegments; // special case for the poles
  18973. var uOffset = 0;
  18974. if (iy == 0 && thetaStart == 0) {
  18975. uOffset = 0.5 / widthSegments;
  18976. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18977. uOffset = -0.5 / widthSegments;
  18978. }
  18979. for (ix = 0; ix <= widthSegments; ix++) {
  18980. var u = ix / widthSegments; // vertex
  18981. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18982. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18983. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18984. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18985. normal.copy(vertex).normalize();
  18986. normals.push(normal.x, normal.y, normal.z); // uv
  18987. uvs.push(u + uOffset, 1 - v);
  18988. verticesRow.push(index++);
  18989. }
  18990. grid.push(verticesRow);
  18991. } // indices
  18992. for (iy = 0; iy < heightSegments; iy++) {
  18993. for (ix = 0; ix < widthSegments; ix++) {
  18994. var a = grid[iy][ix + 1];
  18995. var b = grid[iy][ix];
  18996. var c = grid[iy + 1][ix];
  18997. var d = grid[iy + 1][ix + 1];
  18998. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18999. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19000. }
  19001. } // build geometry
  19002. this.setIndex(indices);
  19003. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19004. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19005. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19006. }
  19007. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19008. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19009. /**
  19010. * @author Kaleb Murphy
  19011. * @author Mugen87 / https://github.com/Mugen87
  19012. */
  19013. // RingGeometry
  19014. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19015. Geometry.call(this);
  19016. this.type = 'RingGeometry';
  19017. this.parameters = {
  19018. innerRadius: innerRadius,
  19019. outerRadius: outerRadius,
  19020. thetaSegments: thetaSegments,
  19021. phiSegments: phiSegments,
  19022. thetaStart: thetaStart,
  19023. thetaLength: thetaLength
  19024. };
  19025. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19026. this.mergeVertices();
  19027. }
  19028. RingGeometry.prototype = Object.create(Geometry.prototype);
  19029. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19030. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19031. BufferGeometry.call(this);
  19032. this.type = 'RingBufferGeometry';
  19033. this.parameters = {
  19034. innerRadius: innerRadius,
  19035. outerRadius: outerRadius,
  19036. thetaSegments: thetaSegments,
  19037. phiSegments: phiSegments,
  19038. thetaStart: thetaStart,
  19039. thetaLength: thetaLength
  19040. };
  19041. innerRadius = innerRadius || 0.5;
  19042. outerRadius = outerRadius || 1;
  19043. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19044. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19045. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19046. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19047. var indices = [];
  19048. var vertices = [];
  19049. var normals = [];
  19050. var uvs = []; // some helper variables
  19051. var segment;
  19052. var radius = innerRadius;
  19053. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19054. var vertex = new Vector3();
  19055. var uv = new Vector2();
  19056. var j, i; // generate vertices, normals and uvs
  19057. for (j = 0; j <= phiSegments; j++) {
  19058. for (i = 0; i <= thetaSegments; i++) {
  19059. // values are generate from the inside of the ring to the outside
  19060. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19061. vertex.x = radius * Math.cos(segment);
  19062. vertex.y = radius * Math.sin(segment);
  19063. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19064. normals.push(0, 0, 1); // uv
  19065. uv.x = (vertex.x / outerRadius + 1) / 2;
  19066. uv.y = (vertex.y / outerRadius + 1) / 2;
  19067. uvs.push(uv.x, uv.y);
  19068. } // increase the radius for next row of vertices
  19069. radius += radiusStep;
  19070. } // indices
  19071. for (j = 0; j < phiSegments; j++) {
  19072. var thetaSegmentLevel = j * (thetaSegments + 1);
  19073. for (i = 0; i < thetaSegments; i++) {
  19074. segment = i + thetaSegmentLevel;
  19075. var a = segment;
  19076. var b = segment + thetaSegments + 1;
  19077. var c = segment + thetaSegments + 2;
  19078. var d = segment + 1; // faces
  19079. indices.push(a, b, d);
  19080. indices.push(b, c, d);
  19081. }
  19082. } // build geometry
  19083. this.setIndex(indices);
  19084. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19085. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19086. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19087. }
  19088. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19089. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19090. /**
  19091. * @author zz85 / https://github.com/zz85
  19092. * @author bhouston / http://clara.io
  19093. * @author Mugen87 / https://github.com/Mugen87
  19094. */
  19095. // LatheGeometry
  19096. function LatheGeometry(points, segments, phiStart, phiLength) {
  19097. Geometry.call(this);
  19098. this.type = 'LatheGeometry';
  19099. this.parameters = {
  19100. points: points,
  19101. segments: segments,
  19102. phiStart: phiStart,
  19103. phiLength: phiLength
  19104. };
  19105. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19106. this.mergeVertices();
  19107. }
  19108. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19109. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19110. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  19111. BufferGeometry.call(this);
  19112. this.type = 'LatheBufferGeometry';
  19113. this.parameters = {
  19114. points: points,
  19115. segments: segments,
  19116. phiStart: phiStart,
  19117. phiLength: phiLength
  19118. };
  19119. segments = Math.floor(segments) || 12;
  19120. phiStart = phiStart || 0;
  19121. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  19122. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  19123. var indices = [];
  19124. var vertices = [];
  19125. var uvs = []; // helper variables
  19126. var base;
  19127. var inverseSegments = 1.0 / segments;
  19128. var vertex = new Vector3();
  19129. var uv = new Vector2();
  19130. var i, j; // generate vertices and uvs
  19131. for (i = 0; i <= segments; i++) {
  19132. var phi = phiStart + i * inverseSegments * phiLength;
  19133. var sin = Math.sin(phi);
  19134. var cos = Math.cos(phi);
  19135. for (j = 0; j <= points.length - 1; j++) {
  19136. // vertex
  19137. vertex.x = points[j].x * sin;
  19138. vertex.y = points[j].y;
  19139. vertex.z = points[j].x * cos;
  19140. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19141. uv.x = i / segments;
  19142. uv.y = j / (points.length - 1);
  19143. uvs.push(uv.x, uv.y);
  19144. }
  19145. } // indices
  19146. for (i = 0; i < segments; i++) {
  19147. for (j = 0; j < points.length - 1; j++) {
  19148. base = j + i * points.length;
  19149. var a = base;
  19150. var b = base + points.length;
  19151. var c = base + points.length + 1;
  19152. var d = base + 1; // faces
  19153. indices.push(a, b, d);
  19154. indices.push(b, c, d);
  19155. }
  19156. } // build geometry
  19157. this.setIndex(indices);
  19158. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19159. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19160. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19161. // because the corresponding vertices are identical (but still have different UVs).
  19162. if (phiLength === Math.PI * 2) {
  19163. var normals = this.attributes.normal.array;
  19164. var n1 = new Vector3();
  19165. var n2 = new Vector3();
  19166. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  19167. base = segments * points.length * 3;
  19168. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  19169. // select the normal of the vertex in the first line
  19170. n1.x = normals[j + 0];
  19171. n1.y = normals[j + 1];
  19172. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19173. n2.x = normals[base + j + 0];
  19174. n2.y = normals[base + j + 1];
  19175. n2.z = normals[base + j + 2]; // average normals
  19176. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19177. normals[j + 0] = normals[base + j + 0] = n.x;
  19178. normals[j + 1] = normals[base + j + 1] = n.y;
  19179. normals[j + 2] = normals[base + j + 2] = n.z;
  19180. }
  19181. }
  19182. }
  19183. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19184. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  19185. /**
  19186. * @author jonobr1 / http://jonobr1.com
  19187. * @author Mugen87 / https://github.com/Mugen87
  19188. */
  19189. // ShapeGeometry
  19190. function ShapeGeometry(shapes, curveSegments) {
  19191. Geometry.call(this);
  19192. this.type = 'ShapeGeometry';
  19193. if (typeof curveSegments === 'object') {
  19194. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  19195. curveSegments = curveSegments.curveSegments;
  19196. }
  19197. this.parameters = {
  19198. shapes: shapes,
  19199. curveSegments: curveSegments
  19200. };
  19201. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  19202. this.mergeVertices();
  19203. }
  19204. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  19205. ShapeGeometry.prototype.constructor = ShapeGeometry;
  19206. ShapeGeometry.prototype.toJSON = function () {
  19207. var data = Geometry.prototype.toJSON.call(this);
  19208. var shapes = this.parameters.shapes;
  19209. return toJSON$1(shapes, data);
  19210. }; // ShapeBufferGeometry
  19211. function ShapeBufferGeometry(shapes, curveSegments) {
  19212. BufferGeometry.call(this);
  19213. this.type = 'ShapeBufferGeometry';
  19214. this.parameters = {
  19215. shapes: shapes,
  19216. curveSegments: curveSegments
  19217. };
  19218. curveSegments = curveSegments || 12; // buffers
  19219. var indices = [];
  19220. var vertices = [];
  19221. var normals = [];
  19222. var uvs = []; // helper variables
  19223. var groupStart = 0;
  19224. var groupCount = 0; // allow single and array values for "shapes" parameter
  19225. if (Array.isArray(shapes) === false) {
  19226. addShape(shapes);
  19227. } else {
  19228. for (var i = 0; i < shapes.length; i++) {
  19229. addShape(shapes[i]);
  19230. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19231. groupStart += groupCount;
  19232. groupCount = 0;
  19233. }
  19234. } // build geometry
  19235. this.setIndex(indices);
  19236. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19237. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19238. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19239. function addShape(shape) {
  19240. var i, l, shapeHole;
  19241. var indexOffset = vertices.length / 3;
  19242. var points = shape.extractPoints(curveSegments);
  19243. var shapeVertices = points.shape;
  19244. var shapeHoles = points.holes; // check direction of vertices
  19245. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19246. shapeVertices = shapeVertices.reverse();
  19247. }
  19248. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19249. shapeHole = shapeHoles[i];
  19250. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19251. shapeHoles[i] = shapeHole.reverse();
  19252. }
  19253. }
  19254. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19255. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19256. shapeHole = shapeHoles[i];
  19257. shapeVertices = shapeVertices.concat(shapeHole);
  19258. } // vertices, normals, uvs
  19259. for (i = 0, l = shapeVertices.length; i < l; i++) {
  19260. var vertex = shapeVertices[i];
  19261. vertices.push(vertex.x, vertex.y, 0);
  19262. normals.push(0, 0, 1);
  19263. uvs.push(vertex.x, vertex.y); // world uvs
  19264. } // incides
  19265. for (i = 0, l = faces.length; i < l; i++) {
  19266. var face = faces[i];
  19267. var a = face[0] + indexOffset;
  19268. var b = face[1] + indexOffset;
  19269. var c = face[2] + indexOffset;
  19270. indices.push(a, b, c);
  19271. groupCount += 3;
  19272. }
  19273. }
  19274. }
  19275. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19276. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  19277. ShapeBufferGeometry.prototype.toJSON = function () {
  19278. var data = BufferGeometry.prototype.toJSON.call(this);
  19279. var shapes = this.parameters.shapes;
  19280. return toJSON$1(shapes, data);
  19281. }; //
  19282. function toJSON$1(shapes, data) {
  19283. data.shapes = [];
  19284. if (Array.isArray(shapes)) {
  19285. for (var i = 0, l = shapes.length; i < l; i++) {
  19286. var shape = shapes[i];
  19287. data.shapes.push(shape.uuid);
  19288. }
  19289. } else {
  19290. data.shapes.push(shapes.uuid);
  19291. }
  19292. return data;
  19293. }
  19294. /**
  19295. * @author WestLangley / http://github.com/WestLangley
  19296. * @author Mugen87 / https://github.com/Mugen87
  19297. */
  19298. function EdgesGeometry(geometry, thresholdAngle) {
  19299. BufferGeometry.call(this);
  19300. this.type = 'EdgesGeometry';
  19301. this.parameters = {
  19302. thresholdAngle: thresholdAngle
  19303. };
  19304. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  19305. var vertices = []; // helper variables
  19306. var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  19307. var edge = [0, 0],
  19308. edges = {},
  19309. edge1,
  19310. edge2;
  19311. var key,
  19312. keys = ['a', 'b', 'c']; // prepare source geometry
  19313. var geometry2;
  19314. if (geometry.isBufferGeometry) {
  19315. geometry2 = new Geometry();
  19316. geometry2.fromBufferGeometry(geometry);
  19317. } else {
  19318. geometry2 = geometry.clone();
  19319. }
  19320. geometry2.mergeVertices();
  19321. geometry2.computeFaceNormals();
  19322. var sourceVertices = geometry2.vertices;
  19323. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  19324. for (var i = 0, l = faces.length; i < l; i++) {
  19325. var face = faces[i];
  19326. for (var j = 0; j < 3; j++) {
  19327. edge1 = face[keys[j]];
  19328. edge2 = face[keys[(j + 1) % 3]];
  19329. edge[0] = Math.min(edge1, edge2);
  19330. edge[1] = Math.max(edge1, edge2);
  19331. key = edge[0] + ',' + edge[1];
  19332. if (edges[key] === undefined) {
  19333. edges[key] = {
  19334. index1: edge[0],
  19335. index2: edge[1],
  19336. face1: i,
  19337. face2: undefined
  19338. };
  19339. } else {
  19340. edges[key].face2 = i;
  19341. }
  19342. }
  19343. } // generate vertices
  19344. for (key in edges) {
  19345. var e = edges[key]; // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  19346. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  19347. var vertex = sourceVertices[e.index1];
  19348. vertices.push(vertex.x, vertex.y, vertex.z);
  19349. vertex = sourceVertices[e.index2];
  19350. vertices.push(vertex.x, vertex.y, vertex.z);
  19351. }
  19352. } // build geometry
  19353. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19354. }
  19355. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  19356. EdgesGeometry.prototype.constructor = EdgesGeometry;
  19357. /**
  19358. * @author mrdoob / http://mrdoob.com/
  19359. * @author Mugen87 / https://github.com/Mugen87
  19360. */
  19361. // CylinderGeometry
  19362. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19363. Geometry.call(this);
  19364. this.type = 'CylinderGeometry';
  19365. this.parameters = {
  19366. radiusTop: radiusTop,
  19367. radiusBottom: radiusBottom,
  19368. height: height,
  19369. radialSegments: radialSegments,
  19370. heightSegments: heightSegments,
  19371. openEnded: openEnded,
  19372. thetaStart: thetaStart,
  19373. thetaLength: thetaLength
  19374. };
  19375. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  19376. this.mergeVertices();
  19377. }
  19378. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  19379. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  19380. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19381. BufferGeometry.call(this);
  19382. this.type = 'CylinderBufferGeometry';
  19383. this.parameters = {
  19384. radiusTop: radiusTop,
  19385. radiusBottom: radiusBottom,
  19386. height: height,
  19387. radialSegments: radialSegments,
  19388. heightSegments: heightSegments,
  19389. openEnded: openEnded,
  19390. thetaStart: thetaStart,
  19391. thetaLength: thetaLength
  19392. };
  19393. var scope = this;
  19394. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  19395. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  19396. height = height || 1;
  19397. radialSegments = Math.floor(radialSegments) || 8;
  19398. heightSegments = Math.floor(heightSegments) || 1;
  19399. openEnded = openEnded !== undefined ? openEnded : false;
  19400. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19401. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19402. var indices = [];
  19403. var vertices = [];
  19404. var normals = [];
  19405. var uvs = []; // helper variables
  19406. var index = 0;
  19407. var indexArray = [];
  19408. var halfHeight = height / 2;
  19409. var groupStart = 0; // generate geometry
  19410. generateTorso();
  19411. if (openEnded === false) {
  19412. if (radiusTop > 0) generateCap(true);
  19413. if (radiusBottom > 0) generateCap(false);
  19414. } // build geometry
  19415. this.setIndex(indices);
  19416. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19417. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19418. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19419. function generateTorso() {
  19420. var x, y;
  19421. var normal = new Vector3();
  19422. var vertex = new Vector3();
  19423. var groupCount = 0; // this will be used to calculate the normal
  19424. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19425. for (y = 0; y <= heightSegments; y++) {
  19426. var indexRow = [];
  19427. var v = y / heightSegments; // calculate the radius of the current row
  19428. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  19429. for (x = 0; x <= radialSegments; x++) {
  19430. var u = x / radialSegments;
  19431. var theta = u * thetaLength + thetaStart;
  19432. var sinTheta = Math.sin(theta);
  19433. var cosTheta = Math.cos(theta); // vertex
  19434. vertex.x = radius * sinTheta;
  19435. vertex.y = -v * height + halfHeight;
  19436. vertex.z = radius * cosTheta;
  19437. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19438. normal.set(sinTheta, slope, cosTheta).normalize();
  19439. normals.push(normal.x, normal.y, normal.z); // uv
  19440. uvs.push(u, 1 - v); // save index of vertex in respective row
  19441. indexRow.push(index++);
  19442. } // now save vertices of the row in our index array
  19443. indexArray.push(indexRow);
  19444. } // generate indices
  19445. for (x = 0; x < radialSegments; x++) {
  19446. for (y = 0; y < heightSegments; y++) {
  19447. // we use the index array to access the correct indices
  19448. var a = indexArray[y][x];
  19449. var b = indexArray[y + 1][x];
  19450. var c = indexArray[y + 1][x + 1];
  19451. var d = indexArray[y][x + 1]; // faces
  19452. indices.push(a, b, d);
  19453. indices.push(b, c, d); // update group counter
  19454. groupCount += 6;
  19455. }
  19456. } // add a group to the geometry. this will ensure multi material support
  19457. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19458. groupStart += groupCount;
  19459. }
  19460. function generateCap(top) {
  19461. var x, centerIndexStart, centerIndexEnd;
  19462. var uv = new Vector2();
  19463. var vertex = new Vector3();
  19464. var groupCount = 0;
  19465. var radius = top === true ? radiusTop : radiusBottom;
  19466. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  19467. centerIndexStart = index; // first we generate the center vertex data of the cap.
  19468. // because the geometry needs one set of uvs per face,
  19469. // we must generate a center vertex per face/segment
  19470. for (x = 1; x <= radialSegments; x++) {
  19471. // vertex
  19472. vertices.push(0, halfHeight * sign, 0); // normal
  19473. normals.push(0, sign, 0); // uv
  19474. uvs.push(0.5, 0.5); // increase index
  19475. index++;
  19476. } // save the index of the last center vertex
  19477. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19478. for (x = 0; x <= radialSegments; x++) {
  19479. var u = x / radialSegments;
  19480. var theta = u * thetaLength + thetaStart;
  19481. var cosTheta = Math.cos(theta);
  19482. var sinTheta = Math.sin(theta); // vertex
  19483. vertex.x = radius * sinTheta;
  19484. vertex.y = halfHeight * sign;
  19485. vertex.z = radius * cosTheta;
  19486. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19487. normals.push(0, sign, 0); // uv
  19488. uv.x = cosTheta * 0.5 + 0.5;
  19489. uv.y = sinTheta * 0.5 * sign + 0.5;
  19490. uvs.push(uv.x, uv.y); // increase index
  19491. index++;
  19492. } // generate indices
  19493. for (x = 0; x < radialSegments; x++) {
  19494. var c = centerIndexStart + x;
  19495. var i = centerIndexEnd + x;
  19496. if (top === true) {
  19497. // face top
  19498. indices.push(i, i + 1, c);
  19499. } else {
  19500. // face bottom
  19501. indices.push(i + 1, i, c);
  19502. }
  19503. groupCount += 3;
  19504. } // add a group to the geometry. this will ensure multi material support
  19505. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19506. groupStart += groupCount;
  19507. }
  19508. }
  19509. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19510. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  19511. /**
  19512. * @author abelnation / http://github.com/abelnation
  19513. */
  19514. // ConeGeometry
  19515. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19516. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19517. this.type = 'ConeGeometry';
  19518. this.parameters = {
  19519. radius: radius,
  19520. height: height,
  19521. radialSegments: radialSegments,
  19522. heightSegments: heightSegments,
  19523. openEnded: openEnded,
  19524. thetaStart: thetaStart,
  19525. thetaLength: thetaLength
  19526. };
  19527. }
  19528. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  19529. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  19530. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19531. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19532. this.type = 'ConeBufferGeometry';
  19533. this.parameters = {
  19534. radius: radius,
  19535. height: height,
  19536. radialSegments: radialSegments,
  19537. heightSegments: heightSegments,
  19538. openEnded: openEnded,
  19539. thetaStart: thetaStart,
  19540. thetaLength: thetaLength
  19541. };
  19542. }
  19543. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  19544. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  19545. /**
  19546. * @author benaadams / https://twitter.com/ben_a_adams
  19547. * @author Mugen87 / https://github.com/Mugen87
  19548. * @author hughes
  19549. */
  19550. // CircleGeometry
  19551. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  19552. Geometry.call(this);
  19553. this.type = 'CircleGeometry';
  19554. this.parameters = {
  19555. radius: radius,
  19556. segments: segments,
  19557. thetaStart: thetaStart,
  19558. thetaLength: thetaLength
  19559. };
  19560. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  19561. this.mergeVertices();
  19562. }
  19563. CircleGeometry.prototype = Object.create(Geometry.prototype);
  19564. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  19565. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  19566. BufferGeometry.call(this);
  19567. this.type = 'CircleBufferGeometry';
  19568. this.parameters = {
  19569. radius: radius,
  19570. segments: segments,
  19571. thetaStart: thetaStart,
  19572. thetaLength: thetaLength
  19573. };
  19574. radius = radius || 1;
  19575. segments = segments !== undefined ? Math.max(3, segments) : 8;
  19576. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19577. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19578. var indices = [];
  19579. var vertices = [];
  19580. var normals = [];
  19581. var uvs = []; // helper variables
  19582. var i, s;
  19583. var vertex = new Vector3();
  19584. var uv = new Vector2(); // center point
  19585. vertices.push(0, 0, 0);
  19586. normals.push(0, 0, 1);
  19587. uvs.push(0.5, 0.5);
  19588. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  19589. var segment = thetaStart + s / segments * thetaLength; // vertex
  19590. vertex.x = radius * Math.cos(segment);
  19591. vertex.y = radius * Math.sin(segment);
  19592. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19593. normals.push(0, 0, 1); // uvs
  19594. uv.x = (vertices[i] / radius + 1) / 2;
  19595. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19596. uvs.push(uv.x, uv.y);
  19597. } // indices
  19598. for (i = 1; i <= segments; i++) {
  19599. indices.push(i, i + 1, 0);
  19600. } // build geometry
  19601. this.setIndex(indices);
  19602. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19603. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19604. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19605. }
  19606. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19607. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  19608. var Geometries =
  19609. /*#__PURE__*/
  19610. Object.freeze({
  19611. __proto__: null,
  19612. WireframeGeometry: WireframeGeometry,
  19613. ParametricGeometry: ParametricGeometry,
  19614. ParametricBufferGeometry: ParametricBufferGeometry,
  19615. TetrahedronGeometry: TetrahedronGeometry,
  19616. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19617. OctahedronGeometry: OctahedronGeometry,
  19618. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19619. IcosahedronGeometry: IcosahedronGeometry,
  19620. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19621. DodecahedronGeometry: DodecahedronGeometry,
  19622. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19623. PolyhedronGeometry: PolyhedronGeometry,
  19624. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19625. TubeGeometry: TubeGeometry,
  19626. TubeBufferGeometry: TubeBufferGeometry,
  19627. TorusKnotGeometry: TorusKnotGeometry,
  19628. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19629. TorusGeometry: TorusGeometry,
  19630. TorusBufferGeometry: TorusBufferGeometry,
  19631. TextGeometry: TextGeometry,
  19632. TextBufferGeometry: TextBufferGeometry,
  19633. SphereGeometry: SphereGeometry,
  19634. SphereBufferGeometry: SphereBufferGeometry,
  19635. RingGeometry: RingGeometry,
  19636. RingBufferGeometry: RingBufferGeometry,
  19637. PlaneGeometry: PlaneGeometry,
  19638. PlaneBufferGeometry: PlaneBufferGeometry,
  19639. LatheGeometry: LatheGeometry,
  19640. LatheBufferGeometry: LatheBufferGeometry,
  19641. ShapeGeometry: ShapeGeometry,
  19642. ShapeBufferGeometry: ShapeBufferGeometry,
  19643. ExtrudeGeometry: ExtrudeGeometry,
  19644. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19645. EdgesGeometry: EdgesGeometry,
  19646. ConeGeometry: ConeGeometry,
  19647. ConeBufferGeometry: ConeBufferGeometry,
  19648. CylinderGeometry: CylinderGeometry,
  19649. CylinderBufferGeometry: CylinderBufferGeometry,
  19650. CircleGeometry: CircleGeometry,
  19651. CircleBufferGeometry: CircleBufferGeometry,
  19652. BoxGeometry: BoxGeometry,
  19653. BoxBufferGeometry: BoxBufferGeometry
  19654. });
  19655. /**
  19656. * @author mrdoob / http://mrdoob.com/
  19657. *
  19658. * parameters = {
  19659. * color: <THREE.Color>
  19660. * }
  19661. */
  19662. function ShadowMaterial(parameters) {
  19663. Material.call(this);
  19664. this.type = 'ShadowMaterial';
  19665. this.color = new Color(0x000000);
  19666. this.transparent = true;
  19667. this.setValues(parameters);
  19668. }
  19669. ShadowMaterial.prototype = Object.create(Material.prototype);
  19670. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19671. ShadowMaterial.prototype.isShadowMaterial = true;
  19672. ShadowMaterial.prototype.copy = function (source) {
  19673. Material.prototype.copy.call(this, source);
  19674. this.color.copy(source.color);
  19675. return this;
  19676. };
  19677. /**
  19678. * @author mrdoob / http://mrdoob.com/
  19679. */
  19680. function RawShaderMaterial(parameters) {
  19681. ShaderMaterial.call(this, parameters);
  19682. this.type = 'RawShaderMaterial';
  19683. }
  19684. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  19685. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19686. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19687. /**
  19688. * @author WestLangley / http://github.com/WestLangley
  19689. *
  19690. * parameters = {
  19691. * color: <hex>,
  19692. * roughness: <float>,
  19693. * metalness: <float>,
  19694. * opacity: <float>,
  19695. *
  19696. * map: new THREE.Texture( <Image> ),
  19697. *
  19698. * lightMap: new THREE.Texture( <Image> ),
  19699. * lightMapIntensity: <float>
  19700. *
  19701. * aoMap: new THREE.Texture( <Image> ),
  19702. * aoMapIntensity: <float>
  19703. *
  19704. * emissive: <hex>,
  19705. * emissiveIntensity: <float>
  19706. * emissiveMap: new THREE.Texture( <Image> ),
  19707. *
  19708. * bumpMap: new THREE.Texture( <Image> ),
  19709. * bumpScale: <float>,
  19710. *
  19711. * normalMap: new THREE.Texture( <Image> ),
  19712. * normalMapType: THREE.TangentSpaceNormalMap,
  19713. * normalScale: <Vector2>,
  19714. *
  19715. * displacementMap: new THREE.Texture( <Image> ),
  19716. * displacementScale: <float>,
  19717. * displacementBias: <float>,
  19718. *
  19719. * roughnessMap: new THREE.Texture( <Image> ),
  19720. *
  19721. * metalnessMap: new THREE.Texture( <Image> ),
  19722. *
  19723. * alphaMap: new THREE.Texture( <Image> ),
  19724. *
  19725. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19726. * envMapIntensity: <float>
  19727. *
  19728. * refractionRatio: <float>,
  19729. *
  19730. * wireframe: <boolean>,
  19731. * wireframeLinewidth: <float>,
  19732. *
  19733. * skinning: <bool>,
  19734. * morphTargets: <bool>,
  19735. * morphNormals: <bool>
  19736. * }
  19737. */
  19738. function MeshStandardMaterial(parameters) {
  19739. Material.call(this);
  19740. this.defines = {
  19741. 'STANDARD': ''
  19742. };
  19743. this.type = 'MeshStandardMaterial';
  19744. this.color = new Color(0xffffff); // diffuse
  19745. this.roughness = 1.0;
  19746. this.metalness = 0.0;
  19747. this.map = null;
  19748. this.lightMap = null;
  19749. this.lightMapIntensity = 1.0;
  19750. this.aoMap = null;
  19751. this.aoMapIntensity = 1.0;
  19752. this.emissive = new Color(0x000000);
  19753. this.emissiveIntensity = 1.0;
  19754. this.emissiveMap = null;
  19755. this.bumpMap = null;
  19756. this.bumpScale = 1;
  19757. this.normalMap = null;
  19758. this.normalMapType = TangentSpaceNormalMap;
  19759. this.normalScale = new Vector2(1, 1);
  19760. this.displacementMap = null;
  19761. this.displacementScale = 1;
  19762. this.displacementBias = 0;
  19763. this.roughnessMap = null;
  19764. this.metalnessMap = null;
  19765. this.alphaMap = null;
  19766. this.envMap = null;
  19767. this.envMapIntensity = 1.0;
  19768. this.refractionRatio = 0.98;
  19769. this.wireframe = false;
  19770. this.wireframeLinewidth = 1;
  19771. this.wireframeLinecap = 'round';
  19772. this.wireframeLinejoin = 'round';
  19773. this.skinning = false;
  19774. this.morphTargets = false;
  19775. this.morphNormals = false;
  19776. this.vertexTangents = false;
  19777. this.setValues(parameters);
  19778. }
  19779. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  19780. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19781. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19782. MeshStandardMaterial.prototype.copy = function (source) {
  19783. Material.prototype.copy.call(this, source);
  19784. this.defines = {
  19785. 'STANDARD': ''
  19786. };
  19787. this.color.copy(source.color);
  19788. this.roughness = source.roughness;
  19789. this.metalness = source.metalness;
  19790. this.map = source.map;
  19791. this.lightMap = source.lightMap;
  19792. this.lightMapIntensity = source.lightMapIntensity;
  19793. this.aoMap = source.aoMap;
  19794. this.aoMapIntensity = source.aoMapIntensity;
  19795. this.emissive.copy(source.emissive);
  19796. this.emissiveMap = source.emissiveMap;
  19797. this.emissiveIntensity = source.emissiveIntensity;
  19798. this.bumpMap = source.bumpMap;
  19799. this.bumpScale = source.bumpScale;
  19800. this.normalMap = source.normalMap;
  19801. this.normalMapType = source.normalMapType;
  19802. this.normalScale.copy(source.normalScale);
  19803. this.displacementMap = source.displacementMap;
  19804. this.displacementScale = source.displacementScale;
  19805. this.displacementBias = source.displacementBias;
  19806. this.roughnessMap = source.roughnessMap;
  19807. this.metalnessMap = source.metalnessMap;
  19808. this.alphaMap = source.alphaMap;
  19809. this.envMap = source.envMap;
  19810. this.envMapIntensity = source.envMapIntensity;
  19811. this.refractionRatio = source.refractionRatio;
  19812. this.wireframe = source.wireframe;
  19813. this.wireframeLinewidth = source.wireframeLinewidth;
  19814. this.wireframeLinecap = source.wireframeLinecap;
  19815. this.wireframeLinejoin = source.wireframeLinejoin;
  19816. this.skinning = source.skinning;
  19817. this.morphTargets = source.morphTargets;
  19818. this.morphNormals = source.morphNormals;
  19819. this.vertexTangents = source.vertexTangents;
  19820. return this;
  19821. };
  19822. /**
  19823. * @author WestLangley / http://github.com/WestLangley
  19824. *
  19825. * parameters = {
  19826. * clearcoat: <float>,
  19827. * clearcoatMap: new THREE.Texture( <Image> ),
  19828. * clearcoatRoughness: <float>,
  19829. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19830. * clearcoatNormalScale: <Vector2>,
  19831. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19832. *
  19833. * reflectivity: <float>,
  19834. *
  19835. * sheen: <Color>,
  19836. *
  19837. * transparency: <float>
  19838. * }
  19839. */
  19840. function MeshPhysicalMaterial(parameters) {
  19841. MeshStandardMaterial.call(this);
  19842. this.defines = {
  19843. 'STANDARD': '',
  19844. 'PHYSICAL': ''
  19845. };
  19846. this.type = 'MeshPhysicalMaterial';
  19847. this.clearcoat = 0.0;
  19848. this.clearcoatMap = null;
  19849. this.clearcoatRoughness = 0.0;
  19850. this.clearcoatRoughnessMap = null;
  19851. this.clearcoatNormalScale = new Vector2(1, 1);
  19852. this.clearcoatNormalMap = null;
  19853. this.reflectivity = 0.5; // maps to F0 = 0.04
  19854. this.sheen = null; // null will disable sheen bsdf
  19855. this.transparency = 0.0;
  19856. this.setValues(parameters);
  19857. }
  19858. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  19859. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  19860. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19861. MeshPhysicalMaterial.prototype.copy = function (source) {
  19862. MeshStandardMaterial.prototype.copy.call(this, source);
  19863. this.defines = {
  19864. 'STANDARD': '',
  19865. 'PHYSICAL': ''
  19866. };
  19867. this.clearcoat = source.clearcoat;
  19868. this.clearcoatMap = source.clearcoatMap;
  19869. this.clearcoatRoughness = source.clearcoatRoughness;
  19870. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19871. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19872. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19873. this.reflectivity = source.reflectivity;
  19874. if (source.sheen) {
  19875. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  19876. } else {
  19877. this.sheen = null;
  19878. }
  19879. this.transparency = source.transparency;
  19880. return this;
  19881. };
  19882. /**
  19883. * @author mrdoob / http://mrdoob.com/
  19884. * @author alteredq / http://alteredqualia.com/
  19885. *
  19886. * parameters = {
  19887. * color: <hex>,
  19888. * specular: <hex>,
  19889. * shininess: <float>,
  19890. * opacity: <float>,
  19891. *
  19892. * map: new THREE.Texture( <Image> ),
  19893. *
  19894. * lightMap: new THREE.Texture( <Image> ),
  19895. * lightMapIntensity: <float>
  19896. *
  19897. * aoMap: new THREE.Texture( <Image> ),
  19898. * aoMapIntensity: <float>
  19899. *
  19900. * emissive: <hex>,
  19901. * emissiveIntensity: <float>
  19902. * emissiveMap: new THREE.Texture( <Image> ),
  19903. *
  19904. * bumpMap: new THREE.Texture( <Image> ),
  19905. * bumpScale: <float>,
  19906. *
  19907. * normalMap: new THREE.Texture( <Image> ),
  19908. * normalMapType: THREE.TangentSpaceNormalMap,
  19909. * normalScale: <Vector2>,
  19910. *
  19911. * displacementMap: new THREE.Texture( <Image> ),
  19912. * displacementScale: <float>,
  19913. * displacementBias: <float>,
  19914. *
  19915. * specularMap: new THREE.Texture( <Image> ),
  19916. *
  19917. * alphaMap: new THREE.Texture( <Image> ),
  19918. *
  19919. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19920. * combine: THREE.MultiplyOperation,
  19921. * reflectivity: <float>,
  19922. * refractionRatio: <float>,
  19923. *
  19924. * wireframe: <boolean>,
  19925. * wireframeLinewidth: <float>,
  19926. *
  19927. * skinning: <bool>,
  19928. * morphTargets: <bool>,
  19929. * morphNormals: <bool>
  19930. * }
  19931. */
  19932. function MeshPhongMaterial(parameters) {
  19933. Material.call(this);
  19934. this.type = 'MeshPhongMaterial';
  19935. this.color = new Color(0xffffff); // diffuse
  19936. this.specular = new Color(0x111111);
  19937. this.shininess = 30;
  19938. this.map = null;
  19939. this.lightMap = null;
  19940. this.lightMapIntensity = 1.0;
  19941. this.aoMap = null;
  19942. this.aoMapIntensity = 1.0;
  19943. this.emissive = new Color(0x000000);
  19944. this.emissiveIntensity = 1.0;
  19945. this.emissiveMap = null;
  19946. this.bumpMap = null;
  19947. this.bumpScale = 1;
  19948. this.normalMap = null;
  19949. this.normalMapType = TangentSpaceNormalMap;
  19950. this.normalScale = new Vector2(1, 1);
  19951. this.displacementMap = null;
  19952. this.displacementScale = 1;
  19953. this.displacementBias = 0;
  19954. this.specularMap = null;
  19955. this.alphaMap = null;
  19956. this.envMap = null;
  19957. this.combine = MultiplyOperation;
  19958. this.reflectivity = 1;
  19959. this.refractionRatio = 0.98;
  19960. this.wireframe = false;
  19961. this.wireframeLinewidth = 1;
  19962. this.wireframeLinecap = 'round';
  19963. this.wireframeLinejoin = 'round';
  19964. this.skinning = false;
  19965. this.morphTargets = false;
  19966. this.morphNormals = false;
  19967. this.setValues(parameters);
  19968. }
  19969. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  19970. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  19971. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19972. MeshPhongMaterial.prototype.copy = function (source) {
  19973. Material.prototype.copy.call(this, source);
  19974. this.color.copy(source.color);
  19975. this.specular.copy(source.specular);
  19976. this.shininess = source.shininess;
  19977. this.map = source.map;
  19978. this.lightMap = source.lightMap;
  19979. this.lightMapIntensity = source.lightMapIntensity;
  19980. this.aoMap = source.aoMap;
  19981. this.aoMapIntensity = source.aoMapIntensity;
  19982. this.emissive.copy(source.emissive);
  19983. this.emissiveMap = source.emissiveMap;
  19984. this.emissiveIntensity = source.emissiveIntensity;
  19985. this.bumpMap = source.bumpMap;
  19986. this.bumpScale = source.bumpScale;
  19987. this.normalMap = source.normalMap;
  19988. this.normalMapType = source.normalMapType;
  19989. this.normalScale.copy(source.normalScale);
  19990. this.displacementMap = source.displacementMap;
  19991. this.displacementScale = source.displacementScale;
  19992. this.displacementBias = source.displacementBias;
  19993. this.specularMap = source.specularMap;
  19994. this.alphaMap = source.alphaMap;
  19995. this.envMap = source.envMap;
  19996. this.combine = source.combine;
  19997. this.reflectivity = source.reflectivity;
  19998. this.refractionRatio = source.refractionRatio;
  19999. this.wireframe = source.wireframe;
  20000. this.wireframeLinewidth = source.wireframeLinewidth;
  20001. this.wireframeLinecap = source.wireframeLinecap;
  20002. this.wireframeLinejoin = source.wireframeLinejoin;
  20003. this.skinning = source.skinning;
  20004. this.morphTargets = source.morphTargets;
  20005. this.morphNormals = source.morphNormals;
  20006. return this;
  20007. };
  20008. /**
  20009. * @author takahirox / http://github.com/takahirox
  20010. *
  20011. * parameters = {
  20012. * color: <hex>,
  20013. * specular: <hex>,
  20014. * shininess: <float>,
  20015. *
  20016. * map: new THREE.Texture( <Image> ),
  20017. * gradientMap: new THREE.Texture( <Image> ),
  20018. *
  20019. * lightMap: new THREE.Texture( <Image> ),
  20020. * lightMapIntensity: <float>
  20021. *
  20022. * aoMap: new THREE.Texture( <Image> ),
  20023. * aoMapIntensity: <float>
  20024. *
  20025. * emissive: <hex>,
  20026. * emissiveIntensity: <float>
  20027. * emissiveMap: new THREE.Texture( <Image> ),
  20028. *
  20029. * bumpMap: new THREE.Texture( <Image> ),
  20030. * bumpScale: <float>,
  20031. *
  20032. * normalMap: new THREE.Texture( <Image> ),
  20033. * normalMapType: THREE.TangentSpaceNormalMap,
  20034. * normalScale: <Vector2>,
  20035. *
  20036. * displacementMap: new THREE.Texture( <Image> ),
  20037. * displacementScale: <float>,
  20038. * displacementBias: <float>,
  20039. *
  20040. * specularMap: new THREE.Texture( <Image> ),
  20041. *
  20042. * alphaMap: new THREE.Texture( <Image> ),
  20043. *
  20044. * wireframe: <boolean>,
  20045. * wireframeLinewidth: <float>,
  20046. *
  20047. * skinning: <bool>,
  20048. * morphTargets: <bool>,
  20049. * morphNormals: <bool>
  20050. * }
  20051. */
  20052. function MeshToonMaterial(parameters) {
  20053. Material.call(this);
  20054. this.defines = {
  20055. 'TOON': ''
  20056. };
  20057. this.type = 'MeshToonMaterial';
  20058. this.color = new Color(0xffffff);
  20059. this.specular = new Color(0x111111);
  20060. this.shininess = 30;
  20061. this.map = null;
  20062. this.gradientMap = null;
  20063. this.lightMap = null;
  20064. this.lightMapIntensity = 1.0;
  20065. this.aoMap = null;
  20066. this.aoMapIntensity = 1.0;
  20067. this.emissive = new Color(0x000000);
  20068. this.emissiveIntensity = 1.0;
  20069. this.emissiveMap = null;
  20070. this.bumpMap = null;
  20071. this.bumpScale = 1;
  20072. this.normalMap = null;
  20073. this.normalMapType = TangentSpaceNormalMap;
  20074. this.normalScale = new Vector2(1, 1);
  20075. this.displacementMap = null;
  20076. this.displacementScale = 1;
  20077. this.displacementBias = 0;
  20078. this.specularMap = null;
  20079. this.alphaMap = null;
  20080. this.wireframe = false;
  20081. this.wireframeLinewidth = 1;
  20082. this.wireframeLinecap = 'round';
  20083. this.wireframeLinejoin = 'round';
  20084. this.skinning = false;
  20085. this.morphTargets = false;
  20086. this.morphNormals = false;
  20087. this.setValues(parameters);
  20088. }
  20089. MeshToonMaterial.prototype = Object.create(Material.prototype);
  20090. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20091. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20092. MeshToonMaterial.prototype.copy = function (source) {
  20093. Material.prototype.copy.call(this, source);
  20094. this.color.copy(source.color);
  20095. this.specular.copy(source.specular);
  20096. this.shininess = source.shininess;
  20097. this.map = source.map;
  20098. this.gradientMap = source.gradientMap;
  20099. this.lightMap = source.lightMap;
  20100. this.lightMapIntensity = source.lightMapIntensity;
  20101. this.aoMap = source.aoMap;
  20102. this.aoMapIntensity = source.aoMapIntensity;
  20103. this.emissive.copy(source.emissive);
  20104. this.emissiveMap = source.emissiveMap;
  20105. this.emissiveIntensity = source.emissiveIntensity;
  20106. this.bumpMap = source.bumpMap;
  20107. this.bumpScale = source.bumpScale;
  20108. this.normalMap = source.normalMap;
  20109. this.normalMapType = source.normalMapType;
  20110. this.normalScale.copy(source.normalScale);
  20111. this.displacementMap = source.displacementMap;
  20112. this.displacementScale = source.displacementScale;
  20113. this.displacementBias = source.displacementBias;
  20114. this.specularMap = source.specularMap;
  20115. this.alphaMap = source.alphaMap;
  20116. this.wireframe = source.wireframe;
  20117. this.wireframeLinewidth = source.wireframeLinewidth;
  20118. this.wireframeLinecap = source.wireframeLinecap;
  20119. this.wireframeLinejoin = source.wireframeLinejoin;
  20120. this.skinning = source.skinning;
  20121. this.morphTargets = source.morphTargets;
  20122. this.morphNormals = source.morphNormals;
  20123. return this;
  20124. };
  20125. /**
  20126. * @author mrdoob / http://mrdoob.com/
  20127. * @author WestLangley / http://github.com/WestLangley
  20128. *
  20129. * parameters = {
  20130. * opacity: <float>,
  20131. *
  20132. * bumpMap: new THREE.Texture( <Image> ),
  20133. * bumpScale: <float>,
  20134. *
  20135. * normalMap: new THREE.Texture( <Image> ),
  20136. * normalMapType: THREE.TangentSpaceNormalMap,
  20137. * normalScale: <Vector2>,
  20138. *
  20139. * displacementMap: new THREE.Texture( <Image> ),
  20140. * displacementScale: <float>,
  20141. * displacementBias: <float>,
  20142. *
  20143. * wireframe: <boolean>,
  20144. * wireframeLinewidth: <float>
  20145. *
  20146. * skinning: <bool>,
  20147. * morphTargets: <bool>,
  20148. * morphNormals: <bool>
  20149. * }
  20150. */
  20151. function MeshNormalMaterial(parameters) {
  20152. Material.call(this);
  20153. this.type = 'MeshNormalMaterial';
  20154. this.bumpMap = null;
  20155. this.bumpScale = 1;
  20156. this.normalMap = null;
  20157. this.normalMapType = TangentSpaceNormalMap;
  20158. this.normalScale = new Vector2(1, 1);
  20159. this.displacementMap = null;
  20160. this.displacementScale = 1;
  20161. this.displacementBias = 0;
  20162. this.wireframe = false;
  20163. this.wireframeLinewidth = 1;
  20164. this.fog = false;
  20165. this.skinning = false;
  20166. this.morphTargets = false;
  20167. this.morphNormals = false;
  20168. this.setValues(parameters);
  20169. }
  20170. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20171. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20172. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20173. MeshNormalMaterial.prototype.copy = function (source) {
  20174. Material.prototype.copy.call(this, source);
  20175. this.bumpMap = source.bumpMap;
  20176. this.bumpScale = source.bumpScale;
  20177. this.normalMap = source.normalMap;
  20178. this.normalMapType = source.normalMapType;
  20179. this.normalScale.copy(source.normalScale);
  20180. this.displacementMap = source.displacementMap;
  20181. this.displacementScale = source.displacementScale;
  20182. this.displacementBias = source.displacementBias;
  20183. this.wireframe = source.wireframe;
  20184. this.wireframeLinewidth = source.wireframeLinewidth;
  20185. this.skinning = source.skinning;
  20186. this.morphTargets = source.morphTargets;
  20187. this.morphNormals = source.morphNormals;
  20188. return this;
  20189. };
  20190. /**
  20191. * @author mrdoob / http://mrdoob.com/
  20192. * @author alteredq / http://alteredqualia.com/
  20193. *
  20194. * parameters = {
  20195. * color: <hex>,
  20196. * opacity: <float>,
  20197. *
  20198. * map: new THREE.Texture( <Image> ),
  20199. *
  20200. * lightMap: new THREE.Texture( <Image> ),
  20201. * lightMapIntensity: <float>
  20202. *
  20203. * aoMap: new THREE.Texture( <Image> ),
  20204. * aoMapIntensity: <float>
  20205. *
  20206. * emissive: <hex>,
  20207. * emissiveIntensity: <float>
  20208. * emissiveMap: new THREE.Texture( <Image> ),
  20209. *
  20210. * specularMap: new THREE.Texture( <Image> ),
  20211. *
  20212. * alphaMap: new THREE.Texture( <Image> ),
  20213. *
  20214. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20215. * combine: THREE.Multiply,
  20216. * reflectivity: <float>,
  20217. * refractionRatio: <float>,
  20218. *
  20219. * wireframe: <boolean>,
  20220. * wireframeLinewidth: <float>,
  20221. *
  20222. * skinning: <bool>,
  20223. * morphTargets: <bool>,
  20224. * morphNormals: <bool>
  20225. * }
  20226. */
  20227. function MeshLambertMaterial(parameters) {
  20228. Material.call(this);
  20229. this.type = 'MeshLambertMaterial';
  20230. this.color = new Color(0xffffff); // diffuse
  20231. this.map = null;
  20232. this.lightMap = null;
  20233. this.lightMapIntensity = 1.0;
  20234. this.aoMap = null;
  20235. this.aoMapIntensity = 1.0;
  20236. this.emissive = new Color(0x000000);
  20237. this.emissiveIntensity = 1.0;
  20238. this.emissiveMap = null;
  20239. this.specularMap = null;
  20240. this.alphaMap = null;
  20241. this.envMap = null;
  20242. this.combine = MultiplyOperation;
  20243. this.reflectivity = 1;
  20244. this.refractionRatio = 0.98;
  20245. this.wireframe = false;
  20246. this.wireframeLinewidth = 1;
  20247. this.wireframeLinecap = 'round';
  20248. this.wireframeLinejoin = 'round';
  20249. this.skinning = false;
  20250. this.morphTargets = false;
  20251. this.morphNormals = false;
  20252. this.setValues(parameters);
  20253. }
  20254. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  20255. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20256. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20257. MeshLambertMaterial.prototype.copy = function (source) {
  20258. Material.prototype.copy.call(this, source);
  20259. this.color.copy(source.color);
  20260. this.map = source.map;
  20261. this.lightMap = source.lightMap;
  20262. this.lightMapIntensity = source.lightMapIntensity;
  20263. this.aoMap = source.aoMap;
  20264. this.aoMapIntensity = source.aoMapIntensity;
  20265. this.emissive.copy(source.emissive);
  20266. this.emissiveMap = source.emissiveMap;
  20267. this.emissiveIntensity = source.emissiveIntensity;
  20268. this.specularMap = source.specularMap;
  20269. this.alphaMap = source.alphaMap;
  20270. this.envMap = source.envMap;
  20271. this.combine = source.combine;
  20272. this.reflectivity = source.reflectivity;
  20273. this.refractionRatio = source.refractionRatio;
  20274. this.wireframe = source.wireframe;
  20275. this.wireframeLinewidth = source.wireframeLinewidth;
  20276. this.wireframeLinecap = source.wireframeLinecap;
  20277. this.wireframeLinejoin = source.wireframeLinejoin;
  20278. this.skinning = source.skinning;
  20279. this.morphTargets = source.morphTargets;
  20280. this.morphNormals = source.morphNormals;
  20281. return this;
  20282. };
  20283. /**
  20284. * @author WestLangley / http://github.com/WestLangley
  20285. *
  20286. * parameters = {
  20287. * color: <hex>,
  20288. * opacity: <float>,
  20289. *
  20290. * matcap: new THREE.Texture( <Image> ),
  20291. *
  20292. * map: new THREE.Texture( <Image> ),
  20293. *
  20294. * bumpMap: new THREE.Texture( <Image> ),
  20295. * bumpScale: <float>,
  20296. *
  20297. * normalMap: new THREE.Texture( <Image> ),
  20298. * normalMapType: THREE.TangentSpaceNormalMap,
  20299. * normalScale: <Vector2>,
  20300. *
  20301. * displacementMap: new THREE.Texture( <Image> ),
  20302. * displacementScale: <float>,
  20303. * displacementBias: <float>,
  20304. *
  20305. * alphaMap: new THREE.Texture( <Image> ),
  20306. *
  20307. * skinning: <bool>,
  20308. * morphTargets: <bool>,
  20309. * morphNormals: <bool>
  20310. * }
  20311. */
  20312. function MeshMatcapMaterial(parameters) {
  20313. Material.call(this);
  20314. this.defines = {
  20315. 'MATCAP': ''
  20316. };
  20317. this.type = 'MeshMatcapMaterial';
  20318. this.color = new Color(0xffffff); // diffuse
  20319. this.matcap = null;
  20320. this.map = null;
  20321. this.bumpMap = null;
  20322. this.bumpScale = 1;
  20323. this.normalMap = null;
  20324. this.normalMapType = TangentSpaceNormalMap;
  20325. this.normalScale = new Vector2(1, 1);
  20326. this.displacementMap = null;
  20327. this.displacementScale = 1;
  20328. this.displacementBias = 0;
  20329. this.alphaMap = null;
  20330. this.skinning = false;
  20331. this.morphTargets = false;
  20332. this.morphNormals = false;
  20333. this.setValues(parameters);
  20334. }
  20335. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20336. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20337. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20338. MeshMatcapMaterial.prototype.copy = function (source) {
  20339. Material.prototype.copy.call(this, source);
  20340. this.defines = {
  20341. 'MATCAP': ''
  20342. };
  20343. this.color.copy(source.color);
  20344. this.matcap = source.matcap;
  20345. this.map = source.map;
  20346. this.bumpMap = source.bumpMap;
  20347. this.bumpScale = source.bumpScale;
  20348. this.normalMap = source.normalMap;
  20349. this.normalMapType = source.normalMapType;
  20350. this.normalScale.copy(source.normalScale);
  20351. this.displacementMap = source.displacementMap;
  20352. this.displacementScale = source.displacementScale;
  20353. this.displacementBias = source.displacementBias;
  20354. this.alphaMap = source.alphaMap;
  20355. this.skinning = source.skinning;
  20356. this.morphTargets = source.morphTargets;
  20357. this.morphNormals = source.morphNormals;
  20358. return this;
  20359. };
  20360. /**
  20361. * @author alteredq / http://alteredqualia.com/
  20362. *
  20363. * parameters = {
  20364. * color: <hex>,
  20365. * opacity: <float>,
  20366. *
  20367. * linewidth: <float>,
  20368. *
  20369. * scale: <float>,
  20370. * dashSize: <float>,
  20371. * gapSize: <float>
  20372. * }
  20373. */
  20374. function LineDashedMaterial(parameters) {
  20375. LineBasicMaterial.call(this);
  20376. this.type = 'LineDashedMaterial';
  20377. this.scale = 1;
  20378. this.dashSize = 3;
  20379. this.gapSize = 1;
  20380. this.setValues(parameters);
  20381. }
  20382. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20383. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20384. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20385. LineDashedMaterial.prototype.copy = function (source) {
  20386. LineBasicMaterial.prototype.copy.call(this, source);
  20387. this.scale = source.scale;
  20388. this.dashSize = source.dashSize;
  20389. this.gapSize = source.gapSize;
  20390. return this;
  20391. };
  20392. var Materials =
  20393. /*#__PURE__*/
  20394. Object.freeze({
  20395. __proto__: null,
  20396. ShadowMaterial: ShadowMaterial,
  20397. SpriteMaterial: SpriteMaterial,
  20398. RawShaderMaterial: RawShaderMaterial,
  20399. ShaderMaterial: ShaderMaterial,
  20400. PointsMaterial: PointsMaterial,
  20401. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20402. MeshStandardMaterial: MeshStandardMaterial,
  20403. MeshPhongMaterial: MeshPhongMaterial,
  20404. MeshToonMaterial: MeshToonMaterial,
  20405. MeshNormalMaterial: MeshNormalMaterial,
  20406. MeshLambertMaterial: MeshLambertMaterial,
  20407. MeshDepthMaterial: MeshDepthMaterial,
  20408. MeshDistanceMaterial: MeshDistanceMaterial,
  20409. MeshBasicMaterial: MeshBasicMaterial,
  20410. MeshMatcapMaterial: MeshMatcapMaterial,
  20411. LineDashedMaterial: LineDashedMaterial,
  20412. LineBasicMaterial: LineBasicMaterial,
  20413. Material: Material
  20414. });
  20415. /**
  20416. * @author tschw
  20417. * @author Ben Houston / http://clara.io/
  20418. * @author David Sarno / http://lighthaus.us/
  20419. */
  20420. var AnimationUtils = {
  20421. // same as Array.prototype.slice, but also works on typed arrays
  20422. arraySlice: function (array, from, to) {
  20423. if (AnimationUtils.isTypedArray(array)) {
  20424. // in ios9 array.subarray(from, undefined) will return empty array
  20425. // but array.subarray(from) or array.subarray(from, len) is correct
  20426. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20427. }
  20428. return array.slice(from, to);
  20429. },
  20430. // converts an array to a specific type
  20431. convertArray: function (array, type, forceClone) {
  20432. if (!array || // let 'undefined' and 'null' pass
  20433. !forceClone && array.constructor === type) return array;
  20434. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20435. return new type(array); // create typed array
  20436. }
  20437. return Array.prototype.slice.call(array); // create Array
  20438. },
  20439. isTypedArray: function (object) {
  20440. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20441. },
  20442. // returns an array by which times and values can be sorted
  20443. getKeyframeOrder: function (times) {
  20444. function compareTime(i, j) {
  20445. return times[i] - times[j];
  20446. }
  20447. var n = times.length;
  20448. var result = new Array(n);
  20449. for (var i = 0; i !== n; ++i) result[i] = i;
  20450. result.sort(compareTime);
  20451. return result;
  20452. },
  20453. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20454. sortedArray: function (values, stride, order) {
  20455. var nValues = values.length;
  20456. var result = new values.constructor(nValues);
  20457. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20458. var srcOffset = order[i] * stride;
  20459. for (var j = 0; j !== stride; ++j) {
  20460. result[dstOffset++] = values[srcOffset + j];
  20461. }
  20462. }
  20463. return result;
  20464. },
  20465. // function for parsing AOS keyframe formats
  20466. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20467. var i = 1,
  20468. key = jsonKeys[0];
  20469. while (key !== undefined && key[valuePropertyName] === undefined) {
  20470. key = jsonKeys[i++];
  20471. }
  20472. if (key === undefined) return; // no data
  20473. var value = key[valuePropertyName];
  20474. if (value === undefined) return; // no data
  20475. if (Array.isArray(value)) {
  20476. do {
  20477. value = key[valuePropertyName];
  20478. if (value !== undefined) {
  20479. times.push(key.time);
  20480. values.push.apply(values, value); // push all elements
  20481. }
  20482. key = jsonKeys[i++];
  20483. } while (key !== undefined);
  20484. } else if (value.toArray !== undefined) {
  20485. // ...assume THREE.Math-ish
  20486. do {
  20487. value = key[valuePropertyName];
  20488. if (value !== undefined) {
  20489. times.push(key.time);
  20490. value.toArray(values, values.length);
  20491. }
  20492. key = jsonKeys[i++];
  20493. } while (key !== undefined);
  20494. } else {
  20495. // otherwise push as-is
  20496. do {
  20497. value = key[valuePropertyName];
  20498. if (value !== undefined) {
  20499. times.push(key.time);
  20500. values.push(value);
  20501. }
  20502. key = jsonKeys[i++];
  20503. } while (key !== undefined);
  20504. }
  20505. },
  20506. subclip: function (sourceClip, name, startFrame, endFrame, fps) {
  20507. fps = fps || 30;
  20508. var clip = sourceClip.clone();
  20509. clip.name = name;
  20510. var tracks = [];
  20511. for (var i = 0; i < clip.tracks.length; ++i) {
  20512. var track = clip.tracks[i];
  20513. var valueSize = track.getValueSize();
  20514. var times = [];
  20515. var values = [];
  20516. for (var j = 0; j < track.times.length; ++j) {
  20517. var frame = track.times[j] * fps;
  20518. if (frame < startFrame || frame >= endFrame) continue;
  20519. times.push(track.times[j]);
  20520. for (var k = 0; k < valueSize; ++k) {
  20521. values.push(track.values[j * valueSize + k]);
  20522. }
  20523. }
  20524. if (times.length === 0) continue;
  20525. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20526. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20527. tracks.push(track);
  20528. }
  20529. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20530. var minStartTime = Infinity;
  20531. for (var i = 0; i < clip.tracks.length; ++i) {
  20532. if (minStartTime > clip.tracks[i].times[0]) {
  20533. minStartTime = clip.tracks[i].times[0];
  20534. }
  20535. } // shift all tracks such that clip begins at t=0
  20536. for (var i = 0; i < clip.tracks.length; ++i) {
  20537. clip.tracks[i].shift(-1 * minStartTime);
  20538. }
  20539. clip.resetDuration();
  20540. return clip;
  20541. }
  20542. };
  20543. /**
  20544. * Abstract base class of interpolants over parametric samples.
  20545. *
  20546. * The parameter domain is one dimensional, typically the time or a path
  20547. * along a curve defined by the data.
  20548. *
  20549. * The sample values can have any dimensionality and derived classes may
  20550. * apply special interpretations to the data.
  20551. *
  20552. * This class provides the interval seek in a Template Method, deferring
  20553. * the actual interpolation to derived classes.
  20554. *
  20555. * Time complexity is O(1) for linear access crossing at most two points
  20556. * and O(log N) for random access, where N is the number of positions.
  20557. *
  20558. * References:
  20559. *
  20560. * http://www.oodesign.com/template-method-pattern.html
  20561. *
  20562. * @author tschw
  20563. */
  20564. exports.AnimationUtils = AnimationUtils;
  20565. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20566. this.parameterPositions = parameterPositions;
  20567. this._cachedIndex = 0;
  20568. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20569. this.sampleValues = sampleValues;
  20570. this.valueSize = sampleSize;
  20571. }
  20572. Object.assign(Interpolant.prototype, {
  20573. evaluate: function (t) {
  20574. var pp = this.parameterPositions,
  20575. i1 = this._cachedIndex,
  20576. t1 = pp[i1],
  20577. t0 = pp[i1 - 1];
  20578. validate_interval: {
  20579. seek: {
  20580. var right;
  20581. linear_scan: {
  20582. //- See http://jsperf.com/comparison-to-undefined/3
  20583. //- slower code:
  20584. //-
  20585. //- if ( t >= t1 || t1 === undefined ) {
  20586. forward_scan: if (!(t < t1)) {
  20587. for (var giveUpAt = i1 + 2;;) {
  20588. if (t1 === undefined) {
  20589. if (t < t0) break forward_scan; // after end
  20590. i1 = pp.length;
  20591. this._cachedIndex = i1;
  20592. return this.afterEnd_(i1 - 1, t, t0);
  20593. }
  20594. if (i1 === giveUpAt) break; // this loop
  20595. t0 = t1;
  20596. t1 = pp[++i1];
  20597. if (t < t1) {
  20598. // we have arrived at the sought interval
  20599. break seek;
  20600. }
  20601. } // prepare binary search on the right side of the index
  20602. right = pp.length;
  20603. break linear_scan;
  20604. } //- slower code:
  20605. //- if ( t < t0 || t0 === undefined ) {
  20606. if (!(t >= t0)) {
  20607. // looping?
  20608. var t1global = pp[1];
  20609. if (t < t1global) {
  20610. i1 = 2; // + 1, using the scan for the details
  20611. t0 = t1global;
  20612. } // linear reverse scan
  20613. for (var giveUpAt = i1 - 2;;) {
  20614. if (t0 === undefined) {
  20615. // before start
  20616. this._cachedIndex = 0;
  20617. return this.beforeStart_(0, t, t1);
  20618. }
  20619. if (i1 === giveUpAt) break; // this loop
  20620. t1 = t0;
  20621. t0 = pp[--i1 - 1];
  20622. if (t >= t0) {
  20623. // we have arrived at the sought interval
  20624. break seek;
  20625. }
  20626. } // prepare binary search on the left side of the index
  20627. right = i1;
  20628. i1 = 0;
  20629. break linear_scan;
  20630. } // the interval is valid
  20631. break validate_interval;
  20632. } // linear scan
  20633. // binary search
  20634. while (i1 < right) {
  20635. var mid = i1 + right >>> 1;
  20636. if (t < pp[mid]) {
  20637. right = mid;
  20638. } else {
  20639. i1 = mid + 1;
  20640. }
  20641. }
  20642. t1 = pp[i1];
  20643. t0 = pp[i1 - 1]; // check boundary cases, again
  20644. if (t0 === undefined) {
  20645. this._cachedIndex = 0;
  20646. return this.beforeStart_(0, t, t1);
  20647. }
  20648. if (t1 === undefined) {
  20649. i1 = pp.length;
  20650. this._cachedIndex = i1;
  20651. return this.afterEnd_(i1 - 1, t0, t);
  20652. }
  20653. } // seek
  20654. this._cachedIndex = i1;
  20655. this.intervalChanged_(i1, t0, t1);
  20656. } // validate_interval
  20657. return this.interpolate_(i1, t0, t, t1);
  20658. },
  20659. settings: null,
  20660. // optional, subclass-specific settings structure
  20661. // Note: The indirection allows central control of many interpolants.
  20662. // --- Protected interface
  20663. DefaultSettings_: {},
  20664. getSettings_: function () {
  20665. return this.settings || this.DefaultSettings_;
  20666. },
  20667. copySampleValue_: function (index) {
  20668. // copies a sample value to the result buffer
  20669. var result = this.resultBuffer,
  20670. values = this.sampleValues,
  20671. stride = this.valueSize,
  20672. offset = index * stride;
  20673. for (var i = 0; i !== stride; ++i) {
  20674. result[i] = values[offset + i];
  20675. }
  20676. return result;
  20677. },
  20678. // Template methods for derived classes:
  20679. interpolate_: function ()
  20680. /* i1, t0, t, t1 */
  20681. {
  20682. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20683. },
  20684. intervalChanged_: function ()
  20685. /* i1, t0, t1 */
  20686. {// empty
  20687. }
  20688. }); // DECLARE ALIAS AFTER assign prototype
  20689. Object.assign(Interpolant.prototype, {
  20690. //( 0, t, t0 ), returns this.resultBuffer
  20691. beforeStart_: Interpolant.prototype.copySampleValue_,
  20692. //( N-1, tN-1, t ), returns this.resultBuffer
  20693. afterEnd_: Interpolant.prototype.copySampleValue_
  20694. });
  20695. /**
  20696. * Fast and simple cubic spline interpolant.
  20697. *
  20698. * It was derived from a Hermitian construction setting the first derivative
  20699. * at each sample position to the linear slope between neighboring positions
  20700. * over their parameter interval.
  20701. *
  20702. * @author tschw
  20703. */
  20704. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20705. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20706. this._weightPrev = -0;
  20707. this._offsetPrev = -0;
  20708. this._weightNext = -0;
  20709. this._offsetNext = -0;
  20710. }
  20711. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20712. constructor: CubicInterpolant,
  20713. DefaultSettings_: {
  20714. endingStart: ZeroCurvatureEnding,
  20715. endingEnd: ZeroCurvatureEnding
  20716. },
  20717. intervalChanged_: function (i1, t0, t1) {
  20718. var pp = this.parameterPositions,
  20719. iPrev = i1 - 2,
  20720. iNext = i1 + 1,
  20721. tPrev = pp[iPrev],
  20722. tNext = pp[iNext];
  20723. if (tPrev === undefined) {
  20724. switch (this.getSettings_().endingStart) {
  20725. case ZeroSlopeEnding:
  20726. // f'(t0) = 0
  20727. iPrev = i1;
  20728. tPrev = 2 * t0 - t1;
  20729. break;
  20730. case WrapAroundEnding:
  20731. // use the other end of the curve
  20732. iPrev = pp.length - 2;
  20733. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20734. break;
  20735. default:
  20736. // ZeroCurvatureEnding
  20737. // f''(t0) = 0 a.k.a. Natural Spline
  20738. iPrev = i1;
  20739. tPrev = t1;
  20740. }
  20741. }
  20742. if (tNext === undefined) {
  20743. switch (this.getSettings_().endingEnd) {
  20744. case ZeroSlopeEnding:
  20745. // f'(tN) = 0
  20746. iNext = i1;
  20747. tNext = 2 * t1 - t0;
  20748. break;
  20749. case WrapAroundEnding:
  20750. // use the other end of the curve
  20751. iNext = 1;
  20752. tNext = t1 + pp[1] - pp[0];
  20753. break;
  20754. default:
  20755. // ZeroCurvatureEnding
  20756. // f''(tN) = 0, a.k.a. Natural Spline
  20757. iNext = i1 - 1;
  20758. tNext = t0;
  20759. }
  20760. }
  20761. var halfDt = (t1 - t0) * 0.5,
  20762. stride = this.valueSize;
  20763. this._weightPrev = halfDt / (t0 - tPrev);
  20764. this._weightNext = halfDt / (tNext - t1);
  20765. this._offsetPrev = iPrev * stride;
  20766. this._offsetNext = iNext * stride;
  20767. },
  20768. interpolate_: function (i1, t0, t, t1) {
  20769. var result = this.resultBuffer,
  20770. values = this.sampleValues,
  20771. stride = this.valueSize,
  20772. o1 = i1 * stride,
  20773. o0 = o1 - stride,
  20774. oP = this._offsetPrev,
  20775. oN = this._offsetNext,
  20776. wP = this._weightPrev,
  20777. wN = this._weightNext,
  20778. p = (t - t0) / (t1 - t0),
  20779. pp = p * p,
  20780. ppp = pp * p; // evaluate polynomials
  20781. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  20782. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20783. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20784. var sN = wN * ppp - wN * pp; // combine data linearly
  20785. for (var i = 0; i !== stride; ++i) {
  20786. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20787. }
  20788. return result;
  20789. }
  20790. });
  20791. /**
  20792. * @author tschw
  20793. */
  20794. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20795. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20796. }
  20797. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20798. constructor: LinearInterpolant,
  20799. interpolate_: function (i1, t0, t, t1) {
  20800. var result = this.resultBuffer,
  20801. values = this.sampleValues,
  20802. stride = this.valueSize,
  20803. offset1 = i1 * stride,
  20804. offset0 = offset1 - stride,
  20805. weight1 = (t - t0) / (t1 - t0),
  20806. weight0 = 1 - weight1;
  20807. for (var i = 0; i !== stride; ++i) {
  20808. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20809. }
  20810. return result;
  20811. }
  20812. });
  20813. /**
  20814. *
  20815. * Interpolant that evaluates to the sample value at the position preceeding
  20816. * the parameter.
  20817. *
  20818. * @author tschw
  20819. */
  20820. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20821. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20822. }
  20823. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20824. constructor: DiscreteInterpolant,
  20825. interpolate_: function (i1
  20826. /*, t0, t, t1 */
  20827. ) {
  20828. return this.copySampleValue_(i1 - 1);
  20829. }
  20830. });
  20831. /**
  20832. *
  20833. * A timed sequence of keyframes for a specific property.
  20834. *
  20835. *
  20836. * @author Ben Houston / http://clara.io/
  20837. * @author David Sarno / http://lighthaus.us/
  20838. * @author tschw
  20839. */
  20840. function KeyframeTrack(name, times, values, interpolation) {
  20841. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20842. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20843. this.name = name;
  20844. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20845. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20846. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20847. } // Static methods
  20848. Object.assign(KeyframeTrack, {
  20849. // Serialization (in static context, because of constructor invocation
  20850. // and automatic invocation of .toJSON):
  20851. toJSON: function (track) {
  20852. var trackType = track.constructor;
  20853. var json; // derived classes can define a static toJSON method
  20854. if (trackType.toJSON !== undefined) {
  20855. json = trackType.toJSON(track);
  20856. } else {
  20857. // by default, we assume the data can be serialized as-is
  20858. json = {
  20859. 'name': track.name,
  20860. 'times': AnimationUtils.convertArray(track.times, Array),
  20861. 'values': AnimationUtils.convertArray(track.values, Array)
  20862. };
  20863. var interpolation = track.getInterpolation();
  20864. if (interpolation !== track.DefaultInterpolation) {
  20865. json.interpolation = interpolation;
  20866. }
  20867. }
  20868. json.type = track.ValueTypeName; // mandatory
  20869. return json;
  20870. }
  20871. });
  20872. Object.assign(KeyframeTrack.prototype, {
  20873. constructor: KeyframeTrack,
  20874. TimeBufferType: Float32Array,
  20875. ValueBufferType: Float32Array,
  20876. DefaultInterpolation: InterpolateLinear,
  20877. InterpolantFactoryMethodDiscrete: function (result) {
  20878. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20879. },
  20880. InterpolantFactoryMethodLinear: function (result) {
  20881. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20882. },
  20883. InterpolantFactoryMethodSmooth: function (result) {
  20884. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20885. },
  20886. setInterpolation: function (interpolation) {
  20887. var factoryMethod;
  20888. switch (interpolation) {
  20889. case InterpolateDiscrete:
  20890. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20891. break;
  20892. case InterpolateLinear:
  20893. factoryMethod = this.InterpolantFactoryMethodLinear;
  20894. break;
  20895. case InterpolateSmooth:
  20896. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20897. break;
  20898. }
  20899. if (factoryMethod === undefined) {
  20900. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  20901. if (this.createInterpolant === undefined) {
  20902. // fall back to default, unless the default itself is messed up
  20903. if (interpolation !== this.DefaultInterpolation) {
  20904. this.setInterpolation(this.DefaultInterpolation);
  20905. } else {
  20906. throw new Error(message); // fatal, in this case
  20907. }
  20908. }
  20909. console.warn('THREE.KeyframeTrack:', message);
  20910. return this;
  20911. }
  20912. this.createInterpolant = factoryMethod;
  20913. return this;
  20914. },
  20915. getInterpolation: function () {
  20916. switch (this.createInterpolant) {
  20917. case this.InterpolantFactoryMethodDiscrete:
  20918. return InterpolateDiscrete;
  20919. case this.InterpolantFactoryMethodLinear:
  20920. return InterpolateLinear;
  20921. case this.InterpolantFactoryMethodSmooth:
  20922. return InterpolateSmooth;
  20923. }
  20924. },
  20925. getValueSize: function () {
  20926. return this.values.length / this.times.length;
  20927. },
  20928. // move all keyframes either forwards or backwards in time
  20929. shift: function (timeOffset) {
  20930. if (timeOffset !== 0.0) {
  20931. var times = this.times;
  20932. for (var i = 0, n = times.length; i !== n; ++i) {
  20933. times[i] += timeOffset;
  20934. }
  20935. }
  20936. return this;
  20937. },
  20938. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20939. scale: function (timeScale) {
  20940. if (timeScale !== 1.0) {
  20941. var times = this.times;
  20942. for (var i = 0, n = times.length; i !== n; ++i) {
  20943. times[i] *= timeScale;
  20944. }
  20945. }
  20946. return this;
  20947. },
  20948. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20949. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20950. trim: function (startTime, endTime) {
  20951. var times = this.times,
  20952. nKeys = times.length,
  20953. from = 0,
  20954. to = nKeys - 1;
  20955. while (from !== nKeys && times[from] < startTime) {
  20956. ++from;
  20957. }
  20958. while (to !== -1 && times[to] > endTime) {
  20959. --to;
  20960. }
  20961. ++to; // inclusive -> exclusive bound
  20962. if (from !== 0 || to !== nKeys) {
  20963. // empty tracks are forbidden, so keep at least one keyframe
  20964. if (from >= to) {
  20965. to = Math.max(to, 1);
  20966. from = to - 1;
  20967. }
  20968. var stride = this.getValueSize();
  20969. this.times = AnimationUtils.arraySlice(times, from, to);
  20970. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20971. }
  20972. return this;
  20973. },
  20974. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20975. validate: function () {
  20976. var valid = true;
  20977. var valueSize = this.getValueSize();
  20978. if (valueSize - Math.floor(valueSize) !== 0) {
  20979. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20980. valid = false;
  20981. }
  20982. var times = this.times,
  20983. values = this.values,
  20984. nKeys = times.length;
  20985. if (nKeys === 0) {
  20986. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20987. valid = false;
  20988. }
  20989. var prevTime = null;
  20990. for (var i = 0; i !== nKeys; i++) {
  20991. var currTime = times[i];
  20992. if (typeof currTime === 'number' && isNaN(currTime)) {
  20993. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20994. valid = false;
  20995. break;
  20996. }
  20997. if (prevTime !== null && prevTime > currTime) {
  20998. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20999. valid = false;
  21000. break;
  21001. }
  21002. prevTime = currTime;
  21003. }
  21004. if (values !== undefined) {
  21005. if (AnimationUtils.isTypedArray(values)) {
  21006. for (var i = 0, n = values.length; i !== n; ++i) {
  21007. var value = values[i];
  21008. if (isNaN(value)) {
  21009. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21010. valid = false;
  21011. break;
  21012. }
  21013. }
  21014. }
  21015. }
  21016. return valid;
  21017. },
  21018. // removes equivalent sequential keys as common in morph target sequences
  21019. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21020. optimize: function () {
  21021. // times or values may be shared with other tracks, so overwriting is unsafe
  21022. var times = AnimationUtils.arraySlice(this.times),
  21023. values = AnimationUtils.arraySlice(this.values),
  21024. stride = this.getValueSize(),
  21025. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21026. writeIndex = 1,
  21027. lastIndex = times.length - 1;
  21028. for (var i = 1; i < lastIndex; ++i) {
  21029. var keep = false;
  21030. var time = times[i];
  21031. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21032. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21033. if (!smoothInterpolation) {
  21034. // remove unnecessary keyframes same as their neighbors
  21035. var offset = i * stride,
  21036. offsetP = offset - stride,
  21037. offsetN = offset + stride;
  21038. for (var j = 0; j !== stride; ++j) {
  21039. var value = values[offset + j];
  21040. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21041. keep = true;
  21042. break;
  21043. }
  21044. }
  21045. } else {
  21046. keep = true;
  21047. }
  21048. } // in-place compaction
  21049. if (keep) {
  21050. if (i !== writeIndex) {
  21051. times[writeIndex] = times[i];
  21052. var readOffset = i * stride,
  21053. writeOffset = writeIndex * stride;
  21054. for (var j = 0; j !== stride; ++j) {
  21055. values[writeOffset + j] = values[readOffset + j];
  21056. }
  21057. }
  21058. ++writeIndex;
  21059. }
  21060. } // flush last keyframe (compaction looks ahead)
  21061. if (lastIndex > 0) {
  21062. times[writeIndex] = times[lastIndex];
  21063. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21064. values[writeOffset + j] = values[readOffset + j];
  21065. }
  21066. ++writeIndex;
  21067. }
  21068. if (writeIndex !== times.length) {
  21069. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21070. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21071. } else {
  21072. this.times = times;
  21073. this.values = values;
  21074. }
  21075. return this;
  21076. },
  21077. clone: function () {
  21078. var times = AnimationUtils.arraySlice(this.times, 0);
  21079. var values = AnimationUtils.arraySlice(this.values, 0);
  21080. var TypedKeyframeTrack = this.constructor;
  21081. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21082. track.createInterpolant = this.createInterpolant;
  21083. return track;
  21084. }
  21085. });
  21086. /**
  21087. *
  21088. * A Track of Boolean keyframe values.
  21089. *
  21090. *
  21091. * @author Ben Houston / http://clara.io/
  21092. * @author David Sarno / http://lighthaus.us/
  21093. * @author tschw
  21094. */
  21095. function BooleanKeyframeTrack(name, times, values) {
  21096. KeyframeTrack.call(this, name, times, values);
  21097. }
  21098. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21099. constructor: BooleanKeyframeTrack,
  21100. ValueTypeName: 'bool',
  21101. ValueBufferType: Array,
  21102. DefaultInterpolation: InterpolateDiscrete,
  21103. InterpolantFactoryMethodLinear: undefined,
  21104. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21105. // representation of a single value and a custom interpolant that
  21106. // computes "firstValue ^ isOdd( index )".
  21107. });
  21108. /**
  21109. *
  21110. * A Track of keyframe values that represent color.
  21111. *
  21112. *
  21113. * @author Ben Houston / http://clara.io/
  21114. * @author David Sarno / http://lighthaus.us/
  21115. * @author tschw
  21116. */
  21117. function ColorKeyframeTrack(name, times, values, interpolation) {
  21118. KeyframeTrack.call(this, name, times, values, interpolation);
  21119. }
  21120. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21121. constructor: ColorKeyframeTrack,
  21122. ValueTypeName: 'color' // ValueBufferType is inherited
  21123. // DefaultInterpolation is inherited
  21124. // Note: Very basic implementation and nothing special yet.
  21125. // However, this is the place for color space parameterization.
  21126. });
  21127. /**
  21128. *
  21129. * A Track of numeric keyframe values.
  21130. *
  21131. * @author Ben Houston / http://clara.io/
  21132. * @author David Sarno / http://lighthaus.us/
  21133. * @author tschw
  21134. */
  21135. function NumberKeyframeTrack(name, times, values, interpolation) {
  21136. KeyframeTrack.call(this, name, times, values, interpolation);
  21137. }
  21138. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21139. constructor: NumberKeyframeTrack,
  21140. ValueTypeName: 'number' // ValueBufferType is inherited
  21141. // DefaultInterpolation is inherited
  21142. });
  21143. /**
  21144. * Spherical linear unit quaternion interpolant.
  21145. *
  21146. * @author tschw
  21147. */
  21148. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21149. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21150. }
  21151. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21152. constructor: QuaternionLinearInterpolant,
  21153. interpolate_: function (i1, t0, t, t1) {
  21154. var result = this.resultBuffer,
  21155. values = this.sampleValues,
  21156. stride = this.valueSize,
  21157. offset = i1 * stride,
  21158. alpha = (t - t0) / (t1 - t0);
  21159. for (var end = offset + stride; offset !== end; offset += 4) {
  21160. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21161. }
  21162. return result;
  21163. }
  21164. });
  21165. /**
  21166. *
  21167. * A Track of quaternion keyframe values.
  21168. *
  21169. * @author Ben Houston / http://clara.io/
  21170. * @author David Sarno / http://lighthaus.us/
  21171. * @author tschw
  21172. */
  21173. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21174. KeyframeTrack.call(this, name, times, values, interpolation);
  21175. }
  21176. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21177. constructor: QuaternionKeyframeTrack,
  21178. ValueTypeName: 'quaternion',
  21179. // ValueBufferType is inherited
  21180. DefaultInterpolation: InterpolateLinear,
  21181. InterpolantFactoryMethodLinear: function (result) {
  21182. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21183. },
  21184. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21185. });
  21186. /**
  21187. *
  21188. * A Track that interpolates Strings
  21189. *
  21190. *
  21191. * @author Ben Houston / http://clara.io/
  21192. * @author David Sarno / http://lighthaus.us/
  21193. * @author tschw
  21194. */
  21195. function StringKeyframeTrack(name, times, values, interpolation) {
  21196. KeyframeTrack.call(this, name, times, values, interpolation);
  21197. }
  21198. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21199. constructor: StringKeyframeTrack,
  21200. ValueTypeName: 'string',
  21201. ValueBufferType: Array,
  21202. DefaultInterpolation: InterpolateDiscrete,
  21203. InterpolantFactoryMethodLinear: undefined,
  21204. InterpolantFactoryMethodSmooth: undefined
  21205. });
  21206. /**
  21207. *
  21208. * A Track of vectored keyframe values.
  21209. *
  21210. *
  21211. * @author Ben Houston / http://clara.io/
  21212. * @author David Sarno / http://lighthaus.us/
  21213. * @author tschw
  21214. */
  21215. function VectorKeyframeTrack(name, times, values, interpolation) {
  21216. KeyframeTrack.call(this, name, times, values, interpolation);
  21217. }
  21218. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21219. constructor: VectorKeyframeTrack,
  21220. ValueTypeName: 'vector' // ValueBufferType is inherited
  21221. // DefaultInterpolation is inherited
  21222. });
  21223. /**
  21224. *
  21225. * Reusable set of Tracks that represent an animation.
  21226. *
  21227. * @author Ben Houston / http://clara.io/
  21228. * @author David Sarno / http://lighthaus.us/
  21229. */
  21230. function AnimationClip(name, duration, tracks) {
  21231. this.name = name;
  21232. this.tracks = tracks;
  21233. this.duration = duration !== undefined ? duration : -1;
  21234. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21235. if (this.duration < 0) {
  21236. this.resetDuration();
  21237. }
  21238. }
  21239. function getTrackTypeForValueTypeName(typeName) {
  21240. switch (typeName.toLowerCase()) {
  21241. case 'scalar':
  21242. case 'double':
  21243. case 'float':
  21244. case 'number':
  21245. case 'integer':
  21246. return NumberKeyframeTrack;
  21247. case 'vector':
  21248. case 'vector2':
  21249. case 'vector3':
  21250. case 'vector4':
  21251. return VectorKeyframeTrack;
  21252. case 'color':
  21253. return ColorKeyframeTrack;
  21254. case 'quaternion':
  21255. return QuaternionKeyframeTrack;
  21256. case 'bool':
  21257. case 'boolean':
  21258. return BooleanKeyframeTrack;
  21259. case 'string':
  21260. return StringKeyframeTrack;
  21261. }
  21262. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21263. }
  21264. function parseKeyframeTrack(json) {
  21265. if (json.type === undefined) {
  21266. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21267. }
  21268. var trackType = getTrackTypeForValueTypeName(json.type);
  21269. if (json.times === undefined) {
  21270. var times = [],
  21271. values = [];
  21272. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21273. json.times = times;
  21274. json.values = values;
  21275. } // derived classes can define a static parse method
  21276. if (trackType.parse !== undefined) {
  21277. return trackType.parse(json);
  21278. } else {
  21279. // by default, we assume a constructor compatible with the base
  21280. return new trackType(json.name, json.times, json.values, json.interpolation);
  21281. }
  21282. }
  21283. Object.assign(AnimationClip, {
  21284. parse: function (json) {
  21285. var tracks = [],
  21286. jsonTracks = json.tracks,
  21287. frameTime = 1.0 / (json.fps || 1.0);
  21288. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  21289. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21290. }
  21291. return new AnimationClip(json.name, json.duration, tracks);
  21292. },
  21293. toJSON: function (clip) {
  21294. var tracks = [],
  21295. clipTracks = clip.tracks;
  21296. var json = {
  21297. 'name': clip.name,
  21298. 'duration': clip.duration,
  21299. 'tracks': tracks,
  21300. 'uuid': clip.uuid
  21301. };
  21302. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  21303. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21304. }
  21305. return json;
  21306. },
  21307. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  21308. var numMorphTargets = morphTargetSequence.length;
  21309. var tracks = [];
  21310. for (var i = 0; i < numMorphTargets; i++) {
  21311. var times = [];
  21312. var values = [];
  21313. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21314. values.push(0, 1, 0);
  21315. var order = AnimationUtils.getKeyframeOrder(times);
  21316. times = AnimationUtils.sortedArray(times, 1, order);
  21317. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21318. // last frame as well for perfect loop.
  21319. if (!noLoop && times[0] === 0) {
  21320. times.push(numMorphTargets);
  21321. values.push(values[0]);
  21322. }
  21323. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21324. }
  21325. return new AnimationClip(name, -1, tracks);
  21326. },
  21327. findByName: function (objectOrClipArray, name) {
  21328. var clipArray = objectOrClipArray;
  21329. if (!Array.isArray(objectOrClipArray)) {
  21330. var o = objectOrClipArray;
  21331. clipArray = o.geometry && o.geometry.animations || o.animations;
  21332. }
  21333. for (var i = 0; i < clipArray.length; i++) {
  21334. if (clipArray[i].name === name) {
  21335. return clipArray[i];
  21336. }
  21337. }
  21338. return null;
  21339. },
  21340. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  21341. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21342. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21343. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21344. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21345. for (var i = 0, il = morphTargets.length; i < il; i++) {
  21346. var morphTarget = morphTargets[i];
  21347. var parts = morphTarget.name.match(pattern);
  21348. if (parts && parts.length > 1) {
  21349. var name = parts[1];
  21350. var animationMorphTargets = animationToMorphTargets[name];
  21351. if (!animationMorphTargets) {
  21352. animationToMorphTargets[name] = animationMorphTargets = [];
  21353. }
  21354. animationMorphTargets.push(morphTarget);
  21355. }
  21356. }
  21357. var clips = [];
  21358. for (var name in animationToMorphTargets) {
  21359. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21360. }
  21361. return clips;
  21362. },
  21363. // parse the animation.hierarchy format
  21364. parseAnimation: function (animation, bones) {
  21365. if (!animation) {
  21366. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21367. return null;
  21368. }
  21369. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21370. // only return track if there are actually keys.
  21371. if (animationKeys.length !== 0) {
  21372. var times = [];
  21373. var values = [];
  21374. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21375. if (times.length !== 0) {
  21376. destTracks.push(new trackType(trackName, times, values));
  21377. }
  21378. }
  21379. };
  21380. var tracks = [];
  21381. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  21382. var duration = animation.length || -1;
  21383. var fps = animation.fps || 30;
  21384. var hierarchyTracks = animation.hierarchy || [];
  21385. for (var h = 0; h < hierarchyTracks.length; h++) {
  21386. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21387. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21388. if (animationKeys[0].morphTargets) {
  21389. // figure out all morph targets used in this track
  21390. var morphTargetNames = {};
  21391. for (var k = 0; k < animationKeys.length; k++) {
  21392. if (animationKeys[k].morphTargets) {
  21393. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21394. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21395. }
  21396. }
  21397. } // create a track for each morph target with all zero
  21398. // morphTargetInfluences except for the keys in which
  21399. // the morphTarget is named.
  21400. for (var morphTargetName in morphTargetNames) {
  21401. var times = [];
  21402. var values = [];
  21403. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21404. var animationKey = animationKeys[k];
  21405. times.push(animationKey.time);
  21406. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21407. }
  21408. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21409. }
  21410. duration = morphTargetNames.length * (fps || 1.0);
  21411. } else {
  21412. // ...assume skeletal animation
  21413. var boneName = '.bones[' + bones[h].name + ']';
  21414. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21415. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21416. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21417. }
  21418. }
  21419. if (tracks.length === 0) {
  21420. return null;
  21421. }
  21422. var clip = new AnimationClip(clipName, duration, tracks);
  21423. return clip;
  21424. }
  21425. });
  21426. Object.assign(AnimationClip.prototype, {
  21427. resetDuration: function () {
  21428. var tracks = this.tracks,
  21429. duration = 0;
  21430. for (var i = 0, n = tracks.length; i !== n; ++i) {
  21431. var track = this.tracks[i];
  21432. duration = Math.max(duration, track.times[track.times.length - 1]);
  21433. }
  21434. this.duration = duration;
  21435. return this;
  21436. },
  21437. trim: function () {
  21438. for (var i = 0; i < this.tracks.length; i++) {
  21439. this.tracks[i].trim(0, this.duration);
  21440. }
  21441. return this;
  21442. },
  21443. validate: function () {
  21444. var valid = true;
  21445. for (var i = 0; i < this.tracks.length; i++) {
  21446. valid = valid && this.tracks[i].validate();
  21447. }
  21448. return valid;
  21449. },
  21450. optimize: function () {
  21451. for (var i = 0; i < this.tracks.length; i++) {
  21452. this.tracks[i].optimize();
  21453. }
  21454. return this;
  21455. },
  21456. clone: function () {
  21457. var tracks = [];
  21458. for (var i = 0; i < this.tracks.length; i++) {
  21459. tracks.push(this.tracks[i].clone());
  21460. }
  21461. return new AnimationClip(this.name, this.duration, tracks);
  21462. }
  21463. });
  21464. /**
  21465. * @author mrdoob / http://mrdoob.com/
  21466. */
  21467. var Cache = {
  21468. enabled: false,
  21469. files: {},
  21470. add: function (key, file) {
  21471. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21472. this.files[key] = file;
  21473. },
  21474. get: function (key) {
  21475. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21476. return this.files[key];
  21477. },
  21478. remove: function (key) {
  21479. delete this.files[key];
  21480. },
  21481. clear: function () {
  21482. this.files = {};
  21483. }
  21484. };
  21485. /**
  21486. * @author mrdoob / http://mrdoob.com/
  21487. */
  21488. exports.Cache = Cache;
  21489. function LoadingManager(onLoad, onProgress, onError) {
  21490. var scope = this;
  21491. var isLoading = false;
  21492. var itemsLoaded = 0;
  21493. var itemsTotal = 0;
  21494. var urlModifier = undefined;
  21495. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21496. // in the constructor
  21497. this.onStart = undefined;
  21498. this.onLoad = onLoad;
  21499. this.onProgress = onProgress;
  21500. this.onError = onError;
  21501. this.itemStart = function (url) {
  21502. itemsTotal++;
  21503. if (isLoading === false) {
  21504. if (scope.onStart !== undefined) {
  21505. scope.onStart(url, itemsLoaded, itemsTotal);
  21506. }
  21507. }
  21508. isLoading = true;
  21509. };
  21510. this.itemEnd = function (url) {
  21511. itemsLoaded++;
  21512. if (scope.onProgress !== undefined) {
  21513. scope.onProgress(url, itemsLoaded, itemsTotal);
  21514. }
  21515. if (itemsLoaded === itemsTotal) {
  21516. isLoading = false;
  21517. if (scope.onLoad !== undefined) {
  21518. scope.onLoad();
  21519. }
  21520. }
  21521. };
  21522. this.itemError = function (url) {
  21523. if (scope.onError !== undefined) {
  21524. scope.onError(url);
  21525. }
  21526. };
  21527. this.resolveURL = function (url) {
  21528. if (urlModifier) {
  21529. return urlModifier(url);
  21530. }
  21531. return url;
  21532. };
  21533. this.setURLModifier = function (transform) {
  21534. urlModifier = transform;
  21535. return this;
  21536. };
  21537. this.addHandler = function (regex, loader) {
  21538. handlers.push(regex, loader);
  21539. return this;
  21540. };
  21541. this.removeHandler = function (regex) {
  21542. var index = handlers.indexOf(regex);
  21543. if (index !== -1) {
  21544. handlers.splice(index, 2);
  21545. }
  21546. return this;
  21547. };
  21548. this.getHandler = function (file) {
  21549. for (var i = 0, l = handlers.length; i < l; i += 2) {
  21550. var regex = handlers[i];
  21551. var loader = handlers[i + 1];
  21552. if (regex.global) regex.lastIndex = 0; // see #17920
  21553. if (regex.test(file)) {
  21554. return loader;
  21555. }
  21556. }
  21557. return null;
  21558. };
  21559. }
  21560. var DefaultLoadingManager = new LoadingManager();
  21561. /**
  21562. * @author alteredq / http://alteredqualia.com/
  21563. */
  21564. exports.DefaultLoadingManager = DefaultLoadingManager;
  21565. function Loader(manager) {
  21566. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21567. this.crossOrigin = 'anonymous';
  21568. this.path = '';
  21569. this.resourcePath = '';
  21570. }
  21571. Object.assign(Loader.prototype, {
  21572. load: function ()
  21573. /* url, onLoad, onProgress, onError */
  21574. {},
  21575. parse: function ()
  21576. /* data */
  21577. {},
  21578. setCrossOrigin: function (crossOrigin) {
  21579. this.crossOrigin = crossOrigin;
  21580. return this;
  21581. },
  21582. setPath: function (path) {
  21583. this.path = path;
  21584. return this;
  21585. },
  21586. setResourcePath: function (resourcePath) {
  21587. this.resourcePath = resourcePath;
  21588. return this;
  21589. }
  21590. });
  21591. /**
  21592. * @author mrdoob / http://mrdoob.com/
  21593. */
  21594. var loading = {};
  21595. function FileLoader(manager) {
  21596. Loader.call(this, manager);
  21597. }
  21598. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21599. constructor: FileLoader,
  21600. load: function (url, onLoad, onProgress, onError) {
  21601. if (url === undefined) url = '';
  21602. if (this.path !== undefined) url = this.path + url;
  21603. url = this.manager.resolveURL(url);
  21604. var scope = this;
  21605. var cached = Cache.get(url);
  21606. if (cached !== undefined) {
  21607. scope.manager.itemStart(url);
  21608. setTimeout(function () {
  21609. if (onLoad) onLoad(cached);
  21610. scope.manager.itemEnd(url);
  21611. }, 0);
  21612. return cached;
  21613. } // Check if request is duplicate
  21614. if (loading[url] !== undefined) {
  21615. loading[url].push({
  21616. onLoad: onLoad,
  21617. onProgress: onProgress,
  21618. onError: onError
  21619. });
  21620. return;
  21621. } // Check for data: URI
  21622. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21623. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21624. if (dataUriRegexResult) {
  21625. var mimeType = dataUriRegexResult[1];
  21626. var isBase64 = !!dataUriRegexResult[2];
  21627. var data = dataUriRegexResult[3];
  21628. data = decodeURIComponent(data);
  21629. if (isBase64) data = atob(data);
  21630. try {
  21631. var response;
  21632. var responseType = (this.responseType || '').toLowerCase();
  21633. switch (responseType) {
  21634. case 'arraybuffer':
  21635. case 'blob':
  21636. var view = new Uint8Array(data.length);
  21637. for (var i = 0; i < data.length; i++) {
  21638. view[i] = data.charCodeAt(i);
  21639. }
  21640. if (responseType === 'blob') {
  21641. response = new Blob([view.buffer], {
  21642. type: mimeType
  21643. });
  21644. } else {
  21645. response = view.buffer;
  21646. }
  21647. break;
  21648. case 'document':
  21649. var parser = new DOMParser();
  21650. response = parser.parseFromString(data, mimeType);
  21651. break;
  21652. case 'json':
  21653. response = JSON.parse(data);
  21654. break;
  21655. default:
  21656. // 'text' or other
  21657. response = data;
  21658. break;
  21659. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21660. setTimeout(function () {
  21661. if (onLoad) onLoad(response);
  21662. scope.manager.itemEnd(url);
  21663. }, 0);
  21664. } catch (error) {
  21665. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21666. setTimeout(function () {
  21667. if (onError) onError(error);
  21668. scope.manager.itemError(url);
  21669. scope.manager.itemEnd(url);
  21670. }, 0);
  21671. }
  21672. } else {
  21673. // Initialise array for duplicate requests
  21674. loading[url] = [];
  21675. loading[url].push({
  21676. onLoad: onLoad,
  21677. onProgress: onProgress,
  21678. onError: onError
  21679. });
  21680. var request = new XMLHttpRequest();
  21681. request.open('GET', url, true);
  21682. request.addEventListener('load', function (event) {
  21683. var response = this.response;
  21684. var callbacks = loading[url];
  21685. delete loading[url];
  21686. if (this.status === 200 || this.status === 0) {
  21687. // Some browsers return HTTP Status 0 when using non-http protocol
  21688. // e.g. 'file://' or 'data://'. Handle as success.
  21689. 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
  21690. // error response bodies as proper responses to requests.
  21691. Cache.add(url, response);
  21692. for (var i = 0, il = callbacks.length; i < il; i++) {
  21693. var callback = callbacks[i];
  21694. if (callback.onLoad) callback.onLoad(response);
  21695. }
  21696. scope.manager.itemEnd(url);
  21697. } else {
  21698. for (var i = 0, il = callbacks.length; i < il; i++) {
  21699. var callback = callbacks[i];
  21700. if (callback.onError) callback.onError(event);
  21701. }
  21702. scope.manager.itemError(url);
  21703. scope.manager.itemEnd(url);
  21704. }
  21705. }, false);
  21706. request.addEventListener('progress', function (event) {
  21707. var callbacks = loading[url];
  21708. for (var i = 0, il = callbacks.length; i < il; i++) {
  21709. var callback = callbacks[i];
  21710. if (callback.onProgress) callback.onProgress(event);
  21711. }
  21712. }, false);
  21713. request.addEventListener('error', function (event) {
  21714. var callbacks = loading[url];
  21715. delete loading[url];
  21716. for (var i = 0, il = callbacks.length; i < il; i++) {
  21717. var callback = callbacks[i];
  21718. if (callback.onError) callback.onError(event);
  21719. }
  21720. scope.manager.itemError(url);
  21721. scope.manager.itemEnd(url);
  21722. }, false);
  21723. request.addEventListener('abort', function (event) {
  21724. var callbacks = loading[url];
  21725. delete loading[url];
  21726. for (var i = 0, il = callbacks.length; i < il; i++) {
  21727. var callback = callbacks[i];
  21728. if (callback.onError) callback.onError(event);
  21729. }
  21730. scope.manager.itemError(url);
  21731. scope.manager.itemEnd(url);
  21732. }, false);
  21733. if (this.responseType !== undefined) request.responseType = this.responseType;
  21734. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21735. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21736. for (var header in this.requestHeader) {
  21737. request.setRequestHeader(header, this.requestHeader[header]);
  21738. }
  21739. request.send(null);
  21740. }
  21741. scope.manager.itemStart(url);
  21742. return request;
  21743. },
  21744. setResponseType: function (value) {
  21745. this.responseType = value;
  21746. return this;
  21747. },
  21748. setWithCredentials: function (value) {
  21749. this.withCredentials = value;
  21750. return this;
  21751. },
  21752. setMimeType: function (value) {
  21753. this.mimeType = value;
  21754. return this;
  21755. },
  21756. setRequestHeader: function (value) {
  21757. this.requestHeader = value;
  21758. return this;
  21759. }
  21760. });
  21761. /**
  21762. * @author bhouston / http://clara.io/
  21763. */
  21764. function AnimationLoader(manager) {
  21765. Loader.call(this, manager);
  21766. }
  21767. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21768. constructor: AnimationLoader,
  21769. load: function (url, onLoad, onProgress, onError) {
  21770. var scope = this;
  21771. var loader = new FileLoader(scope.manager);
  21772. loader.setPath(scope.path);
  21773. loader.load(url, function (text) {
  21774. onLoad(scope.parse(JSON.parse(text)));
  21775. }, onProgress, onError);
  21776. },
  21777. parse: function (json) {
  21778. var animations = [];
  21779. for (var i = 0; i < json.length; i++) {
  21780. var clip = AnimationClip.parse(json[i]);
  21781. animations.push(clip);
  21782. }
  21783. return animations;
  21784. }
  21785. });
  21786. /**
  21787. * @author mrdoob / http://mrdoob.com/
  21788. *
  21789. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21790. *
  21791. * Sub classes have to implement the parse() method which will be used in load().
  21792. */
  21793. function CompressedTextureLoader(manager) {
  21794. Loader.call(this, manager);
  21795. }
  21796. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21797. constructor: CompressedTextureLoader,
  21798. load: function (url, onLoad, onProgress, onError) {
  21799. var scope = this;
  21800. var images = [];
  21801. var texture = new CompressedTexture();
  21802. texture.image = images;
  21803. var loader = new FileLoader(this.manager);
  21804. loader.setPath(this.path);
  21805. loader.setResponseType('arraybuffer');
  21806. function loadTexture(i) {
  21807. loader.load(url[i], function (buffer) {
  21808. var texDatas = scope.parse(buffer, true);
  21809. images[i] = {
  21810. width: texDatas.width,
  21811. height: texDatas.height,
  21812. format: texDatas.format,
  21813. mipmaps: texDatas.mipmaps
  21814. };
  21815. loaded += 1;
  21816. if (loaded === 6) {
  21817. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21818. texture.format = texDatas.format;
  21819. texture.needsUpdate = true;
  21820. if (onLoad) onLoad(texture);
  21821. }
  21822. }, onProgress, onError);
  21823. }
  21824. if (Array.isArray(url)) {
  21825. var loaded = 0;
  21826. for (var i = 0, il = url.length; i < il; ++i) {
  21827. loadTexture(i);
  21828. }
  21829. } else {
  21830. // compressed cubemap texture stored in a single DDS file
  21831. loader.load(url, function (buffer) {
  21832. var texDatas = scope.parse(buffer, true);
  21833. if (texDatas.isCubemap) {
  21834. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21835. for (var f = 0; f < faces; f++) {
  21836. images[f] = {
  21837. mipmaps: []
  21838. };
  21839. for (var i = 0; i < texDatas.mipmapCount; i++) {
  21840. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21841. images[f].format = texDatas.format;
  21842. images[f].width = texDatas.width;
  21843. images[f].height = texDatas.height;
  21844. }
  21845. }
  21846. } else {
  21847. texture.image.width = texDatas.width;
  21848. texture.image.height = texDatas.height;
  21849. texture.mipmaps = texDatas.mipmaps;
  21850. }
  21851. if (texDatas.mipmapCount === 1) {
  21852. texture.minFilter = LinearFilter;
  21853. }
  21854. texture.format = texDatas.format;
  21855. texture.needsUpdate = true;
  21856. if (onLoad) onLoad(texture);
  21857. }, onProgress, onError);
  21858. }
  21859. return texture;
  21860. }
  21861. });
  21862. /**
  21863. * @author Nikos M. / https://github.com/foo123/
  21864. *
  21865. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21866. *
  21867. * Sub classes have to implement the parse() method which will be used in load().
  21868. */
  21869. function DataTextureLoader(manager) {
  21870. Loader.call(this, manager);
  21871. }
  21872. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21873. constructor: DataTextureLoader,
  21874. load: function (url, onLoad, onProgress, onError) {
  21875. var scope = this;
  21876. var texture = new DataTexture();
  21877. var loader = new FileLoader(this.manager);
  21878. loader.setResponseType('arraybuffer');
  21879. loader.setPath(this.path);
  21880. loader.load(url, function (buffer) {
  21881. var texData = scope.parse(buffer);
  21882. if (!texData) return;
  21883. if (texData.image !== undefined) {
  21884. texture.image = texData.image;
  21885. } else if (texData.data !== undefined) {
  21886. texture.image.width = texData.width;
  21887. texture.image.height = texData.height;
  21888. texture.image.data = texData.data;
  21889. }
  21890. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21891. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21892. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21893. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  21894. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21895. if (texData.format !== undefined) {
  21896. texture.format = texData.format;
  21897. }
  21898. if (texData.type !== undefined) {
  21899. texture.type = texData.type;
  21900. }
  21901. if (texData.mipmaps !== undefined) {
  21902. texture.mipmaps = texData.mipmaps;
  21903. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  21904. }
  21905. if (texData.mipmapCount === 1) {
  21906. texture.minFilter = LinearFilter;
  21907. }
  21908. texture.needsUpdate = true;
  21909. if (onLoad) onLoad(texture, texData);
  21910. }, onProgress, onError);
  21911. return texture;
  21912. }
  21913. });
  21914. /**
  21915. * @author mrdoob / http://mrdoob.com/
  21916. */
  21917. function ImageLoader(manager) {
  21918. Loader.call(this, manager);
  21919. }
  21920. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21921. constructor: ImageLoader,
  21922. load: function (url, onLoad, onProgress, onError) {
  21923. if (this.path !== undefined) url = this.path + url;
  21924. url = this.manager.resolveURL(url);
  21925. var scope = this;
  21926. var cached = Cache.get(url);
  21927. if (cached !== undefined) {
  21928. scope.manager.itemStart(url);
  21929. setTimeout(function () {
  21930. if (onLoad) onLoad(cached);
  21931. scope.manager.itemEnd(url);
  21932. }, 0);
  21933. return cached;
  21934. }
  21935. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21936. function onImageLoad() {
  21937. image.removeEventListener('load', onImageLoad, false);
  21938. image.removeEventListener('error', onImageError, false);
  21939. Cache.add(url, this);
  21940. if (onLoad) onLoad(this);
  21941. scope.manager.itemEnd(url);
  21942. }
  21943. function onImageError(event) {
  21944. image.removeEventListener('load', onImageLoad, false);
  21945. image.removeEventListener('error', onImageError, false);
  21946. if (onError) onError(event);
  21947. scope.manager.itemError(url);
  21948. scope.manager.itemEnd(url);
  21949. }
  21950. image.addEventListener('load', onImageLoad, false);
  21951. image.addEventListener('error', onImageError, false);
  21952. if (url.substr(0, 5) !== 'data:') {
  21953. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21954. }
  21955. scope.manager.itemStart(url);
  21956. image.src = url;
  21957. return image;
  21958. }
  21959. });
  21960. /**
  21961. * @author mrdoob / http://mrdoob.com/
  21962. */
  21963. function CubeTextureLoader(manager) {
  21964. Loader.call(this, manager);
  21965. }
  21966. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21967. constructor: CubeTextureLoader,
  21968. load: function (urls, onLoad, onProgress, onError) {
  21969. var texture = new CubeTexture();
  21970. var loader = new ImageLoader(this.manager);
  21971. loader.setCrossOrigin(this.crossOrigin);
  21972. loader.setPath(this.path);
  21973. var loaded = 0;
  21974. function loadTexture(i) {
  21975. loader.load(urls[i], function (image) {
  21976. texture.images[i] = image;
  21977. loaded++;
  21978. if (loaded === 6) {
  21979. texture.needsUpdate = true;
  21980. if (onLoad) onLoad(texture);
  21981. }
  21982. }, undefined, onError);
  21983. }
  21984. for (var i = 0; i < urls.length; ++i) {
  21985. loadTexture(i);
  21986. }
  21987. return texture;
  21988. }
  21989. });
  21990. /**
  21991. * @author mrdoob / http://mrdoob.com/
  21992. */
  21993. function TextureLoader(manager) {
  21994. Loader.call(this, manager);
  21995. }
  21996. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21997. constructor: TextureLoader,
  21998. load: function (url, onLoad, onProgress, onError) {
  21999. var texture = new Texture();
  22000. var loader = new ImageLoader(this.manager);
  22001. loader.setCrossOrigin(this.crossOrigin);
  22002. loader.setPath(this.path);
  22003. loader.load(url, function (image) {
  22004. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22005. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22006. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22007. texture.needsUpdate = true;
  22008. if (onLoad !== undefined) {
  22009. onLoad(texture);
  22010. }
  22011. }, onProgress, onError);
  22012. return texture;
  22013. }
  22014. });
  22015. /**
  22016. * @author zz85 / http://www.lab4games.net/zz85/blog
  22017. * Extensible curve object
  22018. *
  22019. * Some common of curve methods:
  22020. * .getPoint( t, optionalTarget ), .getTangent( t )
  22021. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22022. * .getPoints(), .getSpacedPoints()
  22023. * .getLength()
  22024. * .updateArcLengths()
  22025. *
  22026. * This following curves inherit from THREE.Curve:
  22027. *
  22028. * -- 2D curves --
  22029. * THREE.ArcCurve
  22030. * THREE.CubicBezierCurve
  22031. * THREE.EllipseCurve
  22032. * THREE.LineCurve
  22033. * THREE.QuadraticBezierCurve
  22034. * THREE.SplineCurve
  22035. *
  22036. * -- 3D curves --
  22037. * THREE.CatmullRomCurve3
  22038. * THREE.CubicBezierCurve3
  22039. * THREE.LineCurve3
  22040. * THREE.QuadraticBezierCurve3
  22041. *
  22042. * A series of curves can be represented as a THREE.CurvePath.
  22043. *
  22044. **/
  22045. /**************************************************************
  22046. * Abstract Curve base class
  22047. **************************************************************/
  22048. function Curve() {
  22049. this.type = 'Curve';
  22050. this.arcLengthDivisions = 200;
  22051. }
  22052. Object.assign(Curve.prototype, {
  22053. // Virtual base class method to overwrite and implement in subclasses
  22054. // - t [0 .. 1]
  22055. getPoint: function ()
  22056. /* t, optionalTarget */
  22057. {
  22058. console.warn('THREE.Curve: .getPoint() not implemented.');
  22059. return null;
  22060. },
  22061. // Get point at relative position in curve according to arc length
  22062. // - u [0 .. 1]
  22063. getPointAt: function (u, optionalTarget) {
  22064. var t = this.getUtoTmapping(u);
  22065. return this.getPoint(t, optionalTarget);
  22066. },
  22067. // Get sequence of points using getPoint( t )
  22068. getPoints: function (divisions) {
  22069. if (divisions === undefined) divisions = 5;
  22070. var points = [];
  22071. for (var d = 0; d <= divisions; d++) {
  22072. points.push(this.getPoint(d / divisions));
  22073. }
  22074. return points;
  22075. },
  22076. // Get sequence of points using getPointAt( u )
  22077. getSpacedPoints: function (divisions) {
  22078. if (divisions === undefined) divisions = 5;
  22079. var points = [];
  22080. for (var d = 0; d <= divisions; d++) {
  22081. points.push(this.getPointAt(d / divisions));
  22082. }
  22083. return points;
  22084. },
  22085. // Get total curve arc length
  22086. getLength: function () {
  22087. var lengths = this.getLengths();
  22088. return lengths[lengths.length - 1];
  22089. },
  22090. // Get list of cumulative segment lengths
  22091. getLengths: function (divisions) {
  22092. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22093. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22094. return this.cacheArcLengths;
  22095. }
  22096. this.needsUpdate = false;
  22097. var cache = [];
  22098. var current,
  22099. last = this.getPoint(0);
  22100. var p,
  22101. sum = 0;
  22102. cache.push(0);
  22103. for (p = 1; p <= divisions; p++) {
  22104. current = this.getPoint(p / divisions);
  22105. sum += current.distanceTo(last);
  22106. cache.push(sum);
  22107. last = current;
  22108. }
  22109. this.cacheArcLengths = cache;
  22110. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22111. },
  22112. updateArcLengths: function () {
  22113. this.needsUpdate = true;
  22114. this.getLengths();
  22115. },
  22116. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22117. getUtoTmapping: function (u, distance) {
  22118. var arcLengths = this.getLengths();
  22119. var i = 0,
  22120. il = arcLengths.length;
  22121. var targetArcLength; // The targeted u distance value to get
  22122. if (distance) {
  22123. targetArcLength = distance;
  22124. } else {
  22125. targetArcLength = u * arcLengths[il - 1];
  22126. } // binary search for the index with largest value smaller than target u distance
  22127. var low = 0,
  22128. high = il - 1,
  22129. comparison;
  22130. while (low <= high) {
  22131. 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
  22132. comparison = arcLengths[i] - targetArcLength;
  22133. if (comparison < 0) {
  22134. low = i + 1;
  22135. } else if (comparison > 0) {
  22136. high = i - 1;
  22137. } else {
  22138. high = i;
  22139. break; // DONE
  22140. }
  22141. }
  22142. i = high;
  22143. if (arcLengths[i] === targetArcLength) {
  22144. return i / (il - 1);
  22145. } // we could get finer grain at lengths, or use simple interpolation between two points
  22146. var lengthBefore = arcLengths[i];
  22147. var lengthAfter = arcLengths[i + 1];
  22148. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22149. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22150. var t = (i + segmentFraction) / (il - 1);
  22151. return t;
  22152. },
  22153. // Returns a unit vector tangent at t
  22154. // In case any sub curve does not implement its tangent derivation,
  22155. // 2 points a small delta apart will be used to find its gradient
  22156. // which seems to give a reasonable approximation
  22157. getTangent: function (t) {
  22158. var delta = 0.0001;
  22159. var t1 = t - delta;
  22160. var t2 = t + delta; // Capping in case of danger
  22161. if (t1 < 0) t1 = 0;
  22162. if (t2 > 1) t2 = 1;
  22163. var pt1 = this.getPoint(t1);
  22164. var pt2 = this.getPoint(t2);
  22165. var vec = pt2.clone().sub(pt1);
  22166. return vec.normalize();
  22167. },
  22168. getTangentAt: function (u) {
  22169. var t = this.getUtoTmapping(u);
  22170. return this.getTangent(t);
  22171. },
  22172. computeFrenetFrames: function (segments, closed) {
  22173. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22174. var normal = new Vector3();
  22175. var tangents = [];
  22176. var normals = [];
  22177. var binormals = [];
  22178. var vec = new Vector3();
  22179. var mat = new Matrix4();
  22180. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22181. for (i = 0; i <= segments; i++) {
  22182. u = i / segments;
  22183. tangents[i] = this.getTangentAt(u);
  22184. tangents[i].normalize();
  22185. } // select an initial normal vector perpendicular to the first tangent vector,
  22186. // and in the direction of the minimum tangent xyz component
  22187. normals[0] = new Vector3();
  22188. binormals[0] = new Vector3();
  22189. var min = Number.MAX_VALUE;
  22190. var tx = Math.abs(tangents[0].x);
  22191. var ty = Math.abs(tangents[0].y);
  22192. var tz = Math.abs(tangents[0].z);
  22193. if (tx <= min) {
  22194. min = tx;
  22195. normal.set(1, 0, 0);
  22196. }
  22197. if (ty <= min) {
  22198. min = ty;
  22199. normal.set(0, 1, 0);
  22200. }
  22201. if (tz <= min) {
  22202. normal.set(0, 0, 1);
  22203. }
  22204. vec.crossVectors(tangents[0], normal).normalize();
  22205. normals[0].crossVectors(tangents[0], vec);
  22206. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22207. for (i = 1; i <= segments; i++) {
  22208. normals[i] = normals[i - 1].clone();
  22209. binormals[i] = binormals[i - 1].clone();
  22210. vec.crossVectors(tangents[i - 1], tangents[i]);
  22211. if (vec.length() > Number.EPSILON) {
  22212. vec.normalize();
  22213. theta = Math.acos(MathUtils.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22214. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22215. }
  22216. binormals[i].crossVectors(tangents[i], normals[i]);
  22217. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22218. if (closed === true) {
  22219. theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  22220. theta /= segments;
  22221. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22222. theta = -theta;
  22223. }
  22224. for (i = 1; i <= segments; i++) {
  22225. // twist a little...
  22226. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22227. binormals[i].crossVectors(tangents[i], normals[i]);
  22228. }
  22229. }
  22230. return {
  22231. tangents: tangents,
  22232. normals: normals,
  22233. binormals: binormals
  22234. };
  22235. },
  22236. clone: function () {
  22237. return new this.constructor().copy(this);
  22238. },
  22239. copy: function (source) {
  22240. this.arcLengthDivisions = source.arcLengthDivisions;
  22241. return this;
  22242. },
  22243. toJSON: function () {
  22244. var data = {
  22245. metadata: {
  22246. version: 4.5,
  22247. type: 'Curve',
  22248. generator: 'Curve.toJSON'
  22249. }
  22250. };
  22251. data.arcLengthDivisions = this.arcLengthDivisions;
  22252. data.type = this.type;
  22253. return data;
  22254. },
  22255. fromJSON: function (json) {
  22256. this.arcLengthDivisions = json.arcLengthDivisions;
  22257. return this;
  22258. }
  22259. });
  22260. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22261. Curve.call(this);
  22262. this.type = 'EllipseCurve';
  22263. this.aX = aX || 0;
  22264. this.aY = aY || 0;
  22265. this.xRadius = xRadius || 1;
  22266. this.yRadius = yRadius || 1;
  22267. this.aStartAngle = aStartAngle || 0;
  22268. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22269. this.aClockwise = aClockwise || false;
  22270. this.aRotation = aRotation || 0;
  22271. }
  22272. EllipseCurve.prototype = Object.create(Curve.prototype);
  22273. EllipseCurve.prototype.constructor = EllipseCurve;
  22274. EllipseCurve.prototype.isEllipseCurve = true;
  22275. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  22276. var point = optionalTarget || new Vector2();
  22277. var twoPi = Math.PI * 2;
  22278. var deltaAngle = this.aEndAngle - this.aStartAngle;
  22279. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  22280. while (deltaAngle < 0) deltaAngle += twoPi;
  22281. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  22282. if (deltaAngle < Number.EPSILON) {
  22283. if (samePoints) {
  22284. deltaAngle = 0;
  22285. } else {
  22286. deltaAngle = twoPi;
  22287. }
  22288. }
  22289. if (this.aClockwise === true && !samePoints) {
  22290. if (deltaAngle === twoPi) {
  22291. deltaAngle = -twoPi;
  22292. } else {
  22293. deltaAngle = deltaAngle - twoPi;
  22294. }
  22295. }
  22296. var angle = this.aStartAngle + t * deltaAngle;
  22297. var x = this.aX + this.xRadius * Math.cos(angle);
  22298. var y = this.aY + this.yRadius * Math.sin(angle);
  22299. if (this.aRotation !== 0) {
  22300. var cos = Math.cos(this.aRotation);
  22301. var sin = Math.sin(this.aRotation);
  22302. var tx = x - this.aX;
  22303. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  22304. x = tx * cos - ty * sin + this.aX;
  22305. y = tx * sin + ty * cos + this.aY;
  22306. }
  22307. return point.set(x, y);
  22308. };
  22309. EllipseCurve.prototype.copy = function (source) {
  22310. Curve.prototype.copy.call(this, source);
  22311. this.aX = source.aX;
  22312. this.aY = source.aY;
  22313. this.xRadius = source.xRadius;
  22314. this.yRadius = source.yRadius;
  22315. this.aStartAngle = source.aStartAngle;
  22316. this.aEndAngle = source.aEndAngle;
  22317. this.aClockwise = source.aClockwise;
  22318. this.aRotation = source.aRotation;
  22319. return this;
  22320. };
  22321. EllipseCurve.prototype.toJSON = function () {
  22322. var data = Curve.prototype.toJSON.call(this);
  22323. data.aX = this.aX;
  22324. data.aY = this.aY;
  22325. data.xRadius = this.xRadius;
  22326. data.yRadius = this.yRadius;
  22327. data.aStartAngle = this.aStartAngle;
  22328. data.aEndAngle = this.aEndAngle;
  22329. data.aClockwise = this.aClockwise;
  22330. data.aRotation = this.aRotation;
  22331. return data;
  22332. };
  22333. EllipseCurve.prototype.fromJSON = function (json) {
  22334. Curve.prototype.fromJSON.call(this, json);
  22335. this.aX = json.aX;
  22336. this.aY = json.aY;
  22337. this.xRadius = json.xRadius;
  22338. this.yRadius = json.yRadius;
  22339. this.aStartAngle = json.aStartAngle;
  22340. this.aEndAngle = json.aEndAngle;
  22341. this.aClockwise = json.aClockwise;
  22342. this.aRotation = json.aRotation;
  22343. return this;
  22344. };
  22345. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22346. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22347. this.type = 'ArcCurve';
  22348. }
  22349. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  22350. ArcCurve.prototype.constructor = ArcCurve;
  22351. ArcCurve.prototype.isArcCurve = true;
  22352. /**
  22353. * @author zz85 https://github.com/zz85
  22354. *
  22355. * Centripetal CatmullRom Curve - which is useful for avoiding
  22356. * cusps and self-intersections in non-uniform catmull rom curves.
  22357. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22358. *
  22359. * curve.type accepts centripetal(default), chordal and catmullrom
  22360. * curve.tension is used for catmullrom which defaults to 0.5
  22361. */
  22362. /*
  22363. Based on an optimized c++ solution in
  22364. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22365. - http://ideone.com/NoEbVM
  22366. This CubicPoly class could be used for reusing some variables and calculations,
  22367. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22368. which can be placed in CurveUtils.
  22369. */
  22370. function CubicPoly() {
  22371. var c0 = 0,
  22372. c1 = 0,
  22373. c2 = 0,
  22374. c3 = 0;
  22375. /*
  22376. * Compute coefficients for a cubic polynomial
  22377. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22378. * such that
  22379. * p(0) = x0, p(1) = x1
  22380. * and
  22381. * p'(0) = t0, p'(1) = t1.
  22382. */
  22383. function init(x0, x1, t0, t1) {
  22384. c0 = x0;
  22385. c1 = t0;
  22386. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22387. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22388. }
  22389. return {
  22390. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22391. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22392. },
  22393. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22394. // compute tangents when parameterized in [t1,t2]
  22395. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22396. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22397. t1 *= dt1;
  22398. t2 *= dt1;
  22399. init(x1, x2, t1, t2);
  22400. },
  22401. calc: function (t) {
  22402. var t2 = t * t;
  22403. var t3 = t2 * t;
  22404. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22405. }
  22406. };
  22407. } //
  22408. var tmp = new Vector3();
  22409. var px = new CubicPoly(),
  22410. py = new CubicPoly(),
  22411. pz = new CubicPoly();
  22412. function CatmullRomCurve3(points, closed, curveType, tension) {
  22413. Curve.call(this);
  22414. this.type = 'CatmullRomCurve3';
  22415. this.points = points || [];
  22416. this.closed = closed || false;
  22417. this.curveType = curveType || 'centripetal';
  22418. this.tension = tension || 0.5;
  22419. }
  22420. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22421. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22422. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22423. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  22424. var point = optionalTarget || new Vector3();
  22425. var points = this.points;
  22426. var l = points.length;
  22427. var p = (l - (this.closed ? 0 : 1)) * t;
  22428. var intPoint = Math.floor(p);
  22429. var weight = p - intPoint;
  22430. if (this.closed) {
  22431. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22432. } else if (weight === 0 && intPoint === l - 1) {
  22433. intPoint = l - 2;
  22434. weight = 1;
  22435. }
  22436. var p0, p1, p2, p3; // 4 points
  22437. if (this.closed || intPoint > 0) {
  22438. p0 = points[(intPoint - 1) % l];
  22439. } else {
  22440. // extrapolate first point
  22441. tmp.subVectors(points[0], points[1]).add(points[0]);
  22442. p0 = tmp;
  22443. }
  22444. p1 = points[intPoint % l];
  22445. p2 = points[(intPoint + 1) % l];
  22446. if (this.closed || intPoint + 2 < l) {
  22447. p3 = points[(intPoint + 2) % l];
  22448. } else {
  22449. // extrapolate last point
  22450. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22451. p3 = tmp;
  22452. }
  22453. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22454. // init Centripetal / Chordal Catmull-Rom
  22455. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22456. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22457. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22458. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22459. if (dt1 < 1e-4) dt1 = 1.0;
  22460. if (dt0 < 1e-4) dt0 = dt1;
  22461. if (dt2 < 1e-4) dt2 = dt1;
  22462. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22463. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22464. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22465. } else if (this.curveType === 'catmullrom') {
  22466. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22467. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22468. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22469. }
  22470. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22471. return point;
  22472. };
  22473. CatmullRomCurve3.prototype.copy = function (source) {
  22474. Curve.prototype.copy.call(this, source);
  22475. this.points = [];
  22476. for (var i = 0, l = source.points.length; i < l; i++) {
  22477. var point = source.points[i];
  22478. this.points.push(point.clone());
  22479. }
  22480. this.closed = source.closed;
  22481. this.curveType = source.curveType;
  22482. this.tension = source.tension;
  22483. return this;
  22484. };
  22485. CatmullRomCurve3.prototype.toJSON = function () {
  22486. var data = Curve.prototype.toJSON.call(this);
  22487. data.points = [];
  22488. for (var i = 0, l = this.points.length; i < l; i++) {
  22489. var point = this.points[i];
  22490. data.points.push(point.toArray());
  22491. }
  22492. data.closed = this.closed;
  22493. data.curveType = this.curveType;
  22494. data.tension = this.tension;
  22495. return data;
  22496. };
  22497. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22498. Curve.prototype.fromJSON.call(this, json);
  22499. this.points = [];
  22500. for (var i = 0, l = json.points.length; i < l; i++) {
  22501. var point = json.points[i];
  22502. this.points.push(new Vector3().fromArray(point));
  22503. }
  22504. this.closed = json.closed;
  22505. this.curveType = json.curveType;
  22506. this.tension = json.tension;
  22507. return this;
  22508. };
  22509. /**
  22510. * @author zz85 / http://www.lab4games.net/zz85/blog
  22511. *
  22512. * Bezier Curves formulas obtained from
  22513. * http://en.wikipedia.org/wiki/Bézier_curve
  22514. */
  22515. function CatmullRom(t, p0, p1, p2, p3) {
  22516. var v0 = (p2 - p0) * 0.5;
  22517. var v1 = (p3 - p1) * 0.5;
  22518. var t2 = t * t;
  22519. var t3 = t * t2;
  22520. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22521. } //
  22522. function QuadraticBezierP0(t, p) {
  22523. var k = 1 - t;
  22524. return k * k * p;
  22525. }
  22526. function QuadraticBezierP1(t, p) {
  22527. return 2 * (1 - t) * t * p;
  22528. }
  22529. function QuadraticBezierP2(t, p) {
  22530. return t * t * p;
  22531. }
  22532. function QuadraticBezier(t, p0, p1, p2) {
  22533. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22534. } //
  22535. function CubicBezierP0(t, p) {
  22536. var k = 1 - t;
  22537. return k * k * k * p;
  22538. }
  22539. function CubicBezierP1(t, p) {
  22540. var k = 1 - t;
  22541. return 3 * k * k * t * p;
  22542. }
  22543. function CubicBezierP2(t, p) {
  22544. return 3 * (1 - t) * t * t * p;
  22545. }
  22546. function CubicBezierP3(t, p) {
  22547. return t * t * t * p;
  22548. }
  22549. function CubicBezier(t, p0, p1, p2, p3) {
  22550. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22551. }
  22552. function CubicBezierCurve(v0, v1, v2, v3) {
  22553. Curve.call(this);
  22554. this.type = 'CubicBezierCurve';
  22555. this.v0 = v0 || new Vector2();
  22556. this.v1 = v1 || new Vector2();
  22557. this.v2 = v2 || new Vector2();
  22558. this.v3 = v3 || new Vector2();
  22559. }
  22560. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22561. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22562. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22563. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22564. var point = optionalTarget || new Vector2();
  22565. var v0 = this.v0,
  22566. v1 = this.v1,
  22567. v2 = this.v2,
  22568. v3 = this.v3;
  22569. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22570. return point;
  22571. };
  22572. CubicBezierCurve.prototype.copy = function (source) {
  22573. Curve.prototype.copy.call(this, source);
  22574. this.v0.copy(source.v0);
  22575. this.v1.copy(source.v1);
  22576. this.v2.copy(source.v2);
  22577. this.v3.copy(source.v3);
  22578. return this;
  22579. };
  22580. CubicBezierCurve.prototype.toJSON = function () {
  22581. var data = Curve.prototype.toJSON.call(this);
  22582. data.v0 = this.v0.toArray();
  22583. data.v1 = this.v1.toArray();
  22584. data.v2 = this.v2.toArray();
  22585. data.v3 = this.v3.toArray();
  22586. return data;
  22587. };
  22588. CubicBezierCurve.prototype.fromJSON = function (json) {
  22589. Curve.prototype.fromJSON.call(this, json);
  22590. this.v0.fromArray(json.v0);
  22591. this.v1.fromArray(json.v1);
  22592. this.v2.fromArray(json.v2);
  22593. this.v3.fromArray(json.v3);
  22594. return this;
  22595. };
  22596. function CubicBezierCurve3(v0, v1, v2, v3) {
  22597. Curve.call(this);
  22598. this.type = 'CubicBezierCurve3';
  22599. this.v0 = v0 || new Vector3();
  22600. this.v1 = v1 || new Vector3();
  22601. this.v2 = v2 || new Vector3();
  22602. this.v3 = v3 || new Vector3();
  22603. }
  22604. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  22605. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22606. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22607. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22608. var point = optionalTarget || new Vector3();
  22609. var v0 = this.v0,
  22610. v1 = this.v1,
  22611. v2 = this.v2,
  22612. v3 = this.v3;
  22613. 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));
  22614. return point;
  22615. };
  22616. CubicBezierCurve3.prototype.copy = function (source) {
  22617. Curve.prototype.copy.call(this, source);
  22618. this.v0.copy(source.v0);
  22619. this.v1.copy(source.v1);
  22620. this.v2.copy(source.v2);
  22621. this.v3.copy(source.v3);
  22622. return this;
  22623. };
  22624. CubicBezierCurve3.prototype.toJSON = function () {
  22625. var data = Curve.prototype.toJSON.call(this);
  22626. data.v0 = this.v0.toArray();
  22627. data.v1 = this.v1.toArray();
  22628. data.v2 = this.v2.toArray();
  22629. data.v3 = this.v3.toArray();
  22630. return data;
  22631. };
  22632. CubicBezierCurve3.prototype.fromJSON = function (json) {
  22633. Curve.prototype.fromJSON.call(this, json);
  22634. this.v0.fromArray(json.v0);
  22635. this.v1.fromArray(json.v1);
  22636. this.v2.fromArray(json.v2);
  22637. this.v3.fromArray(json.v3);
  22638. return this;
  22639. };
  22640. function LineCurve(v1, v2) {
  22641. Curve.call(this);
  22642. this.type = 'LineCurve';
  22643. this.v1 = v1 || new Vector2();
  22644. this.v2 = v2 || new Vector2();
  22645. }
  22646. LineCurve.prototype = Object.create(Curve.prototype);
  22647. LineCurve.prototype.constructor = LineCurve;
  22648. LineCurve.prototype.isLineCurve = true;
  22649. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  22650. var point = optionalTarget || new Vector2();
  22651. if (t === 1) {
  22652. point.copy(this.v2);
  22653. } else {
  22654. point.copy(this.v2).sub(this.v1);
  22655. point.multiplyScalar(t).add(this.v1);
  22656. }
  22657. return point;
  22658. }; // Line curve is linear, so we can overwrite default getPointAt
  22659. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  22660. return this.getPoint(u, optionalTarget);
  22661. };
  22662. LineCurve.prototype.getTangent = function ()
  22663. /* t */
  22664. {
  22665. var tangent = this.v2.clone().sub(this.v1);
  22666. return tangent.normalize();
  22667. };
  22668. LineCurve.prototype.copy = function (source) {
  22669. Curve.prototype.copy.call(this, source);
  22670. this.v1.copy(source.v1);
  22671. this.v2.copy(source.v2);
  22672. return this;
  22673. };
  22674. LineCurve.prototype.toJSON = function () {
  22675. var data = Curve.prototype.toJSON.call(this);
  22676. data.v1 = this.v1.toArray();
  22677. data.v2 = this.v2.toArray();
  22678. return data;
  22679. };
  22680. LineCurve.prototype.fromJSON = function (json) {
  22681. Curve.prototype.fromJSON.call(this, json);
  22682. this.v1.fromArray(json.v1);
  22683. this.v2.fromArray(json.v2);
  22684. return this;
  22685. };
  22686. function LineCurve3(v1, v2) {
  22687. Curve.call(this);
  22688. this.type = 'LineCurve3';
  22689. this.v1 = v1 || new Vector3();
  22690. this.v2 = v2 || new Vector3();
  22691. }
  22692. LineCurve3.prototype = Object.create(Curve.prototype);
  22693. LineCurve3.prototype.constructor = LineCurve3;
  22694. LineCurve3.prototype.isLineCurve3 = true;
  22695. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  22696. var point = optionalTarget || new Vector3();
  22697. if (t === 1) {
  22698. point.copy(this.v2);
  22699. } else {
  22700. point.copy(this.v2).sub(this.v1);
  22701. point.multiplyScalar(t).add(this.v1);
  22702. }
  22703. return point;
  22704. }; // Line curve is linear, so we can overwrite default getPointAt
  22705. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  22706. return this.getPoint(u, optionalTarget);
  22707. };
  22708. LineCurve3.prototype.copy = function (source) {
  22709. Curve.prototype.copy.call(this, source);
  22710. this.v1.copy(source.v1);
  22711. this.v2.copy(source.v2);
  22712. return this;
  22713. };
  22714. LineCurve3.prototype.toJSON = function () {
  22715. var data = Curve.prototype.toJSON.call(this);
  22716. data.v1 = this.v1.toArray();
  22717. data.v2 = this.v2.toArray();
  22718. return data;
  22719. };
  22720. LineCurve3.prototype.fromJSON = function (json) {
  22721. Curve.prototype.fromJSON.call(this, json);
  22722. this.v1.fromArray(json.v1);
  22723. this.v2.fromArray(json.v2);
  22724. return this;
  22725. };
  22726. function QuadraticBezierCurve(v0, v1, v2) {
  22727. Curve.call(this);
  22728. this.type = 'QuadraticBezierCurve';
  22729. this.v0 = v0 || new Vector2();
  22730. this.v1 = v1 || new Vector2();
  22731. this.v2 = v2 || new Vector2();
  22732. }
  22733. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  22734. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22735. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22736. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22737. var point = optionalTarget || new Vector2();
  22738. var v0 = this.v0,
  22739. v1 = this.v1,
  22740. v2 = this.v2;
  22741. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  22742. return point;
  22743. };
  22744. QuadraticBezierCurve.prototype.copy = function (source) {
  22745. Curve.prototype.copy.call(this, source);
  22746. this.v0.copy(source.v0);
  22747. this.v1.copy(source.v1);
  22748. this.v2.copy(source.v2);
  22749. return this;
  22750. };
  22751. QuadraticBezierCurve.prototype.toJSON = function () {
  22752. var data = Curve.prototype.toJSON.call(this);
  22753. data.v0 = this.v0.toArray();
  22754. data.v1 = this.v1.toArray();
  22755. data.v2 = this.v2.toArray();
  22756. return data;
  22757. };
  22758. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  22759. Curve.prototype.fromJSON.call(this, json);
  22760. this.v0.fromArray(json.v0);
  22761. this.v1.fromArray(json.v1);
  22762. this.v2.fromArray(json.v2);
  22763. return this;
  22764. };
  22765. function QuadraticBezierCurve3(v0, v1, v2) {
  22766. Curve.call(this);
  22767. this.type = 'QuadraticBezierCurve3';
  22768. this.v0 = v0 || new Vector3();
  22769. this.v1 = v1 || new Vector3();
  22770. this.v2 = v2 || new Vector3();
  22771. }
  22772. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  22773. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22774. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22775. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22776. var point = optionalTarget || new Vector3();
  22777. var v0 = this.v0,
  22778. v1 = this.v1,
  22779. v2 = this.v2;
  22780. 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));
  22781. return point;
  22782. };
  22783. QuadraticBezierCurve3.prototype.copy = function (source) {
  22784. Curve.prototype.copy.call(this, source);
  22785. this.v0.copy(source.v0);
  22786. this.v1.copy(source.v1);
  22787. this.v2.copy(source.v2);
  22788. return this;
  22789. };
  22790. QuadraticBezierCurve3.prototype.toJSON = function () {
  22791. var data = Curve.prototype.toJSON.call(this);
  22792. data.v0 = this.v0.toArray();
  22793. data.v1 = this.v1.toArray();
  22794. data.v2 = this.v2.toArray();
  22795. return data;
  22796. };
  22797. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  22798. Curve.prototype.fromJSON.call(this, json);
  22799. this.v0.fromArray(json.v0);
  22800. this.v1.fromArray(json.v1);
  22801. this.v2.fromArray(json.v2);
  22802. return this;
  22803. };
  22804. function SplineCurve(points
  22805. /* array of Vector2 */
  22806. ) {
  22807. Curve.call(this);
  22808. this.type = 'SplineCurve';
  22809. this.points = points || [];
  22810. }
  22811. SplineCurve.prototype = Object.create(Curve.prototype);
  22812. SplineCurve.prototype.constructor = SplineCurve;
  22813. SplineCurve.prototype.isSplineCurve = true;
  22814. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  22815. var point = optionalTarget || new Vector2();
  22816. var points = this.points;
  22817. var p = (points.length - 1) * t;
  22818. var intPoint = Math.floor(p);
  22819. var weight = p - intPoint;
  22820. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  22821. var p1 = points[intPoint];
  22822. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  22823. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  22824. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  22825. return point;
  22826. };
  22827. SplineCurve.prototype.copy = function (source) {
  22828. Curve.prototype.copy.call(this, source);
  22829. this.points = [];
  22830. for (var i = 0, l = source.points.length; i < l; i++) {
  22831. var point = source.points[i];
  22832. this.points.push(point.clone());
  22833. }
  22834. return this;
  22835. };
  22836. SplineCurve.prototype.toJSON = function () {
  22837. var data = Curve.prototype.toJSON.call(this);
  22838. data.points = [];
  22839. for (var i = 0, l = this.points.length; i < l; i++) {
  22840. var point = this.points[i];
  22841. data.points.push(point.toArray());
  22842. }
  22843. return data;
  22844. };
  22845. SplineCurve.prototype.fromJSON = function (json) {
  22846. Curve.prototype.fromJSON.call(this, json);
  22847. this.points = [];
  22848. for (var i = 0, l = json.points.length; i < l; i++) {
  22849. var point = json.points[i];
  22850. this.points.push(new Vector2().fromArray(point));
  22851. }
  22852. return this;
  22853. };
  22854. var Curves =
  22855. /*#__PURE__*/
  22856. Object.freeze({
  22857. __proto__: null,
  22858. ArcCurve: ArcCurve,
  22859. CatmullRomCurve3: CatmullRomCurve3,
  22860. CubicBezierCurve: CubicBezierCurve,
  22861. CubicBezierCurve3: CubicBezierCurve3,
  22862. EllipseCurve: EllipseCurve,
  22863. LineCurve: LineCurve,
  22864. LineCurve3: LineCurve3,
  22865. QuadraticBezierCurve: QuadraticBezierCurve,
  22866. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22867. SplineCurve: SplineCurve
  22868. });
  22869. /**
  22870. * @author zz85 / http://www.lab4games.net/zz85/blog
  22871. *
  22872. **/
  22873. /**************************************************************
  22874. * Curved Path - a curve path is simply a array of connected
  22875. * curves, but retains the api of a curve
  22876. **************************************************************/
  22877. function CurvePath() {
  22878. Curve.call(this);
  22879. this.type = 'CurvePath';
  22880. this.curves = [];
  22881. this.autoClose = false; // Automatically closes the path
  22882. }
  22883. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  22884. constructor: CurvePath,
  22885. add: function (curve) {
  22886. this.curves.push(curve);
  22887. },
  22888. closePath: function () {
  22889. // Add a line curve if start and end of lines are not connected
  22890. var startPoint = this.curves[0].getPoint(0);
  22891. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22892. if (!startPoint.equals(endPoint)) {
  22893. this.curves.push(new LineCurve(endPoint, startPoint));
  22894. }
  22895. },
  22896. // To get accurate point with reference to
  22897. // entire path distance at time t,
  22898. // following has to be done:
  22899. // 1. Length of each sub path have to be known
  22900. // 2. Locate and identify type of curve
  22901. // 3. Get t for the curve
  22902. // 4. Return curve.getPointAt(t')
  22903. getPoint: function (t) {
  22904. var d = t * this.getLength();
  22905. var curveLengths = this.getCurveLengths();
  22906. var i = 0; // To think about boundaries points.
  22907. while (i < curveLengths.length) {
  22908. if (curveLengths[i] >= d) {
  22909. var diff = curveLengths[i] - d;
  22910. var curve = this.curves[i];
  22911. var segmentLength = curve.getLength();
  22912. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22913. return curve.getPointAt(u);
  22914. }
  22915. i++;
  22916. }
  22917. return null; // loop where sum != 0, sum > d , sum+1 <d
  22918. },
  22919. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22920. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22921. // getPoint() depends on getLength
  22922. getLength: function () {
  22923. var lens = this.getCurveLengths();
  22924. return lens[lens.length - 1];
  22925. },
  22926. // cacheLengths must be recalculated.
  22927. updateArcLengths: function () {
  22928. this.needsUpdate = true;
  22929. this.cacheLengths = null;
  22930. this.getCurveLengths();
  22931. },
  22932. // Compute lengths and cache them
  22933. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22934. getCurveLengths: function () {
  22935. // We use cache values if curves and cache array are same length
  22936. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22937. return this.cacheLengths;
  22938. } // Get length of sub-curve
  22939. // Push sums into cached array
  22940. var lengths = [],
  22941. sums = 0;
  22942. for (var i = 0, l = this.curves.length; i < l; i++) {
  22943. sums += this.curves[i].getLength();
  22944. lengths.push(sums);
  22945. }
  22946. this.cacheLengths = lengths;
  22947. return lengths;
  22948. },
  22949. getSpacedPoints: function (divisions) {
  22950. if (divisions === undefined) divisions = 40;
  22951. var points = [];
  22952. for (var i = 0; i <= divisions; i++) {
  22953. points.push(this.getPoint(i / divisions));
  22954. }
  22955. if (this.autoClose) {
  22956. points.push(points[0]);
  22957. }
  22958. return points;
  22959. },
  22960. getPoints: function (divisions) {
  22961. divisions = divisions || 12;
  22962. var points = [],
  22963. last;
  22964. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  22965. var curve = curves[i];
  22966. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22967. var pts = curve.getPoints(resolution);
  22968. for (var j = 0; j < pts.length; j++) {
  22969. var point = pts[j];
  22970. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22971. points.push(point);
  22972. last = point;
  22973. }
  22974. }
  22975. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22976. points.push(points[0]);
  22977. }
  22978. return points;
  22979. },
  22980. copy: function (source) {
  22981. Curve.prototype.copy.call(this, source);
  22982. this.curves = [];
  22983. for (var i = 0, l = source.curves.length; i < l; i++) {
  22984. var curve = source.curves[i];
  22985. this.curves.push(curve.clone());
  22986. }
  22987. this.autoClose = source.autoClose;
  22988. return this;
  22989. },
  22990. toJSON: function () {
  22991. var data = Curve.prototype.toJSON.call(this);
  22992. data.autoClose = this.autoClose;
  22993. data.curves = [];
  22994. for (var i = 0, l = this.curves.length; i < l; i++) {
  22995. var curve = this.curves[i];
  22996. data.curves.push(curve.toJSON());
  22997. }
  22998. return data;
  22999. },
  23000. fromJSON: function (json) {
  23001. Curve.prototype.fromJSON.call(this, json);
  23002. this.autoClose = json.autoClose;
  23003. this.curves = [];
  23004. for (var i = 0, l = json.curves.length; i < l; i++) {
  23005. var curve = json.curves[i];
  23006. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23007. }
  23008. return this;
  23009. }
  23010. });
  23011. /**
  23012. * @author zz85 / http://www.lab4games.net/zz85/blog
  23013. * Creates free form 2d path using series of points, lines or curves.
  23014. **/
  23015. function Path(points) {
  23016. CurvePath.call(this);
  23017. this.type = 'Path';
  23018. this.currentPoint = new Vector2();
  23019. if (points) {
  23020. this.setFromPoints(points);
  23021. }
  23022. }
  23023. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23024. constructor: Path,
  23025. setFromPoints: function (points) {
  23026. this.moveTo(points[0].x, points[0].y);
  23027. for (var i = 1, l = points.length; i < l; i++) {
  23028. this.lineTo(points[i].x, points[i].y);
  23029. }
  23030. return this;
  23031. },
  23032. moveTo: function (x, y) {
  23033. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23034. return this;
  23035. },
  23036. lineTo: function (x, y) {
  23037. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23038. this.curves.push(curve);
  23039. this.currentPoint.set(x, y);
  23040. return this;
  23041. },
  23042. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23043. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23044. this.curves.push(curve);
  23045. this.currentPoint.set(aX, aY);
  23046. return this;
  23047. },
  23048. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23049. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23050. this.curves.push(curve);
  23051. this.currentPoint.set(aX, aY);
  23052. return this;
  23053. },
  23054. splineThru: function (pts
  23055. /*Array of Vector*/
  23056. ) {
  23057. var npts = [this.currentPoint.clone()].concat(pts);
  23058. var curve = new SplineCurve(npts);
  23059. this.curves.push(curve);
  23060. this.currentPoint.copy(pts[pts.length - 1]);
  23061. return this;
  23062. },
  23063. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23064. var x0 = this.currentPoint.x;
  23065. var y0 = this.currentPoint.y;
  23066. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23067. return this;
  23068. },
  23069. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23070. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23071. return this;
  23072. },
  23073. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23074. var x0 = this.currentPoint.x;
  23075. var y0 = this.currentPoint.y;
  23076. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23077. return this;
  23078. },
  23079. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23080. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23081. if (this.curves.length > 0) {
  23082. // if a previous curve is present, attempt to join
  23083. var firstPoint = curve.getPoint(0);
  23084. if (!firstPoint.equals(this.currentPoint)) {
  23085. this.lineTo(firstPoint.x, firstPoint.y);
  23086. }
  23087. }
  23088. this.curves.push(curve);
  23089. var lastPoint = curve.getPoint(1);
  23090. this.currentPoint.copy(lastPoint);
  23091. return this;
  23092. },
  23093. copy: function (source) {
  23094. CurvePath.prototype.copy.call(this, source);
  23095. this.currentPoint.copy(source.currentPoint);
  23096. return this;
  23097. },
  23098. toJSON: function () {
  23099. var data = CurvePath.prototype.toJSON.call(this);
  23100. data.currentPoint = this.currentPoint.toArray();
  23101. return data;
  23102. },
  23103. fromJSON: function (json) {
  23104. CurvePath.prototype.fromJSON.call(this, json);
  23105. this.currentPoint.fromArray(json.currentPoint);
  23106. return this;
  23107. }
  23108. });
  23109. /**
  23110. * @author zz85 / http://www.lab4games.net/zz85/blog
  23111. * Defines a 2d shape plane using paths.
  23112. **/
  23113. // STEP 1 Create a path.
  23114. // STEP 2 Turn path into shape.
  23115. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23116. // STEP 3a - Extract points from each shape, turn to vertices
  23117. // STEP 3b - Triangulate each shape, add faces.
  23118. function Shape(points) {
  23119. Path.call(this, points);
  23120. this.uuid = MathUtils.generateUUID();
  23121. this.type = 'Shape';
  23122. this.holes = [];
  23123. }
  23124. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23125. constructor: Shape,
  23126. getPointsHoles: function (divisions) {
  23127. var holesPts = [];
  23128. for (var i = 0, l = this.holes.length; i < l; i++) {
  23129. holesPts[i] = this.holes[i].getPoints(divisions);
  23130. }
  23131. return holesPts;
  23132. },
  23133. // get points of shape and holes (keypoints based on segments parameter)
  23134. extractPoints: function (divisions) {
  23135. return {
  23136. shape: this.getPoints(divisions),
  23137. holes: this.getPointsHoles(divisions)
  23138. };
  23139. },
  23140. copy: function (source) {
  23141. Path.prototype.copy.call(this, source);
  23142. this.holes = [];
  23143. for (var i = 0, l = source.holes.length; i < l; i++) {
  23144. var hole = source.holes[i];
  23145. this.holes.push(hole.clone());
  23146. }
  23147. return this;
  23148. },
  23149. toJSON: function () {
  23150. var data = Path.prototype.toJSON.call(this);
  23151. data.uuid = this.uuid;
  23152. data.holes = [];
  23153. for (var i = 0, l = this.holes.length; i < l; i++) {
  23154. var hole = this.holes[i];
  23155. data.holes.push(hole.toJSON());
  23156. }
  23157. return data;
  23158. },
  23159. fromJSON: function (json) {
  23160. Path.prototype.fromJSON.call(this, json);
  23161. this.uuid = json.uuid;
  23162. this.holes = [];
  23163. for (var i = 0, l = json.holes.length; i < l; i++) {
  23164. var hole = json.holes[i];
  23165. this.holes.push(new Path().fromJSON(hole));
  23166. }
  23167. return this;
  23168. }
  23169. });
  23170. /**
  23171. * @author mrdoob / http://mrdoob.com/
  23172. * @author alteredq / http://alteredqualia.com/
  23173. */
  23174. function Light(color, intensity) {
  23175. Object3D.call(this);
  23176. this.type = 'Light';
  23177. this.color = new Color(color);
  23178. this.intensity = intensity !== undefined ? intensity : 1;
  23179. this.receiveShadow = undefined;
  23180. }
  23181. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23182. constructor: Light,
  23183. isLight: true,
  23184. copy: function (source) {
  23185. Object3D.prototype.copy.call(this, source);
  23186. this.color.copy(source.color);
  23187. this.intensity = source.intensity;
  23188. return this;
  23189. },
  23190. toJSON: function (meta) {
  23191. var data = Object3D.prototype.toJSON.call(this, meta);
  23192. data.object.color = this.color.getHex();
  23193. data.object.intensity = this.intensity;
  23194. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23195. if (this.distance !== undefined) data.object.distance = this.distance;
  23196. if (this.angle !== undefined) data.object.angle = this.angle;
  23197. if (this.decay !== undefined) data.object.decay = this.decay;
  23198. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23199. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23200. return data;
  23201. }
  23202. });
  23203. /**
  23204. * @author alteredq / http://alteredqualia.com/
  23205. */
  23206. function HemisphereLight(skyColor, groundColor, intensity) {
  23207. Light.call(this, skyColor, intensity);
  23208. this.type = 'HemisphereLight';
  23209. this.castShadow = undefined;
  23210. this.position.copy(Object3D.DefaultUp);
  23211. this.updateMatrix();
  23212. this.groundColor = new Color(groundColor);
  23213. }
  23214. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23215. constructor: HemisphereLight,
  23216. isHemisphereLight: true,
  23217. copy: function (source) {
  23218. Light.prototype.copy.call(this, source);
  23219. this.groundColor.copy(source.groundColor);
  23220. return this;
  23221. }
  23222. });
  23223. /**
  23224. * @author mrdoob / http://mrdoob.com/
  23225. */
  23226. function LightShadow(camera) {
  23227. this.camera = camera;
  23228. this.bias = 0;
  23229. this.radius = 1;
  23230. this.mapSize = new Vector2(512, 512);
  23231. this.map = null;
  23232. this.mapPass = null;
  23233. this.matrix = new Matrix4();
  23234. this._frustum = new Frustum();
  23235. this._frameExtents = new Vector2(1, 1);
  23236. this._viewportCount = 1;
  23237. this._viewports = [new Vector4(0, 0, 1, 1)];
  23238. }
  23239. Object.assign(LightShadow.prototype, {
  23240. _projScreenMatrix: new Matrix4(),
  23241. _lightPositionWorld: new Vector3(),
  23242. _lookTarget: new Vector3(),
  23243. getViewportCount: function () {
  23244. return this._viewportCount;
  23245. },
  23246. getFrustum: function () {
  23247. return this._frustum;
  23248. },
  23249. updateMatrices: function (light) {
  23250. var shadowCamera = this.camera,
  23251. shadowMatrix = this.matrix,
  23252. projScreenMatrix = this._projScreenMatrix,
  23253. lookTarget = this._lookTarget,
  23254. lightPositionWorld = this._lightPositionWorld;
  23255. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23256. shadowCamera.position.copy(lightPositionWorld);
  23257. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23258. shadowCamera.lookAt(lookTarget);
  23259. shadowCamera.updateMatrixWorld();
  23260. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23261. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23262. 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);
  23263. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23264. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23265. },
  23266. getViewport: function (viewportIndex) {
  23267. return this._viewports[viewportIndex];
  23268. },
  23269. getFrameExtents: function () {
  23270. return this._frameExtents;
  23271. },
  23272. copy: function (source) {
  23273. this.camera = source.camera.clone();
  23274. this.bias = source.bias;
  23275. this.radius = source.radius;
  23276. this.mapSize.copy(source.mapSize);
  23277. return this;
  23278. },
  23279. clone: function () {
  23280. return new this.constructor().copy(this);
  23281. },
  23282. toJSON: function () {
  23283. var object = {};
  23284. if (this.bias !== 0) object.bias = this.bias;
  23285. if (this.radius !== 1) object.radius = this.radius;
  23286. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23287. object.camera = this.camera.toJSON(false).object;
  23288. delete object.camera.matrix;
  23289. return object;
  23290. }
  23291. });
  23292. /**
  23293. * @author mrdoob / http://mrdoob.com/
  23294. */
  23295. function SpotLightShadow() {
  23296. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  23297. }
  23298. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23299. constructor: SpotLightShadow,
  23300. isSpotLightShadow: true,
  23301. updateMatrices: function (light) {
  23302. var camera = this.camera;
  23303. var fov = MathUtils.RAD2DEG * 2 * light.angle;
  23304. var aspect = this.mapSize.width / this.mapSize.height;
  23305. var far = light.distance || camera.far;
  23306. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23307. camera.fov = fov;
  23308. camera.aspect = aspect;
  23309. camera.far = far;
  23310. camera.updateProjectionMatrix();
  23311. }
  23312. LightShadow.prototype.updateMatrices.call(this, light);
  23313. }
  23314. });
  23315. /**
  23316. * @author alteredq / http://alteredqualia.com/
  23317. */
  23318. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  23319. Light.call(this, color, intensity);
  23320. this.type = 'SpotLight';
  23321. this.position.copy(Object3D.DefaultUp);
  23322. this.updateMatrix();
  23323. this.target = new Object3D();
  23324. Object.defineProperty(this, 'power', {
  23325. get: function () {
  23326. // intensity = power per solid angle.
  23327. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23328. return this.intensity * Math.PI;
  23329. },
  23330. set: function (power) {
  23331. // intensity = power per solid angle.
  23332. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23333. this.intensity = power / Math.PI;
  23334. }
  23335. });
  23336. this.distance = distance !== undefined ? distance : 0;
  23337. this.angle = angle !== undefined ? angle : Math.PI / 3;
  23338. this.penumbra = penumbra !== undefined ? penumbra : 0;
  23339. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23340. this.shadow = new SpotLightShadow();
  23341. }
  23342. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  23343. constructor: SpotLight,
  23344. isSpotLight: true,
  23345. copy: function (source) {
  23346. Light.prototype.copy.call(this, source);
  23347. this.distance = source.distance;
  23348. this.angle = source.angle;
  23349. this.penumbra = source.penumbra;
  23350. this.decay = source.decay;
  23351. this.target = source.target.clone();
  23352. this.shadow = source.shadow.clone();
  23353. return this;
  23354. }
  23355. });
  23356. function PointLightShadow() {
  23357. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  23358. this._frameExtents = new Vector2(4, 2);
  23359. this._viewportCount = 6;
  23360. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23361. // following orientation:
  23362. //
  23363. // xzXZ
  23364. // y Y
  23365. //
  23366. // X - Positive x direction
  23367. // x - Negative x direction
  23368. // Y - Positive y direction
  23369. // y - Negative y direction
  23370. // Z - Positive z direction
  23371. // z - Negative z direction
  23372. // positive X
  23373. new Vector4(2, 1, 1, 1), // negative X
  23374. new Vector4(0, 1, 1, 1), // positive Z
  23375. new Vector4(3, 1, 1, 1), // negative Z
  23376. new Vector4(1, 1, 1, 1), // positive Y
  23377. new Vector4(3, 0, 1, 1), // negative Y
  23378. new Vector4(1, 0, 1, 1)];
  23379. 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)];
  23380. 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)];
  23381. }
  23382. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23383. constructor: PointLightShadow,
  23384. isPointLightShadow: true,
  23385. updateMatrices: function (light, viewportIndex) {
  23386. if (viewportIndex === undefined) viewportIndex = 0;
  23387. var camera = this.camera,
  23388. shadowMatrix = this.matrix,
  23389. lightPositionWorld = this._lightPositionWorld,
  23390. lookTarget = this._lookTarget,
  23391. projScreenMatrix = this._projScreenMatrix;
  23392. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23393. camera.position.copy(lightPositionWorld);
  23394. lookTarget.copy(camera.position);
  23395. lookTarget.add(this._cubeDirections[viewportIndex]);
  23396. camera.up.copy(this._cubeUps[viewportIndex]);
  23397. camera.lookAt(lookTarget);
  23398. camera.updateMatrixWorld();
  23399. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23400. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23401. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23402. }
  23403. });
  23404. /**
  23405. * @author mrdoob / http://mrdoob.com/
  23406. */
  23407. function PointLight(color, intensity, distance, decay) {
  23408. Light.call(this, color, intensity);
  23409. this.type = 'PointLight';
  23410. Object.defineProperty(this, 'power', {
  23411. get: function () {
  23412. // intensity = power per solid angle.
  23413. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23414. return this.intensity * 4 * Math.PI;
  23415. },
  23416. set: function (power) {
  23417. // intensity = power per solid angle.
  23418. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23419. this.intensity = power / (4 * Math.PI);
  23420. }
  23421. });
  23422. this.distance = distance !== undefined ? distance : 0;
  23423. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23424. this.shadow = new PointLightShadow();
  23425. }
  23426. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23427. constructor: PointLight,
  23428. isPointLight: true,
  23429. copy: function (source) {
  23430. Light.prototype.copy.call(this, source);
  23431. this.distance = source.distance;
  23432. this.decay = source.decay;
  23433. this.shadow = source.shadow.clone();
  23434. return this;
  23435. }
  23436. });
  23437. /**
  23438. * @author alteredq / http://alteredqualia.com/
  23439. * @author arose / http://github.com/arose
  23440. */
  23441. function OrthographicCamera(left, right, top, bottom, near, far) {
  23442. Camera.call(this);
  23443. this.type = 'OrthographicCamera';
  23444. this.zoom = 1;
  23445. this.view = null;
  23446. this.left = left !== undefined ? left : -1;
  23447. this.right = right !== undefined ? right : 1;
  23448. this.top = top !== undefined ? top : 1;
  23449. this.bottom = bottom !== undefined ? bottom : -1;
  23450. this.near = near !== undefined ? near : 0.1;
  23451. this.far = far !== undefined ? far : 2000;
  23452. this.updateProjectionMatrix();
  23453. }
  23454. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23455. constructor: OrthographicCamera,
  23456. isOrthographicCamera: true,
  23457. copy: function (source, recursive) {
  23458. Camera.prototype.copy.call(this, source, recursive);
  23459. this.left = source.left;
  23460. this.right = source.right;
  23461. this.top = source.top;
  23462. this.bottom = source.bottom;
  23463. this.near = source.near;
  23464. this.far = source.far;
  23465. this.zoom = source.zoom;
  23466. this.view = source.view === null ? null : Object.assign({}, source.view);
  23467. return this;
  23468. },
  23469. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23470. if (this.view === null) {
  23471. this.view = {
  23472. enabled: true,
  23473. fullWidth: 1,
  23474. fullHeight: 1,
  23475. offsetX: 0,
  23476. offsetY: 0,
  23477. width: 1,
  23478. height: 1
  23479. };
  23480. }
  23481. this.view.enabled = true;
  23482. this.view.fullWidth = fullWidth;
  23483. this.view.fullHeight = fullHeight;
  23484. this.view.offsetX = x;
  23485. this.view.offsetY = y;
  23486. this.view.width = width;
  23487. this.view.height = height;
  23488. this.updateProjectionMatrix();
  23489. },
  23490. clearViewOffset: function () {
  23491. if (this.view !== null) {
  23492. this.view.enabled = false;
  23493. }
  23494. this.updateProjectionMatrix();
  23495. },
  23496. updateProjectionMatrix: function () {
  23497. var dx = (this.right - this.left) / (2 * this.zoom);
  23498. var dy = (this.top - this.bottom) / (2 * this.zoom);
  23499. var cx = (this.right + this.left) / 2;
  23500. var cy = (this.top + this.bottom) / 2;
  23501. var left = cx - dx;
  23502. var right = cx + dx;
  23503. var top = cy + dy;
  23504. var bottom = cy - dy;
  23505. if (this.view !== null && this.view.enabled) {
  23506. var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  23507. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  23508. left += scaleW * this.view.offsetX;
  23509. right = left + scaleW * this.view.width;
  23510. top -= scaleH * this.view.offsetY;
  23511. bottom = top - scaleH * this.view.height;
  23512. }
  23513. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23514. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  23515. },
  23516. toJSON: function (meta) {
  23517. var data = Object3D.prototype.toJSON.call(this, meta);
  23518. data.object.zoom = this.zoom;
  23519. data.object.left = this.left;
  23520. data.object.right = this.right;
  23521. data.object.top = this.top;
  23522. data.object.bottom = this.bottom;
  23523. data.object.near = this.near;
  23524. data.object.far = this.far;
  23525. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23526. return data;
  23527. }
  23528. });
  23529. /**
  23530. * @author mrdoob / http://mrdoob.com/
  23531. */
  23532. function DirectionalLightShadow() {
  23533. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23534. }
  23535. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23536. constructor: DirectionalLightShadow,
  23537. isDirectionalLightShadow: true,
  23538. updateMatrices: function (light) {
  23539. LightShadow.prototype.updateMatrices.call(this, light);
  23540. }
  23541. });
  23542. /**
  23543. * @author mrdoob / http://mrdoob.com/
  23544. * @author alteredq / http://alteredqualia.com/
  23545. */
  23546. function DirectionalLight(color, intensity) {
  23547. Light.call(this, color, intensity);
  23548. this.type = 'DirectionalLight';
  23549. this.position.copy(Object3D.DefaultUp);
  23550. this.updateMatrix();
  23551. this.target = new Object3D();
  23552. this.shadow = new DirectionalLightShadow();
  23553. }
  23554. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23555. constructor: DirectionalLight,
  23556. isDirectionalLight: true,
  23557. copy: function (source) {
  23558. Light.prototype.copy.call(this, source);
  23559. this.target = source.target.clone();
  23560. this.shadow = source.shadow.clone();
  23561. return this;
  23562. }
  23563. });
  23564. /**
  23565. * @author mrdoob / http://mrdoob.com/
  23566. */
  23567. function AmbientLight(color, intensity) {
  23568. Light.call(this, color, intensity);
  23569. this.type = 'AmbientLight';
  23570. this.castShadow = undefined;
  23571. }
  23572. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23573. constructor: AmbientLight,
  23574. isAmbientLight: true
  23575. });
  23576. /**
  23577. * @author abelnation / http://github.com/abelnation
  23578. */
  23579. function RectAreaLight(color, intensity, width, height) {
  23580. Light.call(this, color, intensity);
  23581. this.type = 'RectAreaLight';
  23582. this.width = width !== undefined ? width : 10;
  23583. this.height = height !== undefined ? height : 10;
  23584. }
  23585. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23586. constructor: RectAreaLight,
  23587. isRectAreaLight: true,
  23588. copy: function (source) {
  23589. Light.prototype.copy.call(this, source);
  23590. this.width = source.width;
  23591. this.height = source.height;
  23592. return this;
  23593. },
  23594. toJSON: function (meta) {
  23595. var data = Light.prototype.toJSON.call(this, meta);
  23596. data.object.width = this.width;
  23597. data.object.height = this.height;
  23598. return data;
  23599. }
  23600. });
  23601. /**
  23602. * @author mrdoob / http://mrdoob.com/
  23603. */
  23604. function MaterialLoader(manager) {
  23605. Loader.call(this, manager);
  23606. this.textures = {};
  23607. }
  23608. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23609. constructor: MaterialLoader,
  23610. load: function (url, onLoad, onProgress, onError) {
  23611. var scope = this;
  23612. var loader = new FileLoader(scope.manager);
  23613. loader.setPath(scope.path);
  23614. loader.load(url, function (text) {
  23615. onLoad(scope.parse(JSON.parse(text)));
  23616. }, onProgress, onError);
  23617. },
  23618. parse: function (json) {
  23619. var textures = this.textures;
  23620. function getTexture(name) {
  23621. if (textures[name] === undefined) {
  23622. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23623. }
  23624. return textures[name];
  23625. }
  23626. var material = new Materials[json.type]();
  23627. if (json.uuid !== undefined) material.uuid = json.uuid;
  23628. if (json.name !== undefined) material.name = json.name;
  23629. if (json.color !== undefined) material.color.setHex(json.color);
  23630. if (json.roughness !== undefined) material.roughness = json.roughness;
  23631. if (json.metalness !== undefined) material.metalness = json.metalness;
  23632. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23633. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  23634. if (json.specular !== undefined) material.specular.setHex(json.specular);
  23635. if (json.shininess !== undefined) material.shininess = json.shininess;
  23636. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23637. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23638. if (json.fog !== undefined) material.fog = json.fog;
  23639. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23640. if (json.blending !== undefined) material.blending = json.blending;
  23641. if (json.combine !== undefined) material.combine = json.combine;
  23642. if (json.side !== undefined) material.side = json.side;
  23643. if (json.opacity !== undefined) material.opacity = json.opacity;
  23644. if (json.transparent !== undefined) material.transparent = json.transparent;
  23645. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23646. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23647. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23648. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23649. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23650. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23651. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23652. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23653. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23654. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23655. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23656. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23657. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23658. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23659. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23660. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23661. if (json.rotation !== undefined) material.rotation = json.rotation;
  23662. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23663. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23664. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23665. if (json.scale !== undefined) material.scale = json.scale;
  23666. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23667. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23668. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23669. if (json.skinning !== undefined) material.skinning = json.skinning;
  23670. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  23671. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  23672. if (json.dithering !== undefined) material.dithering = json.dithering;
  23673. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  23674. if (json.visible !== undefined) material.visible = json.visible;
  23675. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23676. if (json.userData !== undefined) material.userData = json.userData;
  23677. if (json.vertexColors !== undefined) {
  23678. if (typeof json.vertexColors === 'number') {
  23679. material.vertexColors = json.vertexColors > 0 ? true : false;
  23680. } else {
  23681. material.vertexColors = json.vertexColors;
  23682. }
  23683. } // Shader Material
  23684. if (json.uniforms !== undefined) {
  23685. for (var name in json.uniforms) {
  23686. var uniform = json.uniforms[name];
  23687. material.uniforms[name] = {};
  23688. switch (uniform.type) {
  23689. case 't':
  23690. material.uniforms[name].value = getTexture(uniform.value);
  23691. break;
  23692. case 'c':
  23693. material.uniforms[name].value = new Color().setHex(uniform.value);
  23694. break;
  23695. case 'v2':
  23696. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23697. break;
  23698. case 'v3':
  23699. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23700. break;
  23701. case 'v4':
  23702. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23703. break;
  23704. case 'm3':
  23705. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23706. case 'm4':
  23707. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23708. break;
  23709. default:
  23710. material.uniforms[name].value = uniform.value;
  23711. }
  23712. }
  23713. }
  23714. if (json.defines !== undefined) material.defines = json.defines;
  23715. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23716. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23717. if (json.extensions !== undefined) {
  23718. for (var key in json.extensions) {
  23719. material.extensions[key] = json.extensions[key];
  23720. }
  23721. } // Deprecated
  23722. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23723. // for PointsMaterial
  23724. if (json.size !== undefined) material.size = json.size;
  23725. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23726. if (json.map !== undefined) material.map = getTexture(json.map);
  23727. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23728. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23729. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23730. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23731. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23732. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23733. if (json.normalScale !== undefined) {
  23734. var normalScale = json.normalScale;
  23735. if (Array.isArray(normalScale) === false) {
  23736. // Blender exporter used to export a scalar. See #7459
  23737. normalScale = [normalScale, normalScale];
  23738. }
  23739. material.normalScale = new Vector2().fromArray(normalScale);
  23740. }
  23741. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23742. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23743. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23744. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23745. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23746. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23747. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23748. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23749. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23750. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23751. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23752. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23753. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23754. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23755. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23756. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23757. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23758. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23759. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23760. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23761. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23762. return material;
  23763. },
  23764. setTextures: function (value) {
  23765. this.textures = value;
  23766. return this;
  23767. }
  23768. });
  23769. /**
  23770. * @author Don McCurdy / https://www.donmccurdy.com
  23771. */
  23772. var LoaderUtils = {
  23773. decodeText: function (array) {
  23774. if (typeof TextDecoder !== 'undefined') {
  23775. return new TextDecoder().decode(array);
  23776. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23777. // throws a "maximum call stack size exceeded" error for large arrays.
  23778. var s = '';
  23779. for (var i = 0, il = array.length; i < il; i++) {
  23780. // Implicitly assumes little-endian.
  23781. s += String.fromCharCode(array[i]);
  23782. }
  23783. try {
  23784. // merges multi-byte utf-8 characters.
  23785. return decodeURIComponent(escape(s));
  23786. } catch (e) {
  23787. // see #16358
  23788. return s;
  23789. }
  23790. },
  23791. extractUrlBase: function (url) {
  23792. var index = url.lastIndexOf('/');
  23793. if (index === -1) return './';
  23794. return url.substr(0, index + 1);
  23795. }
  23796. };
  23797. /**
  23798. * @author benaadams / https://twitter.com/ben_a_adams
  23799. */
  23800. exports.LoaderUtils = LoaderUtils;
  23801. function InstancedBufferGeometry() {
  23802. BufferGeometry.call(this);
  23803. this.type = 'InstancedBufferGeometry';
  23804. this.maxInstancedCount = undefined;
  23805. }
  23806. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  23807. constructor: InstancedBufferGeometry,
  23808. isInstancedBufferGeometry: true,
  23809. copy: function (source) {
  23810. BufferGeometry.prototype.copy.call(this, source);
  23811. this.maxInstancedCount = source.maxInstancedCount;
  23812. return this;
  23813. },
  23814. clone: function () {
  23815. return new this.constructor().copy(this);
  23816. },
  23817. toJSON: function () {
  23818. var data = BufferGeometry.prototype.toJSON.call(this);
  23819. data.maxInstancedCount = this.maxInstancedCount;
  23820. data.isInstancedBufferGeometry = true;
  23821. return data;
  23822. }
  23823. });
  23824. /**
  23825. * @author benaadams / https://twitter.com/ben_a_adams
  23826. */
  23827. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  23828. if (typeof normalized === 'number') {
  23829. meshPerAttribute = normalized;
  23830. normalized = false;
  23831. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23832. }
  23833. BufferAttribute.call(this, array, itemSize, normalized);
  23834. this.meshPerAttribute = meshPerAttribute || 1;
  23835. }
  23836. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  23837. constructor: InstancedBufferAttribute,
  23838. isInstancedBufferAttribute: true,
  23839. copy: function (source) {
  23840. BufferAttribute.prototype.copy.call(this, source);
  23841. this.meshPerAttribute = source.meshPerAttribute;
  23842. return this;
  23843. },
  23844. toJSON: function () {
  23845. var data = BufferAttribute.prototype.toJSON.call(this);
  23846. data.meshPerAttribute = this.meshPerAttribute;
  23847. data.isInstancedBufferAttribute = true;
  23848. return data;
  23849. }
  23850. });
  23851. /**
  23852. * @author mrdoob / http://mrdoob.com/
  23853. */
  23854. function BufferGeometryLoader(manager) {
  23855. Loader.call(this, manager);
  23856. }
  23857. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23858. constructor: BufferGeometryLoader,
  23859. load: function (url, onLoad, onProgress, onError) {
  23860. var scope = this;
  23861. var loader = new FileLoader(scope.manager);
  23862. loader.setPath(scope.path);
  23863. loader.load(url, function (text) {
  23864. onLoad(scope.parse(JSON.parse(text)));
  23865. }, onProgress, onError);
  23866. },
  23867. parse: function (json) {
  23868. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23869. var index = json.data.index;
  23870. if (index !== undefined) {
  23871. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  23872. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23873. }
  23874. var attributes = json.data.attributes;
  23875. for (var key in attributes) {
  23876. var attribute = attributes[key];
  23877. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23878. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23879. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23880. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23881. geometry.setAttribute(key, bufferAttribute);
  23882. }
  23883. var morphAttributes = json.data.morphAttributes;
  23884. if (morphAttributes) {
  23885. for (var key in morphAttributes) {
  23886. var attributeArray = morphAttributes[key];
  23887. var array = [];
  23888. for (var i = 0, il = attributeArray.length; i < il; i++) {
  23889. var attribute = attributeArray[i];
  23890. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23891. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23892. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23893. array.push(bufferAttribute);
  23894. }
  23895. geometry.morphAttributes[key] = array;
  23896. }
  23897. }
  23898. var morphTargetsRelative = json.data.morphTargetsRelative;
  23899. if (morphTargetsRelative) {
  23900. geometry.morphTargetsRelative = true;
  23901. }
  23902. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23903. if (groups !== undefined) {
  23904. for (var i = 0, n = groups.length; i !== n; ++i) {
  23905. var group = groups[i];
  23906. geometry.addGroup(group.start, group.count, group.materialIndex);
  23907. }
  23908. }
  23909. var boundingSphere = json.data.boundingSphere;
  23910. if (boundingSphere !== undefined) {
  23911. var center = new Vector3();
  23912. if (boundingSphere.center !== undefined) {
  23913. center.fromArray(boundingSphere.center);
  23914. }
  23915. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23916. }
  23917. if (json.name) geometry.name = json.name;
  23918. if (json.userData) geometry.userData = json.userData;
  23919. return geometry;
  23920. }
  23921. });
  23922. var TYPED_ARRAYS = {
  23923. Int8Array: Int8Array,
  23924. Uint8Array: Uint8Array,
  23925. // Workaround for IE11 pre KB2929437. See #11440
  23926. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  23927. Int16Array: Int16Array,
  23928. Uint16Array: Uint16Array,
  23929. Int32Array: Int32Array,
  23930. Uint32Array: Uint32Array,
  23931. Float32Array: Float32Array,
  23932. Float64Array: Float64Array
  23933. };
  23934. /**
  23935. * @author mrdoob / http://mrdoob.com/
  23936. */
  23937. function ObjectLoader(manager) {
  23938. Loader.call(this, manager);
  23939. }
  23940. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23941. constructor: ObjectLoader,
  23942. load: function (url, onLoad, onProgress, onError) {
  23943. var scope = this;
  23944. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23945. this.resourcePath = this.resourcePath || path;
  23946. var loader = new FileLoader(scope.manager);
  23947. loader.setPath(this.path);
  23948. loader.load(url, function (text) {
  23949. var json = null;
  23950. try {
  23951. json = JSON.parse(text);
  23952. } catch (error) {
  23953. if (onError !== undefined) onError(error);
  23954. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23955. return;
  23956. }
  23957. var metadata = json.metadata;
  23958. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23959. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23960. return;
  23961. }
  23962. scope.parse(json, onLoad);
  23963. }, onProgress, onError);
  23964. },
  23965. parse: function (json, onLoad) {
  23966. var shapes = this.parseShape(json.shapes);
  23967. var geometries = this.parseGeometries(json.geometries, shapes);
  23968. var images = this.parseImages(json.images, function () {
  23969. if (onLoad !== undefined) onLoad(object);
  23970. });
  23971. var textures = this.parseTextures(json.textures, images);
  23972. var materials = this.parseMaterials(json.materials, textures);
  23973. var object = this.parseObject(json.object, geometries, materials);
  23974. if (json.animations) {
  23975. object.animations = this.parseAnimations(json.animations);
  23976. }
  23977. if (json.images === undefined || json.images.length === 0) {
  23978. if (onLoad !== undefined) onLoad(object);
  23979. }
  23980. return object;
  23981. },
  23982. parseShape: function (json) {
  23983. var shapes = {};
  23984. if (json !== undefined) {
  23985. for (var i = 0, l = json.length; i < l; i++) {
  23986. var shape = new Shape().fromJSON(json[i]);
  23987. shapes[shape.uuid] = shape;
  23988. }
  23989. }
  23990. return shapes;
  23991. },
  23992. parseGeometries: function (json, shapes) {
  23993. var geometries = {};
  23994. if (json !== undefined) {
  23995. var bufferGeometryLoader = new BufferGeometryLoader();
  23996. for (var i = 0, l = json.length; i < l; i++) {
  23997. var geometry;
  23998. var data = json[i];
  23999. switch (data.type) {
  24000. case 'PlaneGeometry':
  24001. case 'PlaneBufferGeometry':
  24002. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24003. break;
  24004. case 'BoxGeometry':
  24005. case 'BoxBufferGeometry':
  24006. case 'CubeGeometry':
  24007. // backwards compatible
  24008. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24009. break;
  24010. case 'CircleGeometry':
  24011. case 'CircleBufferGeometry':
  24012. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24013. break;
  24014. case 'CylinderGeometry':
  24015. case 'CylinderBufferGeometry':
  24016. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24017. break;
  24018. case 'ConeGeometry':
  24019. case 'ConeBufferGeometry':
  24020. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24021. break;
  24022. case 'SphereGeometry':
  24023. case 'SphereBufferGeometry':
  24024. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24025. break;
  24026. case 'DodecahedronGeometry':
  24027. case 'DodecahedronBufferGeometry':
  24028. case 'IcosahedronGeometry':
  24029. case 'IcosahedronBufferGeometry':
  24030. case 'OctahedronGeometry':
  24031. case 'OctahedronBufferGeometry':
  24032. case 'TetrahedronGeometry':
  24033. case 'TetrahedronBufferGeometry':
  24034. geometry = new Geometries[data.type](data.radius, data.detail);
  24035. break;
  24036. case 'RingGeometry':
  24037. case 'RingBufferGeometry':
  24038. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24039. break;
  24040. case 'TorusGeometry':
  24041. case 'TorusBufferGeometry':
  24042. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24043. break;
  24044. case 'TorusKnotGeometry':
  24045. case 'TorusKnotBufferGeometry':
  24046. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24047. break;
  24048. case 'TubeGeometry':
  24049. case 'TubeBufferGeometry':
  24050. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24051. // User defined curves or instances of CurvePath will not be deserialized.
  24052. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24053. break;
  24054. case 'LatheGeometry':
  24055. case 'LatheBufferGeometry':
  24056. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24057. break;
  24058. case 'PolyhedronGeometry':
  24059. case 'PolyhedronBufferGeometry':
  24060. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24061. break;
  24062. case 'ShapeGeometry':
  24063. case 'ShapeBufferGeometry':
  24064. var geometryShapes = [];
  24065. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24066. var shape = shapes[data.shapes[j]];
  24067. geometryShapes.push(shape);
  24068. }
  24069. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24070. break;
  24071. case 'ExtrudeGeometry':
  24072. case 'ExtrudeBufferGeometry':
  24073. var geometryShapes = [];
  24074. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24075. var shape = shapes[data.shapes[j]];
  24076. geometryShapes.push(shape);
  24077. }
  24078. var extrudePath = data.options.extrudePath;
  24079. if (extrudePath !== undefined) {
  24080. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24081. }
  24082. geometry = new Geometries[data.type](geometryShapes, data.options);
  24083. break;
  24084. case 'BufferGeometry':
  24085. case 'InstancedBufferGeometry':
  24086. geometry = bufferGeometryLoader.parse(data);
  24087. break;
  24088. case 'Geometry':
  24089. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  24090. break;
  24091. default:
  24092. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24093. continue;
  24094. }
  24095. geometry.uuid = data.uuid;
  24096. if (data.name !== undefined) geometry.name = data.name;
  24097. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24098. geometries[data.uuid] = geometry;
  24099. }
  24100. }
  24101. return geometries;
  24102. },
  24103. parseMaterials: function (json, textures) {
  24104. var cache = {}; // MultiMaterial
  24105. var materials = {};
  24106. if (json !== undefined) {
  24107. var loader = new MaterialLoader();
  24108. loader.setTextures(textures);
  24109. for (var i = 0, l = json.length; i < l; i++) {
  24110. var data = json[i];
  24111. if (data.type === 'MultiMaterial') {
  24112. // Deprecated
  24113. var array = [];
  24114. for (var j = 0; j < data.materials.length; j++) {
  24115. var material = data.materials[j];
  24116. if (cache[material.uuid] === undefined) {
  24117. cache[material.uuid] = loader.parse(material);
  24118. }
  24119. array.push(cache[material.uuid]);
  24120. }
  24121. materials[data.uuid] = array;
  24122. } else {
  24123. if (cache[data.uuid] === undefined) {
  24124. cache[data.uuid] = loader.parse(data);
  24125. }
  24126. materials[data.uuid] = cache[data.uuid];
  24127. }
  24128. }
  24129. }
  24130. return materials;
  24131. },
  24132. parseAnimations: function (json) {
  24133. var animations = [];
  24134. for (var i = 0; i < json.length; i++) {
  24135. var data = json[i];
  24136. var clip = AnimationClip.parse(data);
  24137. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24138. animations.push(clip);
  24139. }
  24140. return animations;
  24141. },
  24142. parseImages: function (json, onLoad) {
  24143. var scope = this;
  24144. var images = {};
  24145. function loadImage(url) {
  24146. scope.manager.itemStart(url);
  24147. return loader.load(url, function () {
  24148. scope.manager.itemEnd(url);
  24149. }, undefined, function () {
  24150. scope.manager.itemError(url);
  24151. scope.manager.itemEnd(url);
  24152. });
  24153. }
  24154. if (json !== undefined && json.length > 0) {
  24155. var manager = new LoadingManager(onLoad);
  24156. var loader = new ImageLoader(manager);
  24157. loader.setCrossOrigin(this.crossOrigin);
  24158. for (var i = 0, il = json.length; i < il; i++) {
  24159. var image = json[i];
  24160. var url = image.url;
  24161. if (Array.isArray(url)) {
  24162. // load array of images e.g CubeTexture
  24163. images[image.uuid] = [];
  24164. for (var j = 0, jl = url.length; j < jl; j++) {
  24165. var currentUrl = url[j];
  24166. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24167. images[image.uuid].push(loadImage(path));
  24168. }
  24169. } else {
  24170. // load single image
  24171. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24172. images[image.uuid] = loadImage(path);
  24173. }
  24174. }
  24175. }
  24176. return images;
  24177. },
  24178. parseTextures: function (json, images) {
  24179. function parseConstant(value, type) {
  24180. if (typeof value === 'number') return value;
  24181. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24182. return type[value];
  24183. }
  24184. var textures = {};
  24185. if (json !== undefined) {
  24186. for (var i = 0, l = json.length; i < l; i++) {
  24187. var data = json[i];
  24188. if (data.image === undefined) {
  24189. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24190. }
  24191. if (images[data.image] === undefined) {
  24192. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24193. }
  24194. var texture;
  24195. if (Array.isArray(images[data.image])) {
  24196. texture = new CubeTexture(images[data.image]);
  24197. } else {
  24198. texture = new Texture(images[data.image]);
  24199. }
  24200. texture.needsUpdate = true;
  24201. texture.uuid = data.uuid;
  24202. if (data.name !== undefined) texture.name = data.name;
  24203. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24204. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24205. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24206. if (data.center !== undefined) texture.center.fromArray(data.center);
  24207. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24208. if (data.wrap !== undefined) {
  24209. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24210. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24211. }
  24212. if (data.format !== undefined) texture.format = data.format;
  24213. if (data.type !== undefined) texture.type = data.type;
  24214. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24215. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24216. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24217. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24218. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24219. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24220. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24221. textures[data.uuid] = texture;
  24222. }
  24223. }
  24224. return textures;
  24225. },
  24226. parseObject: function (data, geometries, materials) {
  24227. var object;
  24228. function getGeometry(name) {
  24229. if (geometries[name] === undefined) {
  24230. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24231. }
  24232. return geometries[name];
  24233. }
  24234. function getMaterial(name) {
  24235. if (name === undefined) return undefined;
  24236. if (Array.isArray(name)) {
  24237. var array = [];
  24238. for (var i = 0, l = name.length; i < l; i++) {
  24239. var uuid = name[i];
  24240. if (materials[uuid] === undefined) {
  24241. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24242. }
  24243. array.push(materials[uuid]);
  24244. }
  24245. return array;
  24246. }
  24247. if (materials[name] === undefined) {
  24248. console.warn('THREE.ObjectLoader: Undefined material', name);
  24249. }
  24250. return materials[name];
  24251. }
  24252. switch (data.type) {
  24253. case 'Scene':
  24254. object = new Scene();
  24255. if (data.background !== undefined) {
  24256. if (Number.isInteger(data.background)) {
  24257. object.background = new Color(data.background);
  24258. }
  24259. }
  24260. if (data.fog !== undefined) {
  24261. if (data.fog.type === 'Fog') {
  24262. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24263. } else if (data.fog.type === 'FogExp2') {
  24264. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24265. }
  24266. }
  24267. break;
  24268. case 'PerspectiveCamera':
  24269. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24270. if (data.focus !== undefined) object.focus = data.focus;
  24271. if (data.zoom !== undefined) object.zoom = data.zoom;
  24272. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24273. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24274. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24275. break;
  24276. case 'OrthographicCamera':
  24277. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24278. if (data.zoom !== undefined) object.zoom = data.zoom;
  24279. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24280. break;
  24281. case 'AmbientLight':
  24282. object = new AmbientLight(data.color, data.intensity);
  24283. break;
  24284. case 'DirectionalLight':
  24285. object = new DirectionalLight(data.color, data.intensity);
  24286. break;
  24287. case 'PointLight':
  24288. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24289. break;
  24290. case 'RectAreaLight':
  24291. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24292. break;
  24293. case 'SpotLight':
  24294. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24295. break;
  24296. case 'HemisphereLight':
  24297. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24298. break;
  24299. case 'SkinnedMesh':
  24300. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  24301. case 'Mesh':
  24302. var geometry = getGeometry(data.geometry);
  24303. var material = getMaterial(data.material);
  24304. object = new Mesh(geometry, material);
  24305. break;
  24306. case 'InstancedMesh':
  24307. var geometry = getGeometry(data.geometry);
  24308. var material = getMaterial(data.material);
  24309. var count = data.count;
  24310. var instanceMatrix = data.instanceMatrix;
  24311. object = new InstancedMesh(geometry, material, count);
  24312. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24313. break;
  24314. case 'LOD':
  24315. object = new LOD();
  24316. break;
  24317. case 'Line':
  24318. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  24319. break;
  24320. case 'LineLoop':
  24321. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24322. break;
  24323. case 'LineSegments':
  24324. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24325. break;
  24326. case 'PointCloud':
  24327. case 'Points':
  24328. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24329. break;
  24330. case 'Sprite':
  24331. object = new Sprite(getMaterial(data.material));
  24332. break;
  24333. case 'Group':
  24334. object = new Group();
  24335. break;
  24336. default:
  24337. object = new Object3D();
  24338. }
  24339. object.uuid = data.uuid;
  24340. if (data.name !== undefined) object.name = data.name;
  24341. if (data.matrix !== undefined) {
  24342. object.matrix.fromArray(data.matrix);
  24343. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24344. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24345. } else {
  24346. if (data.position !== undefined) object.position.fromArray(data.position);
  24347. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24348. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24349. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24350. }
  24351. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24352. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24353. if (data.shadow) {
  24354. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24355. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24356. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24357. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24358. }
  24359. if (data.visible !== undefined) object.visible = data.visible;
  24360. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24361. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24362. if (data.userData !== undefined) object.userData = data.userData;
  24363. if (data.layers !== undefined) object.layers.mask = data.layers;
  24364. if (data.children !== undefined) {
  24365. var children = data.children;
  24366. for (var i = 0; i < children.length; i++) {
  24367. object.add(this.parseObject(children[i], geometries, materials));
  24368. }
  24369. }
  24370. if (data.type === 'LOD') {
  24371. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24372. var levels = data.levels;
  24373. for (var l = 0; l < levels.length; l++) {
  24374. var level = levels[l];
  24375. var child = object.getObjectByProperty('uuid', level.object);
  24376. if (child !== undefined) {
  24377. object.addLevel(child, level.distance);
  24378. }
  24379. }
  24380. }
  24381. return object;
  24382. }
  24383. });
  24384. var TEXTURE_MAPPING = {
  24385. UVMapping: UVMapping,
  24386. CubeReflectionMapping: CubeReflectionMapping,
  24387. CubeRefractionMapping: CubeRefractionMapping,
  24388. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24389. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24390. SphericalReflectionMapping: SphericalReflectionMapping,
  24391. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24392. CubeUVRefractionMapping: CubeUVRefractionMapping
  24393. };
  24394. var TEXTURE_WRAPPING = {
  24395. RepeatWrapping: RepeatWrapping,
  24396. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24397. MirroredRepeatWrapping: MirroredRepeatWrapping
  24398. };
  24399. var TEXTURE_FILTER = {
  24400. NearestFilter: NearestFilter,
  24401. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24402. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24403. LinearFilter: LinearFilter,
  24404. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24405. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24406. };
  24407. /**
  24408. * @author thespite / http://clicktorelease.com/
  24409. */
  24410. function ImageBitmapLoader(manager) {
  24411. if (typeof createImageBitmap === 'undefined') {
  24412. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24413. }
  24414. if (typeof fetch === 'undefined') {
  24415. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24416. }
  24417. Loader.call(this, manager);
  24418. this.options = undefined;
  24419. }
  24420. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24421. constructor: ImageBitmapLoader,
  24422. setOptions: function setOptions(options) {
  24423. this.options = options;
  24424. return this;
  24425. },
  24426. load: function (url, onLoad, onProgress, onError) {
  24427. if (url === undefined) url = '';
  24428. if (this.path !== undefined) url = this.path + url;
  24429. url = this.manager.resolveURL(url);
  24430. var scope = this;
  24431. var cached = Cache.get(url);
  24432. if (cached !== undefined) {
  24433. scope.manager.itemStart(url);
  24434. setTimeout(function () {
  24435. if (onLoad) onLoad(cached);
  24436. scope.manager.itemEnd(url);
  24437. }, 0);
  24438. return cached;
  24439. }
  24440. fetch(url).then(function (res) {
  24441. return res.blob();
  24442. }).then(function (blob) {
  24443. if (scope.options === undefined) {
  24444. // Workaround for FireFox. It causes an error if you pass options.
  24445. return createImageBitmap(blob);
  24446. } else {
  24447. return createImageBitmap(blob, scope.options);
  24448. }
  24449. }).then(function (imageBitmap) {
  24450. Cache.add(url, imageBitmap);
  24451. if (onLoad) onLoad(imageBitmap);
  24452. scope.manager.itemEnd(url);
  24453. }).catch(function (e) {
  24454. if (onError) onError(e);
  24455. scope.manager.itemError(url);
  24456. scope.manager.itemEnd(url);
  24457. });
  24458. scope.manager.itemStart(url);
  24459. }
  24460. });
  24461. /**
  24462. * @author zz85 / http://www.lab4games.net/zz85/blog
  24463. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  24464. **/
  24465. function ShapePath() {
  24466. this.type = 'ShapePath';
  24467. this.color = new Color();
  24468. this.subPaths = [];
  24469. this.currentPath = null;
  24470. }
  24471. Object.assign(ShapePath.prototype, {
  24472. moveTo: function (x, y) {
  24473. this.currentPath = new Path();
  24474. this.subPaths.push(this.currentPath);
  24475. this.currentPath.moveTo(x, y);
  24476. return this;
  24477. },
  24478. lineTo: function (x, y) {
  24479. this.currentPath.lineTo(x, y);
  24480. return this;
  24481. },
  24482. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  24483. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24484. return this;
  24485. },
  24486. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24487. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24488. return this;
  24489. },
  24490. splineThru: function (pts) {
  24491. this.currentPath.splineThru(pts);
  24492. return this;
  24493. },
  24494. toShapes: function (isCCW, noHoles) {
  24495. function toShapesNoHoles(inSubpaths) {
  24496. var shapes = [];
  24497. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  24498. var tmpPath = inSubpaths[i];
  24499. var tmpShape = new Shape();
  24500. tmpShape.curves = tmpPath.curves;
  24501. shapes.push(tmpShape);
  24502. }
  24503. return shapes;
  24504. }
  24505. function isPointInsidePolygon(inPt, inPolygon) {
  24506. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24507. // toggling of inside/outside at every single! intersection point of an edge
  24508. // with the horizontal line through inPt, left of inPt
  24509. // not counting lowerY endpoints of edges and whole edges on that line
  24510. var inside = false;
  24511. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24512. var edgeLowPt = inPolygon[p];
  24513. var edgeHighPt = inPolygon[q];
  24514. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  24515. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  24516. if (Math.abs(edgeDy) > Number.EPSILON) {
  24517. // not parallel
  24518. if (edgeDy < 0) {
  24519. edgeLowPt = inPolygon[q];
  24520. edgeDx = -edgeDx;
  24521. edgeHighPt = inPolygon[p];
  24522. edgeDy = -edgeDy;
  24523. }
  24524. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24525. if (inPt.y === edgeLowPt.y) {
  24526. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24527. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24528. } else {
  24529. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24530. if (perpEdge === 0) return true; // inPt is on contour ?
  24531. if (perpEdge < 0) continue;
  24532. inside = !inside; // true intersection left of inPt
  24533. }
  24534. } else {
  24535. // parallel or collinear
  24536. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24537. // edge lies on the same horizontal line as inPt
  24538. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24539. // continue;
  24540. }
  24541. }
  24542. return inside;
  24543. }
  24544. var isClockWise = ShapeUtils.isClockWise;
  24545. var subPaths = this.subPaths;
  24546. if (subPaths.length === 0) return [];
  24547. if (noHoles === true) return toShapesNoHoles(subPaths);
  24548. var solid,
  24549. tmpPath,
  24550. tmpShape,
  24551. shapes = [];
  24552. if (subPaths.length === 1) {
  24553. tmpPath = subPaths[0];
  24554. tmpShape = new Shape();
  24555. tmpShape.curves = tmpPath.curves;
  24556. shapes.push(tmpShape);
  24557. return shapes;
  24558. }
  24559. var holesFirst = !isClockWise(subPaths[0].getPoints());
  24560. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24561. var betterShapeHoles = [];
  24562. var newShapes = [];
  24563. var newShapeHoles = [];
  24564. var mainIdx = 0;
  24565. var tmpPoints;
  24566. newShapes[mainIdx] = undefined;
  24567. newShapeHoles[mainIdx] = [];
  24568. for (var i = 0, l = subPaths.length; i < l; i++) {
  24569. tmpPath = subPaths[i];
  24570. tmpPoints = tmpPath.getPoints();
  24571. solid = isClockWise(tmpPoints);
  24572. solid = isCCW ? !solid : solid;
  24573. if (solid) {
  24574. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24575. newShapes[mainIdx] = {
  24576. s: new Shape(),
  24577. p: tmpPoints
  24578. };
  24579. newShapes[mainIdx].s.curves = tmpPath.curves;
  24580. if (holesFirst) mainIdx++;
  24581. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24582. } else {
  24583. newShapeHoles[mainIdx].push({
  24584. h: tmpPath,
  24585. p: tmpPoints[0]
  24586. }); //console.log('ccw', i);
  24587. }
  24588. } // only Holes? -> probably all Shapes with wrong orientation
  24589. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24590. if (newShapes.length > 1) {
  24591. var ambiguous = false;
  24592. var toChange = [];
  24593. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24594. betterShapeHoles[sIdx] = [];
  24595. }
  24596. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24597. var sho = newShapeHoles[sIdx];
  24598. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  24599. var ho = sho[hIdx];
  24600. var hole_unassigned = true;
  24601. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24602. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24603. if (sIdx !== s2Idx) toChange.push({
  24604. froms: sIdx,
  24605. tos: s2Idx,
  24606. hole: hIdx
  24607. });
  24608. if (hole_unassigned) {
  24609. hole_unassigned = false;
  24610. betterShapeHoles[s2Idx].push(ho);
  24611. } else {
  24612. ambiguous = true;
  24613. }
  24614. }
  24615. }
  24616. if (hole_unassigned) {
  24617. betterShapeHoles[sIdx].push(ho);
  24618. }
  24619. }
  24620. } // console.log("ambiguous: ", ambiguous);
  24621. if (toChange.length > 0) {
  24622. // console.log("to change: ", toChange);
  24623. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24624. }
  24625. }
  24626. var tmpHoles;
  24627. for (var i = 0, il = newShapes.length; i < il; i++) {
  24628. tmpShape = newShapes[i].s;
  24629. shapes.push(tmpShape);
  24630. tmpHoles = newShapeHoles[i];
  24631. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  24632. tmpShape.holes.push(tmpHoles[j].h);
  24633. }
  24634. } //console.log("shape", shapes);
  24635. return shapes;
  24636. }
  24637. });
  24638. /**
  24639. * @author zz85 / http://www.lab4games.net/zz85/blog
  24640. * @author mrdoob / http://mrdoob.com/
  24641. */
  24642. function Font(data) {
  24643. this.type = 'Font';
  24644. this.data = data;
  24645. }
  24646. Object.assign(Font.prototype, {
  24647. isFont: true,
  24648. generateShapes: function (text, size) {
  24649. if (size === undefined) size = 100;
  24650. var shapes = [];
  24651. var paths = createPaths(text, size, this.data);
  24652. for (var p = 0, pl = paths.length; p < pl; p++) {
  24653. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24654. }
  24655. return shapes;
  24656. }
  24657. });
  24658. function createPaths(text, size, data) {
  24659. var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  24660. var scale = size / data.resolution;
  24661. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24662. var paths = [];
  24663. var offsetX = 0,
  24664. offsetY = 0;
  24665. for (var i = 0; i < chars.length; i++) {
  24666. var char = chars[i];
  24667. if (char === '\n') {
  24668. offsetX = 0;
  24669. offsetY -= line_height;
  24670. } else {
  24671. var ret = createPath(char, scale, offsetX, offsetY, data);
  24672. offsetX += ret.offsetX;
  24673. paths.push(ret.path);
  24674. }
  24675. }
  24676. return paths;
  24677. }
  24678. function createPath(char, scale, offsetX, offsetY, data) {
  24679. var glyph = data.glyphs[char] || data.glyphs['?'];
  24680. if (!glyph) {
  24681. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24682. return;
  24683. }
  24684. var path = new ShapePath();
  24685. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24686. if (glyph.o) {
  24687. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24688. for (var i = 0, l = outline.length; i < l;) {
  24689. var action = outline[i++];
  24690. switch (action) {
  24691. case 'm':
  24692. // moveTo
  24693. x = outline[i++] * scale + offsetX;
  24694. y = outline[i++] * scale + offsetY;
  24695. path.moveTo(x, y);
  24696. break;
  24697. case 'l':
  24698. // lineTo
  24699. x = outline[i++] * scale + offsetX;
  24700. y = outline[i++] * scale + offsetY;
  24701. path.lineTo(x, y);
  24702. break;
  24703. case 'q':
  24704. // quadraticCurveTo
  24705. cpx = outline[i++] * scale + offsetX;
  24706. cpy = outline[i++] * scale + offsetY;
  24707. cpx1 = outline[i++] * scale + offsetX;
  24708. cpy1 = outline[i++] * scale + offsetY;
  24709. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24710. break;
  24711. case 'b':
  24712. // bezierCurveTo
  24713. cpx = outline[i++] * scale + offsetX;
  24714. cpy = outline[i++] * scale + offsetY;
  24715. cpx1 = outline[i++] * scale + offsetX;
  24716. cpy1 = outline[i++] * scale + offsetY;
  24717. cpx2 = outline[i++] * scale + offsetX;
  24718. cpy2 = outline[i++] * scale + offsetY;
  24719. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24720. break;
  24721. }
  24722. }
  24723. }
  24724. return {
  24725. offsetX: glyph.ha * scale,
  24726. path: path
  24727. };
  24728. }
  24729. /**
  24730. * @author mrdoob / http://mrdoob.com/
  24731. */
  24732. function FontLoader(manager) {
  24733. Loader.call(this, manager);
  24734. }
  24735. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24736. constructor: FontLoader,
  24737. load: function (url, onLoad, onProgress, onError) {
  24738. var scope = this;
  24739. var loader = new FileLoader(this.manager);
  24740. loader.setPath(this.path);
  24741. loader.load(url, function (text) {
  24742. var json;
  24743. try {
  24744. json = JSON.parse(text);
  24745. } catch (e) {
  24746. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24747. json = JSON.parse(text.substring(65, text.length - 2));
  24748. }
  24749. var font = scope.parse(json);
  24750. if (onLoad) onLoad(font);
  24751. }, onProgress, onError);
  24752. },
  24753. parse: function (json) {
  24754. return new Font(json);
  24755. }
  24756. });
  24757. /**
  24758. * @author mrdoob / http://mrdoob.com/
  24759. */
  24760. var _context;
  24761. var AudioContext = {
  24762. getContext: function () {
  24763. if (_context === undefined) {
  24764. _context = new (window.AudioContext || window.webkitAudioContext)();
  24765. }
  24766. return _context;
  24767. },
  24768. setContext: function (value) {
  24769. _context = value;
  24770. }
  24771. };
  24772. /**
  24773. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24774. */
  24775. exports.AudioContext = AudioContext;
  24776. function AudioLoader(manager) {
  24777. Loader.call(this, manager);
  24778. }
  24779. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24780. constructor: AudioLoader,
  24781. load: function (url, onLoad, onProgress, onError) {
  24782. var loader = new FileLoader(this.manager);
  24783. loader.setResponseType('arraybuffer');
  24784. loader.setPath(this.path);
  24785. loader.load(url, function (buffer) {
  24786. // Create a copy of the buffer. The `decodeAudioData` method
  24787. // detaches the buffer when complete, preventing reuse.
  24788. var bufferCopy = buffer.slice(0);
  24789. var context = AudioContext.getContext();
  24790. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24791. onLoad(audioBuffer);
  24792. });
  24793. }, onProgress, onError);
  24794. }
  24795. });
  24796. /**
  24797. * @author bhouston / http://clara.io
  24798. * @author WestLangley / http://github.com/WestLangley
  24799. *
  24800. * Primary reference:
  24801. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24802. *
  24803. * Secondary reference:
  24804. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24805. */
  24806. // 3-band SH defined by 9 coefficients
  24807. function SphericalHarmonics3() {
  24808. this.coefficients = [];
  24809. for (var i = 0; i < 9; i++) {
  24810. this.coefficients.push(new Vector3());
  24811. }
  24812. }
  24813. Object.assign(SphericalHarmonics3.prototype, {
  24814. isSphericalHarmonics3: true,
  24815. set: function (coefficients) {
  24816. for (var i = 0; i < 9; i++) {
  24817. this.coefficients[i].copy(coefficients[i]);
  24818. }
  24819. return this;
  24820. },
  24821. zero: function () {
  24822. for (var i = 0; i < 9; i++) {
  24823. this.coefficients[i].set(0, 0, 0);
  24824. }
  24825. return this;
  24826. },
  24827. // get the radiance in the direction of the normal
  24828. // target is a Vector3
  24829. getAt: function (normal, target) {
  24830. // normal is assumed to be unit length
  24831. var x = normal.x,
  24832. y = normal.y,
  24833. z = normal.z;
  24834. var coeff = this.coefficients; // band 0
  24835. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24836. target.addScaledVector(coeff[1], 0.488603 * y);
  24837. target.addScaledVector(coeff[2], 0.488603 * z);
  24838. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  24839. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24840. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24841. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24842. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24843. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24844. return target;
  24845. },
  24846. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24847. // target is a Vector3
  24848. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24849. getIrradianceAt: function (normal, target) {
  24850. // normal is assumed to be unit length
  24851. var x = normal.x,
  24852. y = normal.y,
  24853. z = normal.z;
  24854. var coeff = this.coefficients; // band 0
  24855. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24856. // band 1
  24857. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24858. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24859. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  24860. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24861. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24862. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24863. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24864. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24865. return target;
  24866. },
  24867. add: function (sh) {
  24868. for (var i = 0; i < 9; i++) {
  24869. this.coefficients[i].add(sh.coefficients[i]);
  24870. }
  24871. return this;
  24872. },
  24873. addScaledSH: function (sh, s) {
  24874. for (var i = 0; i < 9; i++) {
  24875. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24876. }
  24877. return this;
  24878. },
  24879. scale: function (s) {
  24880. for (var i = 0; i < 9; i++) {
  24881. this.coefficients[i].multiplyScalar(s);
  24882. }
  24883. return this;
  24884. },
  24885. lerp: function (sh, alpha) {
  24886. for (var i = 0; i < 9; i++) {
  24887. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24888. }
  24889. return this;
  24890. },
  24891. equals: function (sh) {
  24892. for (var i = 0; i < 9; i++) {
  24893. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24894. return false;
  24895. }
  24896. }
  24897. return true;
  24898. },
  24899. copy: function (sh) {
  24900. return this.set(sh.coefficients);
  24901. },
  24902. clone: function () {
  24903. return new this.constructor().copy(this);
  24904. },
  24905. fromArray: function (array, offset) {
  24906. if (offset === undefined) offset = 0;
  24907. var coefficients = this.coefficients;
  24908. for (var i = 0; i < 9; i++) {
  24909. coefficients[i].fromArray(array, offset + i * 3);
  24910. }
  24911. return this;
  24912. },
  24913. toArray: function (array, offset) {
  24914. if (array === undefined) array = [];
  24915. if (offset === undefined) offset = 0;
  24916. var coefficients = this.coefficients;
  24917. for (var i = 0; i < 9; i++) {
  24918. coefficients[i].toArray(array, offset + i * 3);
  24919. }
  24920. return array;
  24921. }
  24922. });
  24923. Object.assign(SphericalHarmonics3, {
  24924. // evaluate the basis functions
  24925. // shBasis is an Array[ 9 ]
  24926. getBasisAt: function (normal, shBasis) {
  24927. // normal is assumed to be unit length
  24928. var x = normal.x,
  24929. y = normal.y,
  24930. z = normal.z; // band 0
  24931. shBasis[0] = 0.282095; // band 1
  24932. shBasis[1] = 0.488603 * y;
  24933. shBasis[2] = 0.488603 * z;
  24934. shBasis[3] = 0.488603 * x; // band 2
  24935. shBasis[4] = 1.092548 * x * y;
  24936. shBasis[5] = 1.092548 * y * z;
  24937. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24938. shBasis[7] = 1.092548 * x * z;
  24939. shBasis[8] = 0.546274 * (x * x - y * y);
  24940. }
  24941. });
  24942. /**
  24943. * @author WestLangley / http://github.com/WestLangley
  24944. *
  24945. * A LightProbe is a source of indirect-diffuse light
  24946. */
  24947. function LightProbe(sh, intensity) {
  24948. Light.call(this, undefined, intensity);
  24949. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24950. }
  24951. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24952. constructor: LightProbe,
  24953. isLightProbe: true,
  24954. copy: function (source) {
  24955. Light.prototype.copy.call(this, source);
  24956. this.sh.copy(source.sh);
  24957. this.intensity = source.intensity;
  24958. return this;
  24959. },
  24960. toJSON: function (meta) {
  24961. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24962. return data;
  24963. }
  24964. });
  24965. /**
  24966. * @author WestLangley / http://github.com/WestLangley
  24967. */
  24968. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  24969. LightProbe.call(this, undefined, intensity);
  24970. var color1 = new Color().set(skyColor);
  24971. var color2 = new Color().set(groundColor);
  24972. var sky = new Vector3(color1.r, color1.g, color1.b);
  24973. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24974. var c0 = Math.sqrt(Math.PI);
  24975. var c1 = c0 * Math.sqrt(0.75);
  24976. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24977. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24978. }
  24979. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24980. constructor: HemisphereLightProbe,
  24981. isHemisphereLightProbe: true,
  24982. copy: function (source) {
  24983. // modifying colors not currently supported
  24984. LightProbe.prototype.copy.call(this, source);
  24985. return this;
  24986. },
  24987. toJSON: function (meta) {
  24988. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24989. return data;
  24990. }
  24991. });
  24992. /**
  24993. * @author WestLangley / http://github.com/WestLangley
  24994. */
  24995. function AmbientLightProbe(color, intensity) {
  24996. LightProbe.call(this, undefined, intensity);
  24997. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24998. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24999. }
  25000. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25001. constructor: AmbientLightProbe,
  25002. isAmbientLightProbe: true,
  25003. copy: function (source) {
  25004. // modifying color not currently supported
  25005. LightProbe.prototype.copy.call(this, source);
  25006. return this;
  25007. },
  25008. toJSON: function (meta) {
  25009. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25010. return data;
  25011. }
  25012. });
  25013. var _eyeRight = new Matrix4();
  25014. var _eyeLeft = new Matrix4();
  25015. /**
  25016. * @author mrdoob / http://mrdoob.com/
  25017. */
  25018. function StereoCamera() {
  25019. this.type = 'StereoCamera';
  25020. this.aspect = 1;
  25021. this.eyeSep = 0.064;
  25022. this.cameraL = new PerspectiveCamera();
  25023. this.cameraL.layers.enable(1);
  25024. this.cameraL.matrixAutoUpdate = false;
  25025. this.cameraR = new PerspectiveCamera();
  25026. this.cameraR.layers.enable(2);
  25027. this.cameraR.matrixAutoUpdate = false;
  25028. this._cache = {
  25029. focus: null,
  25030. fov: null,
  25031. aspect: null,
  25032. near: null,
  25033. far: null,
  25034. zoom: null,
  25035. eyeSep: null
  25036. };
  25037. }
  25038. Object.assign(StereoCamera.prototype, {
  25039. update: function (camera) {
  25040. var cache = this._cache;
  25041. var 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;
  25042. if (needsUpdate) {
  25043. cache.focus = camera.focus;
  25044. cache.fov = camera.fov;
  25045. cache.aspect = camera.aspect * this.aspect;
  25046. cache.near = camera.near;
  25047. cache.far = camera.far;
  25048. cache.zoom = camera.zoom;
  25049. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25050. // http://paulbourke.net/stereographics/stereorender/
  25051. var projectionMatrix = camera.projectionMatrix.clone();
  25052. var eyeSepHalf = cache.eyeSep / 2;
  25053. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25054. var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25055. var xmin, xmax; // translate xOffset
  25056. _eyeLeft.elements[12] = -eyeSepHalf;
  25057. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25058. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25059. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25060. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25061. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25062. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25063. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25064. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25065. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25066. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25067. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25068. }
  25069. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25070. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25071. }
  25072. });
  25073. /**
  25074. * @author alteredq / http://alteredqualia.com/
  25075. */
  25076. function Clock(autoStart) {
  25077. this.autoStart = autoStart !== undefined ? autoStart : true;
  25078. this.startTime = 0;
  25079. this.oldTime = 0;
  25080. this.elapsedTime = 0;
  25081. this.running = false;
  25082. }
  25083. Object.assign(Clock.prototype, {
  25084. start: function () {
  25085. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25086. this.oldTime = this.startTime;
  25087. this.elapsedTime = 0;
  25088. this.running = true;
  25089. },
  25090. stop: function () {
  25091. this.getElapsedTime();
  25092. this.running = false;
  25093. this.autoStart = false;
  25094. },
  25095. getElapsedTime: function () {
  25096. this.getDelta();
  25097. return this.elapsedTime;
  25098. },
  25099. getDelta: function () {
  25100. var diff = 0;
  25101. if (this.autoStart && !this.running) {
  25102. this.start();
  25103. return 0;
  25104. }
  25105. if (this.running) {
  25106. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25107. diff = (newTime - this.oldTime) / 1000;
  25108. this.oldTime = newTime;
  25109. this.elapsedTime += diff;
  25110. }
  25111. return diff;
  25112. }
  25113. });
  25114. /**
  25115. * @author mrdoob / http://mrdoob.com/
  25116. */
  25117. var _position$2 = new Vector3();
  25118. var _quaternion$3 = new Quaternion();
  25119. var _scale$1 = new Vector3();
  25120. var _orientation = new Vector3();
  25121. function AudioListener() {
  25122. Object3D.call(this);
  25123. this.type = 'AudioListener';
  25124. this.context = AudioContext.getContext();
  25125. this.gain = this.context.createGain();
  25126. this.gain.connect(this.context.destination);
  25127. this.filter = null;
  25128. this.timeDelta = 0; // private
  25129. this._clock = new Clock();
  25130. }
  25131. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25132. constructor: AudioListener,
  25133. getInput: function () {
  25134. return this.gain;
  25135. },
  25136. removeFilter: function () {
  25137. if (this.filter !== null) {
  25138. this.gain.disconnect(this.filter);
  25139. this.filter.disconnect(this.context.destination);
  25140. this.gain.connect(this.context.destination);
  25141. this.filter = null;
  25142. }
  25143. return this;
  25144. },
  25145. getFilter: function () {
  25146. return this.filter;
  25147. },
  25148. setFilter: function (value) {
  25149. if (this.filter !== null) {
  25150. this.gain.disconnect(this.filter);
  25151. this.filter.disconnect(this.context.destination);
  25152. } else {
  25153. this.gain.disconnect(this.context.destination);
  25154. }
  25155. this.filter = value;
  25156. this.gain.connect(this.filter);
  25157. this.filter.connect(this.context.destination);
  25158. return this;
  25159. },
  25160. getMasterVolume: function () {
  25161. return this.gain.gain.value;
  25162. },
  25163. setMasterVolume: function (value) {
  25164. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25165. return this;
  25166. },
  25167. updateMatrixWorld: function (force) {
  25168. Object3D.prototype.updateMatrixWorld.call(this, force);
  25169. var listener = this.context.listener;
  25170. var up = this.up;
  25171. this.timeDelta = this._clock.getDelta();
  25172. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25173. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25174. if (listener.positionX) {
  25175. // code path for Chrome (see #14393)
  25176. var endTime = this.context.currentTime + this.timeDelta;
  25177. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25178. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25179. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25180. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25181. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25182. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25183. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25184. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25185. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25186. } else {
  25187. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25188. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25189. }
  25190. }
  25191. });
  25192. /**
  25193. * @author mrdoob / http://mrdoob.com/
  25194. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25195. */
  25196. function Audio(listener) {
  25197. Object3D.call(this);
  25198. this.type = 'Audio';
  25199. this.listener = listener;
  25200. this.context = listener.context;
  25201. this.gain = this.context.createGain();
  25202. this.gain.connect(listener.getInput());
  25203. this.autoplay = false;
  25204. this.buffer = null;
  25205. this.detune = 0;
  25206. this.loop = false;
  25207. this.loopStart = 0;
  25208. this.loopEnd = 0;
  25209. this.offset = 0;
  25210. this.duration = undefined;
  25211. this.playbackRate = 1;
  25212. this.isPlaying = false;
  25213. this.hasPlaybackControl = true;
  25214. this.sourceType = 'empty';
  25215. this._startedAt = 0;
  25216. this._pausedAt = 0;
  25217. this.filters = [];
  25218. }
  25219. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25220. constructor: Audio,
  25221. getOutput: function () {
  25222. return this.gain;
  25223. },
  25224. setNodeSource: function (audioNode) {
  25225. this.hasPlaybackControl = false;
  25226. this.sourceType = 'audioNode';
  25227. this.source = audioNode;
  25228. this.connect();
  25229. return this;
  25230. },
  25231. setMediaElementSource: function (mediaElement) {
  25232. this.hasPlaybackControl = false;
  25233. this.sourceType = 'mediaNode';
  25234. this.source = this.context.createMediaElementSource(mediaElement);
  25235. this.connect();
  25236. return this;
  25237. },
  25238. setMediaStreamSource: function (mediaStream) {
  25239. this.hasPlaybackControl = false;
  25240. this.sourceType = 'mediaStreamNode';
  25241. this.source = this.context.createMediaStreamSource(mediaStream);
  25242. this.connect();
  25243. return this;
  25244. },
  25245. setBuffer: function (audioBuffer) {
  25246. this.buffer = audioBuffer;
  25247. this.sourceType = 'buffer';
  25248. if (this.autoplay) this.play();
  25249. return this;
  25250. },
  25251. play: function (delay) {
  25252. if (delay === undefined) delay = 0;
  25253. if (this.isPlaying === true) {
  25254. console.warn('THREE.Audio: Audio is already playing.');
  25255. return;
  25256. }
  25257. if (this.hasPlaybackControl === false) {
  25258. console.warn('THREE.Audio: this Audio has no playback control.');
  25259. return;
  25260. }
  25261. this._startedAt = this.context.currentTime + delay;
  25262. var source = this.context.createBufferSource();
  25263. source.buffer = this.buffer;
  25264. source.loop = this.loop;
  25265. source.loopStart = this.loopStart;
  25266. source.loopEnd = this.loopEnd;
  25267. source.onended = this.onEnded.bind(this);
  25268. source.start(this._startedAt, this._pausedAt + this.offset, this.duration);
  25269. this.isPlaying = true;
  25270. this.source = source;
  25271. this.setDetune(this.detune);
  25272. this.setPlaybackRate(this.playbackRate);
  25273. return this.connect();
  25274. },
  25275. pause: function () {
  25276. if (this.hasPlaybackControl === false) {
  25277. console.warn('THREE.Audio: this Audio has no playback control.');
  25278. return;
  25279. }
  25280. if (this.isPlaying === true) {
  25281. this._pausedAt += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25282. this.source.stop();
  25283. this.source.onended = null;
  25284. this.isPlaying = false;
  25285. }
  25286. return this;
  25287. },
  25288. stop: function () {
  25289. if (this.hasPlaybackControl === false) {
  25290. console.warn('THREE.Audio: this Audio has no playback control.');
  25291. return;
  25292. }
  25293. this._pausedAt = 0;
  25294. this.source.stop();
  25295. this.source.onended = null;
  25296. this.isPlaying = false;
  25297. return this;
  25298. },
  25299. connect: function () {
  25300. if (this.filters.length > 0) {
  25301. this.source.connect(this.filters[0]);
  25302. for (var i = 1, l = this.filters.length; i < l; i++) {
  25303. this.filters[i - 1].connect(this.filters[i]);
  25304. }
  25305. this.filters[this.filters.length - 1].connect(this.getOutput());
  25306. } else {
  25307. this.source.connect(this.getOutput());
  25308. }
  25309. return this;
  25310. },
  25311. disconnect: function () {
  25312. if (this.filters.length > 0) {
  25313. this.source.disconnect(this.filters[0]);
  25314. for (var i = 1, l = this.filters.length; i < l; i++) {
  25315. this.filters[i - 1].disconnect(this.filters[i]);
  25316. }
  25317. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25318. } else {
  25319. this.source.disconnect(this.getOutput());
  25320. }
  25321. return this;
  25322. },
  25323. getFilters: function () {
  25324. return this.filters;
  25325. },
  25326. setFilters: function (value) {
  25327. if (!value) value = [];
  25328. if (this.isPlaying === true) {
  25329. this.disconnect();
  25330. this.filters = value;
  25331. this.connect();
  25332. } else {
  25333. this.filters = value;
  25334. }
  25335. return this;
  25336. },
  25337. setDetune: function (value) {
  25338. this.detune = value;
  25339. if (this.source.detune === undefined) return; // only set detune when available
  25340. if (this.isPlaying === true) {
  25341. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25342. }
  25343. return this;
  25344. },
  25345. getDetune: function () {
  25346. return this.detune;
  25347. },
  25348. getFilter: function () {
  25349. return this.getFilters()[0];
  25350. },
  25351. setFilter: function (filter) {
  25352. return this.setFilters(filter ? [filter] : []);
  25353. },
  25354. setPlaybackRate: function (value) {
  25355. if (this.hasPlaybackControl === false) {
  25356. console.warn('THREE.Audio: this Audio has no playback control.');
  25357. return;
  25358. }
  25359. this.playbackRate = value;
  25360. if (this.isPlaying === true) {
  25361. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25362. }
  25363. return this;
  25364. },
  25365. getPlaybackRate: function () {
  25366. return this.playbackRate;
  25367. },
  25368. onEnded: function () {
  25369. this.isPlaying = false;
  25370. },
  25371. getLoop: function () {
  25372. if (this.hasPlaybackControl === false) {
  25373. console.warn('THREE.Audio: this Audio has no playback control.');
  25374. return false;
  25375. }
  25376. return this.loop;
  25377. },
  25378. setLoop: function (value) {
  25379. if (this.hasPlaybackControl === false) {
  25380. console.warn('THREE.Audio: this Audio has no playback control.');
  25381. return;
  25382. }
  25383. this.loop = value;
  25384. if (this.isPlaying === true) {
  25385. this.source.loop = this.loop;
  25386. }
  25387. return this;
  25388. },
  25389. setLoopStart: function (value) {
  25390. this.loopStart = value;
  25391. return this;
  25392. },
  25393. setLoopEnd: function (value) {
  25394. this.loopEnd = value;
  25395. return this;
  25396. },
  25397. getVolume: function () {
  25398. return this.gain.gain.value;
  25399. },
  25400. setVolume: function (value) {
  25401. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25402. return this;
  25403. }
  25404. });
  25405. /**
  25406. * @author mrdoob / http://mrdoob.com/
  25407. */
  25408. var _position$3 = new Vector3();
  25409. var _quaternion$4 = new Quaternion();
  25410. var _scale$2 = new Vector3();
  25411. var _orientation$1 = new Vector3();
  25412. function PositionalAudio(listener) {
  25413. Audio.call(this, listener);
  25414. this.panner = this.context.createPanner();
  25415. this.panner.panningModel = 'HRTF';
  25416. this.panner.connect(this.gain);
  25417. }
  25418. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  25419. constructor: PositionalAudio,
  25420. getOutput: function () {
  25421. return this.panner;
  25422. },
  25423. getRefDistance: function () {
  25424. return this.panner.refDistance;
  25425. },
  25426. setRefDistance: function (value) {
  25427. this.panner.refDistance = value;
  25428. return this;
  25429. },
  25430. getRolloffFactor: function () {
  25431. return this.panner.rolloffFactor;
  25432. },
  25433. setRolloffFactor: function (value) {
  25434. this.panner.rolloffFactor = value;
  25435. return this;
  25436. },
  25437. getDistanceModel: function () {
  25438. return this.panner.distanceModel;
  25439. },
  25440. setDistanceModel: function (value) {
  25441. this.panner.distanceModel = value;
  25442. return this;
  25443. },
  25444. getMaxDistance: function () {
  25445. return this.panner.maxDistance;
  25446. },
  25447. setMaxDistance: function (value) {
  25448. this.panner.maxDistance = value;
  25449. return this;
  25450. },
  25451. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25452. this.panner.coneInnerAngle = coneInnerAngle;
  25453. this.panner.coneOuterAngle = coneOuterAngle;
  25454. this.panner.coneOuterGain = coneOuterGain;
  25455. return this;
  25456. },
  25457. updateMatrixWorld: function (force) {
  25458. Object3D.prototype.updateMatrixWorld.call(this, force);
  25459. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25460. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25461. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25462. var panner = this.panner;
  25463. if (panner.positionX) {
  25464. // code path for Chrome and Firefox (see #14393)
  25465. var endTime = this.context.currentTime + this.listener.timeDelta;
  25466. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25467. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25468. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25469. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25470. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25471. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25472. } else {
  25473. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25474. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25475. }
  25476. }
  25477. });
  25478. /**
  25479. * @author mrdoob / http://mrdoob.com/
  25480. */
  25481. function AudioAnalyser(audio, fftSize) {
  25482. this.analyser = audio.context.createAnalyser();
  25483. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25484. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25485. audio.getOutput().connect(this.analyser);
  25486. }
  25487. Object.assign(AudioAnalyser.prototype, {
  25488. getFrequencyData: function () {
  25489. this.analyser.getByteFrequencyData(this.data);
  25490. return this.data;
  25491. },
  25492. getAverageFrequency: function () {
  25493. var value = 0,
  25494. data = this.getFrequencyData();
  25495. for (var i = 0; i < data.length; i++) {
  25496. value += data[i];
  25497. }
  25498. return value / data.length;
  25499. }
  25500. });
  25501. /**
  25502. *
  25503. * Buffered scene graph property that allows weighted accumulation.
  25504. *
  25505. *
  25506. * @author Ben Houston / http://clara.io/
  25507. * @author David Sarno / http://lighthaus.us/
  25508. * @author tschw
  25509. */
  25510. function PropertyMixer(binding, typeName, valueSize) {
  25511. this.binding = binding;
  25512. this.valueSize = valueSize;
  25513. var bufferType = Float64Array,
  25514. mixFunction;
  25515. switch (typeName) {
  25516. case 'quaternion':
  25517. mixFunction = this._slerp;
  25518. break;
  25519. case 'string':
  25520. case 'bool':
  25521. bufferType = Array;
  25522. mixFunction = this._select;
  25523. break;
  25524. default:
  25525. mixFunction = this._lerp;
  25526. }
  25527. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  25528. //
  25529. // interpolators can use .buffer as their .result
  25530. // the data then goes to 'incoming'
  25531. //
  25532. // 'accu0' and 'accu1' are used frame-interleaved for
  25533. // the cumulative result and are compared to detect
  25534. // changes
  25535. //
  25536. // 'orig' stores the original state of the property
  25537. this._mixBufferRegion = mixFunction;
  25538. this.cumulativeWeight = 0;
  25539. this.useCount = 0;
  25540. this.referenceCount = 0;
  25541. }
  25542. Object.assign(PropertyMixer.prototype, {
  25543. // accumulate data in the 'incoming' region into 'accu<i>'
  25544. accumulate: function (accuIndex, weight) {
  25545. // note: happily accumulating nothing when weight = 0, the caller knows
  25546. // the weight and shouldn't have made the call in the first place
  25547. var buffer = this.buffer,
  25548. stride = this.valueSize,
  25549. offset = accuIndex * stride + stride,
  25550. currentWeight = this.cumulativeWeight;
  25551. if (currentWeight === 0) {
  25552. // accuN := incoming * weight
  25553. for (var i = 0; i !== stride; ++i) {
  25554. buffer[offset + i] = buffer[i];
  25555. }
  25556. currentWeight = weight;
  25557. } else {
  25558. // accuN := accuN + incoming * weight
  25559. currentWeight += weight;
  25560. var mix = weight / currentWeight;
  25561. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25562. }
  25563. this.cumulativeWeight = currentWeight;
  25564. },
  25565. // apply the state of 'accu<i>' to the binding when accus differ
  25566. apply: function (accuIndex) {
  25567. var stride = this.valueSize,
  25568. buffer = this.buffer,
  25569. offset = accuIndex * stride + stride,
  25570. weight = this.cumulativeWeight,
  25571. binding = this.binding;
  25572. this.cumulativeWeight = 0;
  25573. if (weight < 1) {
  25574. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25575. var originalValueOffset = stride * 3;
  25576. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25577. }
  25578. for (var i = stride, e = stride + stride; i !== e; ++i) {
  25579. if (buffer[i] !== buffer[i + stride]) {
  25580. // value has changed -> update scene graph
  25581. binding.setValue(buffer, offset);
  25582. break;
  25583. }
  25584. }
  25585. },
  25586. // remember the state of the bound property and copy it to both accus
  25587. saveOriginalState: function () {
  25588. var binding = this.binding;
  25589. var buffer = this.buffer,
  25590. stride = this.valueSize,
  25591. originalValueOffset = stride * 3;
  25592. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25593. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  25594. buffer[i] = buffer[originalValueOffset + i % stride];
  25595. }
  25596. this.cumulativeWeight = 0;
  25597. },
  25598. // apply the state previously taken via 'saveOriginalState' to the binding
  25599. restoreOriginalState: function () {
  25600. var originalValueOffset = this.valueSize * 3;
  25601. this.binding.setValue(this.buffer, originalValueOffset);
  25602. },
  25603. // mix functions
  25604. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  25605. if (t >= 0.5) {
  25606. for (var i = 0; i !== stride; ++i) {
  25607. buffer[dstOffset + i] = buffer[srcOffset + i];
  25608. }
  25609. }
  25610. },
  25611. _slerp: function (buffer, dstOffset, srcOffset, t) {
  25612. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25613. },
  25614. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  25615. var s = 1 - t;
  25616. for (var i = 0; i !== stride; ++i) {
  25617. var j = dstOffset + i;
  25618. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25619. }
  25620. }
  25621. });
  25622. /**
  25623. *
  25624. * A reference to a real property in the scene graph.
  25625. *
  25626. *
  25627. * @author Ben Houston / http://clara.io/
  25628. * @author David Sarno / http://lighthaus.us/
  25629. * @author tschw
  25630. */
  25631. // Characters [].:/ are reserved for track binding syntax.
  25632. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25633. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25634. // only latin characters, and the unicode \p{L} is not yet supported. So
  25635. // instead, we exclude reserved characters and match everything else.
  25636. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25637. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25638. // be matched to parse the rest of the track name.
  25639. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25640. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25641. // characters. Accessor may contain any character except closing bracket.
  25642. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25643. // contain any non-bracket characters.
  25644. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25645. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25646. var _supportedObjectNames = ['material', 'materials', 'bones'];
  25647. function Composite(targetGroup, path, optionalParsedPath) {
  25648. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25649. this._targetGroup = targetGroup;
  25650. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25651. }
  25652. Object.assign(Composite.prototype, {
  25653. getValue: function (array, offset) {
  25654. this.bind(); // bind all binding
  25655. var firstValidIndex = this._targetGroup.nCachedObjects_,
  25656. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25657. if (binding !== undefined) binding.getValue(array, offset);
  25658. },
  25659. setValue: function (array, offset) {
  25660. var bindings = this._bindings;
  25661. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25662. bindings[i].setValue(array, offset);
  25663. }
  25664. },
  25665. bind: function () {
  25666. var bindings = this._bindings;
  25667. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25668. bindings[i].bind();
  25669. }
  25670. },
  25671. unbind: function () {
  25672. var bindings = this._bindings;
  25673. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25674. bindings[i].unbind();
  25675. }
  25676. }
  25677. });
  25678. function PropertyBinding(rootNode, path, parsedPath) {
  25679. this.path = path;
  25680. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25681. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25682. this.rootNode = rootNode;
  25683. }
  25684. Object.assign(PropertyBinding, {
  25685. Composite: Composite,
  25686. create: function (root, path, parsedPath) {
  25687. if (!(root && root.isAnimationObjectGroup)) {
  25688. return new PropertyBinding(root, path, parsedPath);
  25689. } else {
  25690. return new PropertyBinding.Composite(root, path, parsedPath);
  25691. }
  25692. },
  25693. /**
  25694. * Replaces spaces with underscores and removes unsupported characters from
  25695. * node names, to ensure compatibility with parseTrackName().
  25696. *
  25697. * @param {string} name Node name to be sanitized.
  25698. * @return {string}
  25699. */
  25700. sanitizeNodeName: function (name) {
  25701. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25702. },
  25703. parseTrackName: function (trackName) {
  25704. var matches = _trackRe.exec(trackName);
  25705. if (!matches) {
  25706. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25707. }
  25708. var results = {
  25709. // directoryName: matches[ 1 ], // (tschw) currently unused
  25710. nodeName: matches[2],
  25711. objectName: matches[3],
  25712. objectIndex: matches[4],
  25713. propertyName: matches[5],
  25714. // required
  25715. propertyIndex: matches[6]
  25716. };
  25717. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25718. if (lastDot !== undefined && lastDot !== -1) {
  25719. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  25720. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25721. // 'bar' could be the objectName, or part of a nodeName (which can
  25722. // include '.' characters).
  25723. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25724. results.nodeName = results.nodeName.substring(0, lastDot);
  25725. results.objectName = objectName;
  25726. }
  25727. }
  25728. if (results.propertyName === null || results.propertyName.length === 0) {
  25729. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25730. }
  25731. return results;
  25732. },
  25733. findNode: function (root, nodeName) {
  25734. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25735. return root;
  25736. } // search into skeleton bones.
  25737. if (root.skeleton) {
  25738. var bone = root.skeleton.getBoneByName(nodeName);
  25739. if (bone !== undefined) {
  25740. return bone;
  25741. }
  25742. } // search into node subtree.
  25743. if (root.children) {
  25744. var searchNodeSubtree = function (children) {
  25745. for (var i = 0; i < children.length; i++) {
  25746. var childNode = children[i];
  25747. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25748. return childNode;
  25749. }
  25750. var result = searchNodeSubtree(childNode.children);
  25751. if (result) return result;
  25752. }
  25753. return null;
  25754. };
  25755. var subTreeNode = searchNodeSubtree(root.children);
  25756. if (subTreeNode) {
  25757. return subTreeNode;
  25758. }
  25759. }
  25760. return null;
  25761. }
  25762. });
  25763. Object.assign(PropertyBinding.prototype, {
  25764. // prototype, continued
  25765. // these are used to "bind" a nonexistent property
  25766. _getValue_unavailable: function () {},
  25767. _setValue_unavailable: function () {},
  25768. BindingType: {
  25769. Direct: 0,
  25770. EntireArray: 1,
  25771. ArrayElement: 2,
  25772. HasFromToArray: 3
  25773. },
  25774. Versioning: {
  25775. None: 0,
  25776. NeedsUpdate: 1,
  25777. MatrixWorldNeedsUpdate: 2
  25778. },
  25779. GetterByBindingType: [function getValue_direct(buffer, offset) {
  25780. buffer[offset] = this.node[this.propertyName];
  25781. }, function getValue_array(buffer, offset) {
  25782. var source = this.resolvedProperty;
  25783. for (var i = 0, n = source.length; i !== n; ++i) {
  25784. buffer[offset++] = source[i];
  25785. }
  25786. }, function getValue_arrayElement(buffer, offset) {
  25787. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25788. }, function getValue_toArray(buffer, offset) {
  25789. this.resolvedProperty.toArray(buffer, offset);
  25790. }],
  25791. SetterByBindingTypeAndVersioning: [[// Direct
  25792. function setValue_direct(buffer, offset) {
  25793. this.targetObject[this.propertyName] = buffer[offset];
  25794. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  25795. this.targetObject[this.propertyName] = buffer[offset];
  25796. this.targetObject.needsUpdate = true;
  25797. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25798. this.targetObject[this.propertyName] = buffer[offset];
  25799. this.targetObject.matrixWorldNeedsUpdate = true;
  25800. }], [// EntireArray
  25801. function setValue_array(buffer, offset) {
  25802. var dest = this.resolvedProperty;
  25803. for (var i = 0, n = dest.length; i !== n; ++i) {
  25804. dest[i] = buffer[offset++];
  25805. }
  25806. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  25807. var dest = this.resolvedProperty;
  25808. for (var i = 0, n = dest.length; i !== n; ++i) {
  25809. dest[i] = buffer[offset++];
  25810. }
  25811. this.targetObject.needsUpdate = true;
  25812. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25813. var dest = this.resolvedProperty;
  25814. for (var i = 0, n = dest.length; i !== n; ++i) {
  25815. dest[i] = buffer[offset++];
  25816. }
  25817. this.targetObject.matrixWorldNeedsUpdate = true;
  25818. }], [// ArrayElement
  25819. function setValue_arrayElement(buffer, offset) {
  25820. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25821. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25822. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25823. this.targetObject.needsUpdate = true;
  25824. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25825. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25826. this.targetObject.matrixWorldNeedsUpdate = true;
  25827. }], [// HasToFromArray
  25828. function setValue_fromArray(buffer, offset) {
  25829. this.resolvedProperty.fromArray(buffer, offset);
  25830. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25831. this.resolvedProperty.fromArray(buffer, offset);
  25832. this.targetObject.needsUpdate = true;
  25833. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25834. this.resolvedProperty.fromArray(buffer, offset);
  25835. this.targetObject.matrixWorldNeedsUpdate = true;
  25836. }]],
  25837. getValue: function getValue_unbound(targetArray, offset) {
  25838. this.bind();
  25839. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  25840. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25841. // prototype version of these methods with one that represents
  25842. // the bound state. When the property is not found, the methods
  25843. // become no-ops.
  25844. },
  25845. setValue: function getValue_unbound(sourceArray, offset) {
  25846. this.bind();
  25847. this.setValue(sourceArray, offset);
  25848. },
  25849. // create getter / setter pair for a property in the scene graph
  25850. bind: function () {
  25851. var targetObject = this.node,
  25852. parsedPath = this.parsedPath,
  25853. objectName = parsedPath.objectName,
  25854. propertyName = parsedPath.propertyName,
  25855. propertyIndex = parsedPath.propertyIndex;
  25856. if (!targetObject) {
  25857. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25858. this.node = targetObject;
  25859. } // set fail state so we can just 'return' on error
  25860. this.getValue = this._getValue_unavailable;
  25861. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25862. if (!targetObject) {
  25863. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25864. return;
  25865. }
  25866. if (objectName) {
  25867. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25868. switch (objectName) {
  25869. case 'materials':
  25870. if (!targetObject.material) {
  25871. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25872. return;
  25873. }
  25874. if (!targetObject.material.materials) {
  25875. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25876. return;
  25877. }
  25878. targetObject = targetObject.material.materials;
  25879. break;
  25880. case 'bones':
  25881. if (!targetObject.skeleton) {
  25882. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25883. return;
  25884. } // potential future optimization: skip this if propertyIndex is already an integer
  25885. // and convert the integer string to a true integer.
  25886. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25887. for (var i = 0; i < targetObject.length; i++) {
  25888. if (targetObject[i].name === objectIndex) {
  25889. objectIndex = i;
  25890. break;
  25891. }
  25892. }
  25893. break;
  25894. default:
  25895. if (targetObject[objectName] === undefined) {
  25896. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25897. return;
  25898. }
  25899. targetObject = targetObject[objectName];
  25900. }
  25901. if (objectIndex !== undefined) {
  25902. if (targetObject[objectIndex] === undefined) {
  25903. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25904. return;
  25905. }
  25906. targetObject = targetObject[objectIndex];
  25907. }
  25908. } // resolve property
  25909. var nodeProperty = targetObject[propertyName];
  25910. if (nodeProperty === undefined) {
  25911. var nodeName = parsedPath.nodeName;
  25912. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25913. return;
  25914. } // determine versioning scheme
  25915. var versioning = this.Versioning.None;
  25916. this.targetObject = targetObject;
  25917. if (targetObject.needsUpdate !== undefined) {
  25918. // material
  25919. versioning = this.Versioning.NeedsUpdate;
  25920. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25921. // node transform
  25922. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25923. } // determine how the property gets bound
  25924. var bindingType = this.BindingType.Direct;
  25925. if (propertyIndex !== undefined) {
  25926. // access a sub element of the property array (only primitives are supported right now)
  25927. if (propertyName === "morphTargetInfluences") {
  25928. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25929. // support resolving morphTarget names into indices.
  25930. if (!targetObject.geometry) {
  25931. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25932. return;
  25933. }
  25934. if (targetObject.geometry.isBufferGeometry) {
  25935. if (!targetObject.geometry.morphAttributes) {
  25936. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25937. return;
  25938. }
  25939. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  25940. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  25941. propertyIndex = i;
  25942. break;
  25943. }
  25944. }
  25945. } else {
  25946. if (!targetObject.geometry.morphTargets) {
  25947. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  25948. return;
  25949. }
  25950. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  25951. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  25952. propertyIndex = i;
  25953. break;
  25954. }
  25955. }
  25956. }
  25957. }
  25958. bindingType = this.BindingType.ArrayElement;
  25959. this.resolvedProperty = nodeProperty;
  25960. this.propertyIndex = propertyIndex;
  25961. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25962. // must use copy for Object3D.Euler/Quaternion
  25963. bindingType = this.BindingType.HasFromToArray;
  25964. this.resolvedProperty = nodeProperty;
  25965. } else if (Array.isArray(nodeProperty)) {
  25966. bindingType = this.BindingType.EntireArray;
  25967. this.resolvedProperty = nodeProperty;
  25968. } else {
  25969. this.propertyName = propertyName;
  25970. } // select getter / setter
  25971. this.getValue = this.GetterByBindingType[bindingType];
  25972. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25973. },
  25974. unbind: function () {
  25975. this.node = null; // back to the prototype version of getValue / setValue
  25976. // note: avoiding to mutate the shape of 'this' via 'delete'
  25977. this.getValue = this._getValue_unbound;
  25978. this.setValue = this._setValue_unbound;
  25979. }
  25980. }); // DECLARE ALIAS AFTER assign prototype
  25981. Object.assign(PropertyBinding.prototype, {
  25982. // initial state of these methods that calls 'bind'
  25983. _getValue_unbound: PropertyBinding.prototype.getValue,
  25984. _setValue_unbound: PropertyBinding.prototype.setValue
  25985. });
  25986. /**
  25987. *
  25988. * A group of objects that receives a shared animation state.
  25989. *
  25990. * Usage:
  25991. *
  25992. * - Add objects you would otherwise pass as 'root' to the
  25993. * constructor or the .clipAction method of AnimationMixer.
  25994. *
  25995. * - Instead pass this object as 'root'.
  25996. *
  25997. * - You can also add and remove objects later when the mixer
  25998. * is running.
  25999. *
  26000. * Note:
  26001. *
  26002. * Objects of this class appear as one object to the mixer,
  26003. * so cache control of the individual objects must be done
  26004. * on the group.
  26005. *
  26006. * Limitation:
  26007. *
  26008. * - The animated properties must be compatible among the
  26009. * all objects in the group.
  26010. *
  26011. * - A single property can either be controlled through a
  26012. * target group or directly, but not both.
  26013. *
  26014. * @author tschw
  26015. */
  26016. function AnimationObjectGroup() {
  26017. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  26018. this._objects = Array.prototype.slice.call(arguments);
  26019. this.nCachedObjects_ = 0; // threshold
  26020. // note: read by PropertyBinding.Composite
  26021. var indices = {};
  26022. this._indicesByUUID = indices; // for bookkeeping
  26023. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26024. indices[arguments[i].uuid] = i;
  26025. }
  26026. this._paths = []; // inside: string
  26027. this._parsedPaths = []; // inside: { we don't care, here }
  26028. this._bindings = []; // inside: Array< PropertyBinding >
  26029. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26030. var scope = this;
  26031. this.stats = {
  26032. objects: {
  26033. get total() {
  26034. return scope._objects.length;
  26035. },
  26036. get inUse() {
  26037. return this.total - scope.nCachedObjects_;
  26038. }
  26039. },
  26040. get bindingsPerObject() {
  26041. return scope._bindings.length;
  26042. }
  26043. };
  26044. }
  26045. Object.assign(AnimationObjectGroup.prototype, {
  26046. isAnimationObjectGroup: true,
  26047. add: function () {
  26048. var objects = this._objects,
  26049. nObjects = objects.length,
  26050. nCachedObjects = this.nCachedObjects_,
  26051. indicesByUUID = this._indicesByUUID,
  26052. paths = this._paths,
  26053. parsedPaths = this._parsedPaths,
  26054. bindings = this._bindings,
  26055. nBindings = bindings.length,
  26056. knownObject = undefined;
  26057. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26058. var object = arguments[i],
  26059. uuid = object.uuid,
  26060. index = indicesByUUID[uuid];
  26061. if (index === undefined) {
  26062. // unknown object -> add it to the ACTIVE region
  26063. index = nObjects++;
  26064. indicesByUUID[uuid] = index;
  26065. objects.push(object); // accounting is done, now do the same for all bindings
  26066. for (var j = 0, m = nBindings; j !== m; ++j) {
  26067. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26068. }
  26069. } else if (index < nCachedObjects) {
  26070. knownObject = objects[index]; // move existing object to the ACTIVE region
  26071. var firstActiveIndex = --nCachedObjects,
  26072. lastCachedObject = objects[firstActiveIndex];
  26073. indicesByUUID[lastCachedObject.uuid] = index;
  26074. objects[index] = lastCachedObject;
  26075. indicesByUUID[uuid] = firstActiveIndex;
  26076. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26077. for (var j = 0, m = nBindings; j !== m; ++j) {
  26078. var bindingsForPath = bindings[j],
  26079. lastCached = bindingsForPath[firstActiveIndex],
  26080. binding = bindingsForPath[index];
  26081. bindingsForPath[index] = lastCached;
  26082. if (binding === undefined) {
  26083. // since we do not bother to create new bindings
  26084. // for objects that are cached, the binding may
  26085. // or may not exist
  26086. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26087. }
  26088. bindingsForPath[firstActiveIndex] = binding;
  26089. }
  26090. } else if (objects[index] !== knownObject) {
  26091. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26092. } // else the object is already where we want it to be
  26093. } // for arguments
  26094. this.nCachedObjects_ = nCachedObjects;
  26095. },
  26096. remove: function () {
  26097. var objects = this._objects,
  26098. nCachedObjects = this.nCachedObjects_,
  26099. indicesByUUID = this._indicesByUUID,
  26100. bindings = this._bindings,
  26101. nBindings = bindings.length;
  26102. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26103. var object = arguments[i],
  26104. uuid = object.uuid,
  26105. index = indicesByUUID[uuid];
  26106. if (index !== undefined && index >= nCachedObjects) {
  26107. // move existing object into the CACHED region
  26108. var lastCachedIndex = nCachedObjects++,
  26109. firstActiveObject = objects[lastCachedIndex];
  26110. indicesByUUID[firstActiveObject.uuid] = index;
  26111. objects[index] = firstActiveObject;
  26112. indicesByUUID[uuid] = lastCachedIndex;
  26113. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26114. for (var j = 0, m = nBindings; j !== m; ++j) {
  26115. var bindingsForPath = bindings[j],
  26116. firstActive = bindingsForPath[lastCachedIndex],
  26117. binding = bindingsForPath[index];
  26118. bindingsForPath[index] = firstActive;
  26119. bindingsForPath[lastCachedIndex] = binding;
  26120. }
  26121. }
  26122. } // for arguments
  26123. this.nCachedObjects_ = nCachedObjects;
  26124. },
  26125. // remove & forget
  26126. uncache: function () {
  26127. var objects = this._objects,
  26128. nObjects = objects.length,
  26129. nCachedObjects = this.nCachedObjects_,
  26130. indicesByUUID = this._indicesByUUID,
  26131. bindings = this._bindings,
  26132. nBindings = bindings.length;
  26133. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26134. var object = arguments[i],
  26135. uuid = object.uuid,
  26136. index = indicesByUUID[uuid];
  26137. if (index !== undefined) {
  26138. delete indicesByUUID[uuid];
  26139. if (index < nCachedObjects) {
  26140. // object is cached, shrink the CACHED region
  26141. var firstActiveIndex = --nCachedObjects,
  26142. lastCachedObject = objects[firstActiveIndex],
  26143. lastIndex = --nObjects,
  26144. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26145. indicesByUUID[lastCachedObject.uuid] = index;
  26146. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26147. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26148. objects[firstActiveIndex] = lastObject;
  26149. objects.pop(); // accounting is done, now do the same for all bindings
  26150. for (var j = 0, m = nBindings; j !== m; ++j) {
  26151. var bindingsForPath = bindings[j],
  26152. lastCached = bindingsForPath[firstActiveIndex],
  26153. last = bindingsForPath[lastIndex];
  26154. bindingsForPath[index] = lastCached;
  26155. bindingsForPath[firstActiveIndex] = last;
  26156. bindingsForPath.pop();
  26157. }
  26158. } else {
  26159. // object is active, just swap with the last and pop
  26160. var lastIndex = --nObjects,
  26161. lastObject = objects[lastIndex];
  26162. indicesByUUID[lastObject.uuid] = index;
  26163. objects[index] = lastObject;
  26164. objects.pop(); // accounting is done, now do the same for all bindings
  26165. for (var j = 0, m = nBindings; j !== m; ++j) {
  26166. var bindingsForPath = bindings[j];
  26167. bindingsForPath[index] = bindingsForPath[lastIndex];
  26168. bindingsForPath.pop();
  26169. }
  26170. } // cached or active
  26171. } // if object is known
  26172. } // for arguments
  26173. this.nCachedObjects_ = nCachedObjects;
  26174. },
  26175. // Internal interface used by befriended PropertyBinding.Composite:
  26176. subscribe_: function (path, parsedPath) {
  26177. // returns an array of bindings for the given path that is changed
  26178. // according to the contained objects in the group
  26179. var indicesByPath = this._bindingsIndicesByPath,
  26180. index = indicesByPath[path],
  26181. bindings = this._bindings;
  26182. if (index !== undefined) return bindings[index];
  26183. var paths = this._paths,
  26184. parsedPaths = this._parsedPaths,
  26185. objects = this._objects,
  26186. nObjects = objects.length,
  26187. nCachedObjects = this.nCachedObjects_,
  26188. bindingsForPath = new Array(nObjects);
  26189. index = bindings.length;
  26190. indicesByPath[path] = index;
  26191. paths.push(path);
  26192. parsedPaths.push(parsedPath);
  26193. bindings.push(bindingsForPath);
  26194. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26195. var object = objects[i];
  26196. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26197. }
  26198. return bindingsForPath;
  26199. },
  26200. unsubscribe_: function (path) {
  26201. // tells the group to forget about a property path and no longer
  26202. // update the array previously obtained with 'subscribe_'
  26203. var indicesByPath = this._bindingsIndicesByPath,
  26204. index = indicesByPath[path];
  26205. if (index !== undefined) {
  26206. var paths = this._paths,
  26207. parsedPaths = this._parsedPaths,
  26208. bindings = this._bindings,
  26209. lastBindingsIndex = bindings.length - 1,
  26210. lastBindings = bindings[lastBindingsIndex],
  26211. lastBindingsPath = path[lastBindingsIndex];
  26212. indicesByPath[lastBindingsPath] = index;
  26213. bindings[index] = lastBindings;
  26214. bindings.pop();
  26215. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26216. parsedPaths.pop();
  26217. paths[index] = paths[lastBindingsIndex];
  26218. paths.pop();
  26219. }
  26220. }
  26221. });
  26222. /**
  26223. *
  26224. * Action provided by AnimationMixer for scheduling clip playback on specific
  26225. * objects.
  26226. *
  26227. * @author Ben Houston / http://clara.io/
  26228. * @author David Sarno / http://lighthaus.us/
  26229. * @author tschw
  26230. *
  26231. */
  26232. function AnimationAction(mixer, clip, localRoot) {
  26233. this._mixer = mixer;
  26234. this._clip = clip;
  26235. this._localRoot = localRoot || null;
  26236. var tracks = clip.tracks,
  26237. nTracks = tracks.length,
  26238. interpolants = new Array(nTracks);
  26239. var interpolantSettings = {
  26240. endingStart: ZeroCurvatureEnding,
  26241. endingEnd: ZeroCurvatureEnding
  26242. };
  26243. for (var i = 0; i !== nTracks; ++i) {
  26244. var interpolant = tracks[i].createInterpolant(null);
  26245. interpolants[i] = interpolant;
  26246. interpolant.settings = interpolantSettings;
  26247. }
  26248. this._interpolantSettings = interpolantSettings;
  26249. this._interpolants = interpolants; // bound by the mixer
  26250. // inside: PropertyMixer (managed by the mixer)
  26251. this._propertyBindings = new Array(nTracks);
  26252. this._cacheIndex = null; // for the memory manager
  26253. this._byClipCacheIndex = null; // for the memory manager
  26254. this._timeScaleInterpolant = null;
  26255. this._weightInterpolant = null;
  26256. this.loop = LoopRepeat;
  26257. this._loopCount = -1; // global mixer time when the action is to be started
  26258. // it's set back to 'null' upon start of the action
  26259. this._startTime = null; // scaled local time of the action
  26260. // gets clamped or wrapped to 0..clip.duration according to loop
  26261. this.time = 0;
  26262. this.timeScale = 1;
  26263. this._effectiveTimeScale = 1;
  26264. this.weight = 1;
  26265. this._effectiveWeight = 1;
  26266. this.repetitions = Infinity; // no. of repetitions when looping
  26267. this.paused = false; // true -> zero effective time scale
  26268. this.enabled = true; // false -> zero effective weight
  26269. this.clampWhenFinished = false; // keep feeding the last frame?
  26270. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26271. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26272. }
  26273. Object.assign(AnimationAction.prototype, {
  26274. // State & Scheduling
  26275. play: function () {
  26276. this._mixer._activateAction(this);
  26277. return this;
  26278. },
  26279. stop: function () {
  26280. this._mixer._deactivateAction(this);
  26281. return this.reset();
  26282. },
  26283. reset: function () {
  26284. this.paused = false;
  26285. this.enabled = true;
  26286. this.time = 0; // restart clip
  26287. this._loopCount = -1; // forget previous loops
  26288. this._startTime = null; // forget scheduling
  26289. return this.stopFading().stopWarping();
  26290. },
  26291. isRunning: function () {
  26292. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26293. },
  26294. // return true when play has been called
  26295. isScheduled: function () {
  26296. return this._mixer._isActiveAction(this);
  26297. },
  26298. startAt: function (time) {
  26299. this._startTime = time;
  26300. return this;
  26301. },
  26302. setLoop: function (mode, repetitions) {
  26303. this.loop = mode;
  26304. this.repetitions = repetitions;
  26305. return this;
  26306. },
  26307. // Weight
  26308. // set the weight stopping any scheduled fading
  26309. // although .enabled = false yields an effective weight of zero, this
  26310. // method does *not* change .enabled, because it would be confusing
  26311. setEffectiveWeight: function (weight) {
  26312. this.weight = weight; // note: same logic as when updated at runtime
  26313. this._effectiveWeight = this.enabled ? weight : 0;
  26314. return this.stopFading();
  26315. },
  26316. // return the weight considering fading and .enabled
  26317. getEffectiveWeight: function () {
  26318. return this._effectiveWeight;
  26319. },
  26320. fadeIn: function (duration) {
  26321. return this._scheduleFading(duration, 0, 1);
  26322. },
  26323. fadeOut: function (duration) {
  26324. return this._scheduleFading(duration, 1, 0);
  26325. },
  26326. crossFadeFrom: function (fadeOutAction, duration, warp) {
  26327. fadeOutAction.fadeOut(duration);
  26328. this.fadeIn(duration);
  26329. if (warp) {
  26330. var fadeInDuration = this._clip.duration,
  26331. fadeOutDuration = fadeOutAction._clip.duration,
  26332. startEndRatio = fadeOutDuration / fadeInDuration,
  26333. endStartRatio = fadeInDuration / fadeOutDuration;
  26334. fadeOutAction.warp(1.0, startEndRatio, duration);
  26335. this.warp(endStartRatio, 1.0, duration);
  26336. }
  26337. return this;
  26338. },
  26339. crossFadeTo: function (fadeInAction, duration, warp) {
  26340. return fadeInAction.crossFadeFrom(this, duration, warp);
  26341. },
  26342. stopFading: function () {
  26343. var weightInterpolant = this._weightInterpolant;
  26344. if (weightInterpolant !== null) {
  26345. this._weightInterpolant = null;
  26346. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26347. }
  26348. return this;
  26349. },
  26350. // Time Scale Control
  26351. // set the time scale stopping any scheduled warping
  26352. // although .paused = true yields an effective time scale of zero, this
  26353. // method does *not* change .paused, because it would be confusing
  26354. setEffectiveTimeScale: function (timeScale) {
  26355. this.timeScale = timeScale;
  26356. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26357. return this.stopWarping();
  26358. },
  26359. // return the time scale considering warping and .paused
  26360. getEffectiveTimeScale: function () {
  26361. return this._effectiveTimeScale;
  26362. },
  26363. setDuration: function (duration) {
  26364. this.timeScale = this._clip.duration / duration;
  26365. return this.stopWarping();
  26366. },
  26367. syncWith: function (action) {
  26368. this.time = action.time;
  26369. this.timeScale = action.timeScale;
  26370. return this.stopWarping();
  26371. },
  26372. halt: function (duration) {
  26373. return this.warp(this._effectiveTimeScale, 0, duration);
  26374. },
  26375. warp: function (startTimeScale, endTimeScale, duration) {
  26376. var mixer = this._mixer,
  26377. now = mixer.time,
  26378. interpolant = this._timeScaleInterpolant,
  26379. timeScale = this.timeScale;
  26380. if (interpolant === null) {
  26381. interpolant = mixer._lendControlInterpolant();
  26382. this._timeScaleInterpolant = interpolant;
  26383. }
  26384. var times = interpolant.parameterPositions,
  26385. values = interpolant.sampleValues;
  26386. times[0] = now;
  26387. times[1] = now + duration;
  26388. values[0] = startTimeScale / timeScale;
  26389. values[1] = endTimeScale / timeScale;
  26390. return this;
  26391. },
  26392. stopWarping: function () {
  26393. var timeScaleInterpolant = this._timeScaleInterpolant;
  26394. if (timeScaleInterpolant !== null) {
  26395. this._timeScaleInterpolant = null;
  26396. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26397. }
  26398. return this;
  26399. },
  26400. // Object Accessors
  26401. getMixer: function () {
  26402. return this._mixer;
  26403. },
  26404. getClip: function () {
  26405. return this._clip;
  26406. },
  26407. getRoot: function () {
  26408. return this._localRoot || this._mixer._root;
  26409. },
  26410. // Interna
  26411. _update: function (time, deltaTime, timeDirection, accuIndex) {
  26412. // called by the mixer
  26413. if (!this.enabled) {
  26414. // call ._updateWeight() to update ._effectiveWeight
  26415. this._updateWeight(time);
  26416. return;
  26417. }
  26418. var startTime = this._startTime;
  26419. if (startTime !== null) {
  26420. // check for scheduled start of action
  26421. var timeRunning = (time - startTime) * timeDirection;
  26422. if (timeRunning < 0 || timeDirection === 0) {
  26423. return; // yet to come / don't decide when delta = 0
  26424. } // start
  26425. this._startTime = null; // unschedule
  26426. deltaTime = timeDirection * timeRunning;
  26427. } // apply time scale and advance time
  26428. deltaTime *= this._updateTimeScale(time);
  26429. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26430. // an effective weight of 0
  26431. var weight = this._updateWeight(time);
  26432. if (weight > 0) {
  26433. var interpolants = this._interpolants;
  26434. var propertyMixers = this._propertyBindings;
  26435. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  26436. interpolants[j].evaluate(clipTime);
  26437. propertyMixers[j].accumulate(accuIndex, weight);
  26438. }
  26439. }
  26440. },
  26441. _updateWeight: function (time) {
  26442. var weight = 0;
  26443. if (this.enabled) {
  26444. weight = this.weight;
  26445. var interpolant = this._weightInterpolant;
  26446. if (interpolant !== null) {
  26447. var interpolantValue = interpolant.evaluate(time)[0];
  26448. weight *= interpolantValue;
  26449. if (time > interpolant.parameterPositions[1]) {
  26450. this.stopFading();
  26451. if (interpolantValue === 0) {
  26452. // faded out, disable
  26453. this.enabled = false;
  26454. }
  26455. }
  26456. }
  26457. }
  26458. this._effectiveWeight = weight;
  26459. return weight;
  26460. },
  26461. _updateTimeScale: function (time) {
  26462. var timeScale = 0;
  26463. if (!this.paused) {
  26464. timeScale = this.timeScale;
  26465. var interpolant = this._timeScaleInterpolant;
  26466. if (interpolant !== null) {
  26467. var interpolantValue = interpolant.evaluate(time)[0];
  26468. timeScale *= interpolantValue;
  26469. if (time > interpolant.parameterPositions[1]) {
  26470. this.stopWarping();
  26471. if (timeScale === 0) {
  26472. // motion has halted, pause
  26473. this.paused = true;
  26474. } else {
  26475. // warp done - apply final time scale
  26476. this.timeScale = timeScale;
  26477. }
  26478. }
  26479. }
  26480. }
  26481. this._effectiveTimeScale = timeScale;
  26482. return timeScale;
  26483. },
  26484. _updateTime: function (deltaTime) {
  26485. var time = this.time + deltaTime;
  26486. var duration = this._clip.duration;
  26487. var loop = this.loop;
  26488. var loopCount = this._loopCount;
  26489. var pingPong = loop === LoopPingPong;
  26490. if (deltaTime === 0) {
  26491. if (loopCount === -1) return time;
  26492. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26493. }
  26494. if (loop === LoopOnce) {
  26495. if (loopCount === -1) {
  26496. // just started
  26497. this._loopCount = 0;
  26498. this._setEndings(true, true, false);
  26499. }
  26500. handle_stop: {
  26501. if (time >= duration) {
  26502. time = duration;
  26503. } else if (time < 0) {
  26504. time = 0;
  26505. } else {
  26506. this.time = time;
  26507. break handle_stop;
  26508. }
  26509. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26510. this.time = time;
  26511. this._mixer.dispatchEvent({
  26512. type: 'finished',
  26513. action: this,
  26514. direction: deltaTime < 0 ? -1 : 1
  26515. });
  26516. }
  26517. } else {
  26518. // repetitive Repeat or PingPong
  26519. if (loopCount === -1) {
  26520. // just started
  26521. if (deltaTime >= 0) {
  26522. loopCount = 0;
  26523. this._setEndings(true, this.repetitions === 0, pingPong);
  26524. } else {
  26525. // when looping in reverse direction, the initial
  26526. // transition through zero counts as a repetition,
  26527. // so leave loopCount at -1
  26528. this._setEndings(this.repetitions === 0, true, pingPong);
  26529. }
  26530. }
  26531. if (time >= duration || time < 0) {
  26532. // wrap around
  26533. var loopDelta = Math.floor(time / duration); // signed
  26534. time -= duration * loopDelta;
  26535. loopCount += Math.abs(loopDelta);
  26536. var pending = this.repetitions - loopCount;
  26537. if (pending <= 0) {
  26538. // have to stop (switch state, clamp time, fire event)
  26539. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26540. time = deltaTime > 0 ? duration : 0;
  26541. this.time = time;
  26542. this._mixer.dispatchEvent({
  26543. type: 'finished',
  26544. action: this,
  26545. direction: deltaTime > 0 ? 1 : -1
  26546. });
  26547. } else {
  26548. // keep running
  26549. if (pending === 1) {
  26550. // entering the last round
  26551. var atStart = deltaTime < 0;
  26552. this._setEndings(atStart, !atStart, pingPong);
  26553. } else {
  26554. this._setEndings(false, false, pingPong);
  26555. }
  26556. this._loopCount = loopCount;
  26557. this.time = time;
  26558. this._mixer.dispatchEvent({
  26559. type: 'loop',
  26560. action: this,
  26561. loopDelta: loopDelta
  26562. });
  26563. }
  26564. } else {
  26565. this.time = time;
  26566. }
  26567. if (pingPong && (loopCount & 1) === 1) {
  26568. // invert time for the "pong round"
  26569. return duration - time;
  26570. }
  26571. }
  26572. return time;
  26573. },
  26574. _setEndings: function (atStart, atEnd, pingPong) {
  26575. var settings = this._interpolantSettings;
  26576. if (pingPong) {
  26577. settings.endingStart = ZeroSlopeEnding;
  26578. settings.endingEnd = ZeroSlopeEnding;
  26579. } else {
  26580. // assuming for LoopOnce atStart == atEnd == true
  26581. if (atStart) {
  26582. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26583. } else {
  26584. settings.endingStart = WrapAroundEnding;
  26585. }
  26586. if (atEnd) {
  26587. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26588. } else {
  26589. settings.endingEnd = WrapAroundEnding;
  26590. }
  26591. }
  26592. },
  26593. _scheduleFading: function (duration, weightNow, weightThen) {
  26594. var mixer = this._mixer,
  26595. now = mixer.time,
  26596. interpolant = this._weightInterpolant;
  26597. if (interpolant === null) {
  26598. interpolant = mixer._lendControlInterpolant();
  26599. this._weightInterpolant = interpolant;
  26600. }
  26601. var times = interpolant.parameterPositions,
  26602. values = interpolant.sampleValues;
  26603. times[0] = now;
  26604. values[0] = weightNow;
  26605. times[1] = now + duration;
  26606. values[1] = weightThen;
  26607. return this;
  26608. }
  26609. });
  26610. /**
  26611. *
  26612. * Player for AnimationClips.
  26613. *
  26614. *
  26615. * @author Ben Houston / http://clara.io/
  26616. * @author David Sarno / http://lighthaus.us/
  26617. * @author tschw
  26618. */
  26619. function AnimationMixer(root) {
  26620. this._root = root;
  26621. this._initMemoryManager();
  26622. this._accuIndex = 0;
  26623. this.time = 0;
  26624. this.timeScale = 1.0;
  26625. }
  26626. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  26627. constructor: AnimationMixer,
  26628. _bindAction: function (action, prototypeAction) {
  26629. var root = action._localRoot || this._root,
  26630. tracks = action._clip.tracks,
  26631. nTracks = tracks.length,
  26632. bindings = action._propertyBindings,
  26633. interpolants = action._interpolants,
  26634. rootUuid = root.uuid,
  26635. bindingsByRoot = this._bindingsByRootAndName,
  26636. bindingsByName = bindingsByRoot[rootUuid];
  26637. if (bindingsByName === undefined) {
  26638. bindingsByName = {};
  26639. bindingsByRoot[rootUuid] = bindingsByName;
  26640. }
  26641. for (var i = 0; i !== nTracks; ++i) {
  26642. var track = tracks[i],
  26643. trackName = track.name,
  26644. binding = bindingsByName[trackName];
  26645. if (binding !== undefined) {
  26646. bindings[i] = binding;
  26647. } else {
  26648. binding = bindings[i];
  26649. if (binding !== undefined) {
  26650. // existing binding, make sure the cache knows
  26651. if (binding._cacheIndex === null) {
  26652. ++binding.referenceCount;
  26653. this._addInactiveBinding(binding, rootUuid, trackName);
  26654. }
  26655. continue;
  26656. }
  26657. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26658. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26659. ++binding.referenceCount;
  26660. this._addInactiveBinding(binding, rootUuid, trackName);
  26661. bindings[i] = binding;
  26662. }
  26663. interpolants[i].resultBuffer = binding.buffer;
  26664. }
  26665. },
  26666. _activateAction: function (action) {
  26667. if (!this._isActiveAction(action)) {
  26668. if (action._cacheIndex === null) {
  26669. // this action has been forgotten by the cache, but the user
  26670. // appears to be still using it -> rebind
  26671. var rootUuid = (action._localRoot || this._root).uuid,
  26672. clipUuid = action._clip.uuid,
  26673. actionsForClip = this._actionsByClip[clipUuid];
  26674. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26675. this._addInactiveAction(action, clipUuid, rootUuid);
  26676. }
  26677. var bindings = action._propertyBindings; // increment reference counts / sort out state
  26678. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26679. var binding = bindings[i];
  26680. if (binding.useCount++ === 0) {
  26681. this._lendBinding(binding);
  26682. binding.saveOriginalState();
  26683. }
  26684. }
  26685. this._lendAction(action);
  26686. }
  26687. },
  26688. _deactivateAction: function (action) {
  26689. if (this._isActiveAction(action)) {
  26690. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  26691. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26692. var binding = bindings[i];
  26693. if (--binding.useCount === 0) {
  26694. binding.restoreOriginalState();
  26695. this._takeBackBinding(binding);
  26696. }
  26697. }
  26698. this._takeBackAction(action);
  26699. }
  26700. },
  26701. // Memory manager
  26702. _initMemoryManager: function () {
  26703. this._actions = []; // 'nActiveActions' followed by inactive ones
  26704. this._nActiveActions = 0;
  26705. this._actionsByClip = {}; // inside:
  26706. // {
  26707. // knownActions: Array< AnimationAction > - used as prototypes
  26708. // actionByRoot: AnimationAction - lookup
  26709. // }
  26710. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26711. this._nActiveBindings = 0;
  26712. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26713. this._controlInterpolants = []; // same game as above
  26714. this._nActiveControlInterpolants = 0;
  26715. var scope = this;
  26716. this.stats = {
  26717. actions: {
  26718. get total() {
  26719. return scope._actions.length;
  26720. },
  26721. get inUse() {
  26722. return scope._nActiveActions;
  26723. }
  26724. },
  26725. bindings: {
  26726. get total() {
  26727. return scope._bindings.length;
  26728. },
  26729. get inUse() {
  26730. return scope._nActiveBindings;
  26731. }
  26732. },
  26733. controlInterpolants: {
  26734. get total() {
  26735. return scope._controlInterpolants.length;
  26736. },
  26737. get inUse() {
  26738. return scope._nActiveControlInterpolants;
  26739. }
  26740. }
  26741. };
  26742. },
  26743. // Memory management for AnimationAction objects
  26744. _isActiveAction: function (action) {
  26745. var index = action._cacheIndex;
  26746. return index !== null && index < this._nActiveActions;
  26747. },
  26748. _addInactiveAction: function (action, clipUuid, rootUuid) {
  26749. var actions = this._actions,
  26750. actionsByClip = this._actionsByClip,
  26751. actionsForClip = actionsByClip[clipUuid];
  26752. if (actionsForClip === undefined) {
  26753. actionsForClip = {
  26754. knownActions: [action],
  26755. actionByRoot: {}
  26756. };
  26757. action._byClipCacheIndex = 0;
  26758. actionsByClip[clipUuid] = actionsForClip;
  26759. } else {
  26760. var knownActions = actionsForClip.knownActions;
  26761. action._byClipCacheIndex = knownActions.length;
  26762. knownActions.push(action);
  26763. }
  26764. action._cacheIndex = actions.length;
  26765. actions.push(action);
  26766. actionsForClip.actionByRoot[rootUuid] = action;
  26767. },
  26768. _removeInactiveAction: function (action) {
  26769. var actions = this._actions,
  26770. lastInactiveAction = actions[actions.length - 1],
  26771. cacheIndex = action._cacheIndex;
  26772. lastInactiveAction._cacheIndex = cacheIndex;
  26773. actions[cacheIndex] = lastInactiveAction;
  26774. actions.pop();
  26775. action._cacheIndex = null;
  26776. var clipUuid = action._clip.uuid,
  26777. actionsByClip = this._actionsByClip,
  26778. actionsForClip = actionsByClip[clipUuid],
  26779. knownActionsForClip = actionsForClip.knownActions,
  26780. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26781. byClipCacheIndex = action._byClipCacheIndex;
  26782. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26783. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26784. knownActionsForClip.pop();
  26785. action._byClipCacheIndex = null;
  26786. var actionByRoot = actionsForClip.actionByRoot,
  26787. rootUuid = (action._localRoot || this._root).uuid;
  26788. delete actionByRoot[rootUuid];
  26789. if (knownActionsForClip.length === 0) {
  26790. delete actionsByClip[clipUuid];
  26791. }
  26792. this._removeInactiveBindingsForAction(action);
  26793. },
  26794. _removeInactiveBindingsForAction: function (action) {
  26795. var bindings = action._propertyBindings;
  26796. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26797. var binding = bindings[i];
  26798. if (--binding.referenceCount === 0) {
  26799. this._removeInactiveBinding(binding);
  26800. }
  26801. }
  26802. },
  26803. _lendAction: function (action) {
  26804. // [ active actions | inactive actions ]
  26805. // [ active actions >| inactive actions ]
  26806. // s a
  26807. // <-swap->
  26808. // a s
  26809. var actions = this._actions,
  26810. prevIndex = action._cacheIndex,
  26811. lastActiveIndex = this._nActiveActions++,
  26812. firstInactiveAction = actions[lastActiveIndex];
  26813. action._cacheIndex = lastActiveIndex;
  26814. actions[lastActiveIndex] = action;
  26815. firstInactiveAction._cacheIndex = prevIndex;
  26816. actions[prevIndex] = firstInactiveAction;
  26817. },
  26818. _takeBackAction: function (action) {
  26819. // [ active actions | inactive actions ]
  26820. // [ active actions |< inactive actions ]
  26821. // a s
  26822. // <-swap->
  26823. // s a
  26824. var actions = this._actions,
  26825. prevIndex = action._cacheIndex,
  26826. firstInactiveIndex = --this._nActiveActions,
  26827. lastActiveAction = actions[firstInactiveIndex];
  26828. action._cacheIndex = firstInactiveIndex;
  26829. actions[firstInactiveIndex] = action;
  26830. lastActiveAction._cacheIndex = prevIndex;
  26831. actions[prevIndex] = lastActiveAction;
  26832. },
  26833. // Memory management for PropertyMixer objects
  26834. _addInactiveBinding: function (binding, rootUuid, trackName) {
  26835. var bindingsByRoot = this._bindingsByRootAndName,
  26836. bindingByName = bindingsByRoot[rootUuid],
  26837. bindings = this._bindings;
  26838. if (bindingByName === undefined) {
  26839. bindingByName = {};
  26840. bindingsByRoot[rootUuid] = bindingByName;
  26841. }
  26842. bindingByName[trackName] = binding;
  26843. binding._cacheIndex = bindings.length;
  26844. bindings.push(binding);
  26845. },
  26846. _removeInactiveBinding: function (binding) {
  26847. var bindings = this._bindings,
  26848. propBinding = binding.binding,
  26849. rootUuid = propBinding.rootNode.uuid,
  26850. trackName = propBinding.path,
  26851. bindingsByRoot = this._bindingsByRootAndName,
  26852. bindingByName = bindingsByRoot[rootUuid],
  26853. lastInactiveBinding = bindings[bindings.length - 1],
  26854. cacheIndex = binding._cacheIndex;
  26855. lastInactiveBinding._cacheIndex = cacheIndex;
  26856. bindings[cacheIndex] = lastInactiveBinding;
  26857. bindings.pop();
  26858. delete bindingByName[trackName];
  26859. if (Object.keys(bindingByName).length === 0) {
  26860. delete bindingsByRoot[rootUuid];
  26861. }
  26862. },
  26863. _lendBinding: function (binding) {
  26864. var bindings = this._bindings,
  26865. prevIndex = binding._cacheIndex,
  26866. lastActiveIndex = this._nActiveBindings++,
  26867. firstInactiveBinding = bindings[lastActiveIndex];
  26868. binding._cacheIndex = lastActiveIndex;
  26869. bindings[lastActiveIndex] = binding;
  26870. firstInactiveBinding._cacheIndex = prevIndex;
  26871. bindings[prevIndex] = firstInactiveBinding;
  26872. },
  26873. _takeBackBinding: function (binding) {
  26874. var bindings = this._bindings,
  26875. prevIndex = binding._cacheIndex,
  26876. firstInactiveIndex = --this._nActiveBindings,
  26877. lastActiveBinding = bindings[firstInactiveIndex];
  26878. binding._cacheIndex = firstInactiveIndex;
  26879. bindings[firstInactiveIndex] = binding;
  26880. lastActiveBinding._cacheIndex = prevIndex;
  26881. bindings[prevIndex] = lastActiveBinding;
  26882. },
  26883. // Memory management of Interpolants for weight and time scale
  26884. _lendControlInterpolant: function () {
  26885. var interpolants = this._controlInterpolants,
  26886. lastActiveIndex = this._nActiveControlInterpolants++,
  26887. interpolant = interpolants[lastActiveIndex];
  26888. if (interpolant === undefined) {
  26889. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26890. interpolant.__cacheIndex = lastActiveIndex;
  26891. interpolants[lastActiveIndex] = interpolant;
  26892. }
  26893. return interpolant;
  26894. },
  26895. _takeBackControlInterpolant: function (interpolant) {
  26896. var interpolants = this._controlInterpolants,
  26897. prevIndex = interpolant.__cacheIndex,
  26898. firstInactiveIndex = --this._nActiveControlInterpolants,
  26899. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26900. interpolant.__cacheIndex = firstInactiveIndex;
  26901. interpolants[firstInactiveIndex] = interpolant;
  26902. lastActiveInterpolant.__cacheIndex = prevIndex;
  26903. interpolants[prevIndex] = lastActiveInterpolant;
  26904. },
  26905. _controlInterpolantsResultBuffer: new Float32Array(1),
  26906. // return an action for a clip optionally using a custom root target
  26907. // object (this method allocates a lot of dynamic memory in case a
  26908. // previously unknown clip/root combination is specified)
  26909. clipAction: function (clip, optionalRoot) {
  26910. var root = optionalRoot || this._root,
  26911. rootUuid = root.uuid,
  26912. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26913. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  26914. actionsForClip = this._actionsByClip[clipUuid],
  26915. prototypeAction = null;
  26916. if (actionsForClip !== undefined) {
  26917. var existingAction = actionsForClip.actionByRoot[rootUuid];
  26918. if (existingAction !== undefined) {
  26919. return existingAction;
  26920. } // we know the clip, so we don't have to parse all
  26921. // the bindings again but can just copy
  26922. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26923. if (clipObject === null) clipObject = prototypeAction._clip;
  26924. } // clip must be known when specified via string
  26925. if (clipObject === null) return null; // allocate all resources required to run it
  26926. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  26927. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26928. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26929. return newAction;
  26930. },
  26931. // get an existing action
  26932. existingAction: function (clip, optionalRoot) {
  26933. var root = optionalRoot || this._root,
  26934. rootUuid = root.uuid,
  26935. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26936. clipUuid = clipObject ? clipObject.uuid : clip,
  26937. actionsForClip = this._actionsByClip[clipUuid];
  26938. if (actionsForClip !== undefined) {
  26939. return actionsForClip.actionByRoot[rootUuid] || null;
  26940. }
  26941. return null;
  26942. },
  26943. // deactivates all previously scheduled actions
  26944. stopAllAction: function () {
  26945. var actions = this._actions,
  26946. nActions = this._nActiveActions,
  26947. bindings = this._bindings,
  26948. nBindings = this._nActiveBindings;
  26949. this._nActiveActions = 0;
  26950. this._nActiveBindings = 0;
  26951. for (var i = 0; i !== nActions; ++i) {
  26952. actions[i].reset();
  26953. }
  26954. for (var i = 0; i !== nBindings; ++i) {
  26955. bindings[i].useCount = 0;
  26956. }
  26957. return this;
  26958. },
  26959. // advance the time and update apply the animation
  26960. update: function (deltaTime) {
  26961. deltaTime *= this.timeScale;
  26962. var actions = this._actions,
  26963. nActions = this._nActiveActions,
  26964. time = this.time += deltaTime,
  26965. timeDirection = Math.sign(deltaTime),
  26966. accuIndex = this._accuIndex ^= 1; // run active actions
  26967. for (var i = 0; i !== nActions; ++i) {
  26968. var action = actions[i];
  26969. action._update(time, deltaTime, timeDirection, accuIndex);
  26970. } // update scene graph
  26971. var bindings = this._bindings,
  26972. nBindings = this._nActiveBindings;
  26973. for (var i = 0; i !== nBindings; ++i) {
  26974. bindings[i].apply(accuIndex);
  26975. }
  26976. return this;
  26977. },
  26978. // Allows you to seek to a specific time in an animation.
  26979. setTime: function (timeInSeconds) {
  26980. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26981. for (var i = 0; i < this._actions.length; i++) {
  26982. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26983. }
  26984. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26985. },
  26986. // return this mixer's root target object
  26987. getRoot: function () {
  26988. return this._root;
  26989. },
  26990. // free all resources specific to a particular clip
  26991. uncacheClip: function (clip) {
  26992. var actions = this._actions,
  26993. clipUuid = clip.uuid,
  26994. actionsByClip = this._actionsByClip,
  26995. actionsForClip = actionsByClip[clipUuid];
  26996. if (actionsForClip !== undefined) {
  26997. // note: just calling _removeInactiveAction would mess up the
  26998. // iteration state and also require updating the state we can
  26999. // just throw away
  27000. var actionsToRemove = actionsForClip.knownActions;
  27001. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27002. var action = actionsToRemove[i];
  27003. this._deactivateAction(action);
  27004. var cacheIndex = action._cacheIndex,
  27005. lastInactiveAction = actions[actions.length - 1];
  27006. action._cacheIndex = null;
  27007. action._byClipCacheIndex = null;
  27008. lastInactiveAction._cacheIndex = cacheIndex;
  27009. actions[cacheIndex] = lastInactiveAction;
  27010. actions.pop();
  27011. this._removeInactiveBindingsForAction(action);
  27012. }
  27013. delete actionsByClip[clipUuid];
  27014. }
  27015. },
  27016. // free all resources specific to a particular root target object
  27017. uncacheRoot: function (root) {
  27018. var rootUuid = root.uuid,
  27019. actionsByClip = this._actionsByClip;
  27020. for (var clipUuid in actionsByClip) {
  27021. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27022. action = actionByRoot[rootUuid];
  27023. if (action !== undefined) {
  27024. this._deactivateAction(action);
  27025. this._removeInactiveAction(action);
  27026. }
  27027. }
  27028. var bindingsByRoot = this._bindingsByRootAndName,
  27029. bindingByName = bindingsByRoot[rootUuid];
  27030. if (bindingByName !== undefined) {
  27031. for (var trackName in bindingByName) {
  27032. var binding = bindingByName[trackName];
  27033. binding.restoreOriginalState();
  27034. this._removeInactiveBinding(binding);
  27035. }
  27036. }
  27037. },
  27038. // remove a targeted clip from the cache
  27039. uncacheAction: function (clip, optionalRoot) {
  27040. var action = this.existingAction(clip, optionalRoot);
  27041. if (action !== null) {
  27042. this._deactivateAction(action);
  27043. this._removeInactiveAction(action);
  27044. }
  27045. }
  27046. });
  27047. /**
  27048. * @author mrdoob / http://mrdoob.com/
  27049. */
  27050. function Uniform(value) {
  27051. if (typeof value === 'string') {
  27052. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27053. value = arguments[1];
  27054. }
  27055. this.value = value;
  27056. }
  27057. Uniform.prototype.clone = function () {
  27058. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27059. };
  27060. /**
  27061. * @author benaadams / https://twitter.com/ben_a_adams
  27062. */
  27063. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27064. InterleavedBuffer.call(this, array, stride);
  27065. this.meshPerAttribute = meshPerAttribute || 1;
  27066. }
  27067. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27068. constructor: InstancedInterleavedBuffer,
  27069. isInstancedInterleavedBuffer: true,
  27070. copy: function (source) {
  27071. InterleavedBuffer.prototype.copy.call(this, source);
  27072. this.meshPerAttribute = source.meshPerAttribute;
  27073. return this;
  27074. }
  27075. });
  27076. /**
  27077. * @author mrdoob / http://mrdoob.com/
  27078. * @author bhouston / http://clara.io/
  27079. * @author stephomi / http://stephaneginier.com/
  27080. */
  27081. function Raycaster(origin, direction, near, far) {
  27082. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27083. this.near = near || 0;
  27084. this.far = far || Infinity;
  27085. this.camera = null;
  27086. this.layers = new Layers();
  27087. this.params = {
  27088. Mesh: {},
  27089. Line: {
  27090. threshold: 1
  27091. },
  27092. LOD: {},
  27093. Points: {
  27094. threshold: 1
  27095. },
  27096. Sprite: {}
  27097. };
  27098. Object.defineProperties(this.params, {
  27099. PointCloud: {
  27100. get: function () {
  27101. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27102. return this.Points;
  27103. }
  27104. }
  27105. });
  27106. }
  27107. function ascSort(a, b) {
  27108. return a.distance - b.distance;
  27109. }
  27110. function intersectObject(object, raycaster, intersects, recursive) {
  27111. if (object.layers.test(raycaster.layers)) {
  27112. object.raycast(raycaster, intersects);
  27113. }
  27114. if (recursive === true) {
  27115. var children = object.children;
  27116. for (var i = 0, l = children.length; i < l; i++) {
  27117. intersectObject(children[i], raycaster, intersects, true);
  27118. }
  27119. }
  27120. }
  27121. Object.assign(Raycaster.prototype, {
  27122. set: function (origin, direction) {
  27123. // direction is assumed to be normalized (for accurate distance calculations)
  27124. this.ray.set(origin, direction);
  27125. },
  27126. setFromCamera: function (coords, camera) {
  27127. if (camera && camera.isPerspectiveCamera) {
  27128. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27129. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27130. this.camera = camera;
  27131. } else if (camera && camera.isOrthographicCamera) {
  27132. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27133. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27134. this.camera = camera;
  27135. } else {
  27136. console.error('THREE.Raycaster: Unsupported camera type.');
  27137. }
  27138. },
  27139. intersectObject: function (object, recursive, optionalTarget) {
  27140. var intersects = optionalTarget || [];
  27141. intersectObject(object, this, intersects, recursive);
  27142. intersects.sort(ascSort);
  27143. return intersects;
  27144. },
  27145. intersectObjects: function (objects, recursive, optionalTarget) {
  27146. var intersects = optionalTarget || [];
  27147. if (Array.isArray(objects) === false) {
  27148. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27149. return intersects;
  27150. }
  27151. for (var i = 0, l = objects.length; i < l; i++) {
  27152. intersectObject(objects[i], this, intersects, recursive);
  27153. }
  27154. intersects.sort(ascSort);
  27155. return intersects;
  27156. }
  27157. });
  27158. /**
  27159. * @author bhouston / http://clara.io
  27160. * @author WestLangley / http://github.com/WestLangley
  27161. *
  27162. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27163. *
  27164. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27165. * The azimuthal angle (theta) is measured from the positive z-axis.
  27166. */
  27167. function Spherical(radius, phi, theta) {
  27168. this.radius = radius !== undefined ? radius : 1.0;
  27169. this.phi = phi !== undefined ? phi : 0; // polar angle
  27170. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27171. return this;
  27172. }
  27173. Object.assign(Spherical.prototype, {
  27174. set: function (radius, phi, theta) {
  27175. this.radius = radius;
  27176. this.phi = phi;
  27177. this.theta = theta;
  27178. return this;
  27179. },
  27180. clone: function () {
  27181. return new this.constructor().copy(this);
  27182. },
  27183. copy: function (other) {
  27184. this.radius = other.radius;
  27185. this.phi = other.phi;
  27186. this.theta = other.theta;
  27187. return this;
  27188. },
  27189. // restrict phi to be betwee EPS and PI-EPS
  27190. makeSafe: function () {
  27191. var EPS = 0.000001;
  27192. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27193. return this;
  27194. },
  27195. setFromVector3: function (v) {
  27196. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27197. },
  27198. setFromCartesianCoords: function (x, y, z) {
  27199. this.radius = Math.sqrt(x * x + y * y + z * z);
  27200. if (this.radius === 0) {
  27201. this.theta = 0;
  27202. this.phi = 0;
  27203. } else {
  27204. this.theta = Math.atan2(x, z);
  27205. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  27206. }
  27207. return this;
  27208. }
  27209. });
  27210. /**
  27211. * @author Mugen87 / https://github.com/Mugen87
  27212. *
  27213. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27214. *
  27215. */
  27216. function Cylindrical(radius, theta, y) {
  27217. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27218. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27219. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27220. return this;
  27221. }
  27222. Object.assign(Cylindrical.prototype, {
  27223. set: function (radius, theta, y) {
  27224. this.radius = radius;
  27225. this.theta = theta;
  27226. this.y = y;
  27227. return this;
  27228. },
  27229. clone: function () {
  27230. return new this.constructor().copy(this);
  27231. },
  27232. copy: function (other) {
  27233. this.radius = other.radius;
  27234. this.theta = other.theta;
  27235. this.y = other.y;
  27236. return this;
  27237. },
  27238. setFromVector3: function (v) {
  27239. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27240. },
  27241. setFromCartesianCoords: function (x, y, z) {
  27242. this.radius = Math.sqrt(x * x + z * z);
  27243. this.theta = Math.atan2(x, z);
  27244. this.y = y;
  27245. return this;
  27246. }
  27247. });
  27248. /**
  27249. * @author bhouston / http://clara.io
  27250. */
  27251. var _vector$7 = new Vector2();
  27252. function Box2(min, max) {
  27253. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27254. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27255. }
  27256. Object.assign(Box2.prototype, {
  27257. set: function (min, max) {
  27258. this.min.copy(min);
  27259. this.max.copy(max);
  27260. return this;
  27261. },
  27262. setFromPoints: function (points) {
  27263. this.makeEmpty();
  27264. for (var i = 0, il = points.length; i < il; i++) {
  27265. this.expandByPoint(points[i]);
  27266. }
  27267. return this;
  27268. },
  27269. setFromCenterAndSize: function (center, size) {
  27270. var halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  27271. this.min.copy(center).sub(halfSize);
  27272. this.max.copy(center).add(halfSize);
  27273. return this;
  27274. },
  27275. clone: function () {
  27276. return new this.constructor().copy(this);
  27277. },
  27278. copy: function (box) {
  27279. this.min.copy(box.min);
  27280. this.max.copy(box.max);
  27281. return this;
  27282. },
  27283. makeEmpty: function () {
  27284. this.min.x = this.min.y = +Infinity;
  27285. this.max.x = this.max.y = -Infinity;
  27286. return this;
  27287. },
  27288. isEmpty: function () {
  27289. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27290. return this.max.x < this.min.x || this.max.y < this.min.y;
  27291. },
  27292. getCenter: function (target) {
  27293. if (target === undefined) {
  27294. console.warn('THREE.Box2: .getCenter() target is now required');
  27295. target = new Vector2();
  27296. }
  27297. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27298. },
  27299. getSize: function (target) {
  27300. if (target === undefined) {
  27301. console.warn('THREE.Box2: .getSize() target is now required');
  27302. target = new Vector2();
  27303. }
  27304. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27305. },
  27306. expandByPoint: function (point) {
  27307. this.min.min(point);
  27308. this.max.max(point);
  27309. return this;
  27310. },
  27311. expandByVector: function (vector) {
  27312. this.min.sub(vector);
  27313. this.max.add(vector);
  27314. return this;
  27315. },
  27316. expandByScalar: function (scalar) {
  27317. this.min.addScalar(-scalar);
  27318. this.max.addScalar(scalar);
  27319. return this;
  27320. },
  27321. containsPoint: function (point) {
  27322. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27323. },
  27324. containsBox: function (box) {
  27325. 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;
  27326. },
  27327. getParameter: function (point, target) {
  27328. // This can potentially have a divide by zero if the box
  27329. // has a size dimension of 0.
  27330. if (target === undefined) {
  27331. console.warn('THREE.Box2: .getParameter() target is now required');
  27332. target = new Vector2();
  27333. }
  27334. 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));
  27335. },
  27336. intersectsBox: function (box) {
  27337. // using 4 splitting planes to rule out intersections
  27338. 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;
  27339. },
  27340. clampPoint: function (point, target) {
  27341. if (target === undefined) {
  27342. console.warn('THREE.Box2: .clampPoint() target is now required');
  27343. target = new Vector2();
  27344. }
  27345. return target.copy(point).clamp(this.min, this.max);
  27346. },
  27347. distanceToPoint: function (point) {
  27348. var clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  27349. return clampedPoint.sub(point).length();
  27350. },
  27351. intersect: function (box) {
  27352. this.min.max(box.min);
  27353. this.max.min(box.max);
  27354. return this;
  27355. },
  27356. union: function (box) {
  27357. this.min.min(box.min);
  27358. this.max.max(box.max);
  27359. return this;
  27360. },
  27361. translate: function (offset) {
  27362. this.min.add(offset);
  27363. this.max.add(offset);
  27364. return this;
  27365. },
  27366. equals: function (box) {
  27367. return box.min.equals(this.min) && box.max.equals(this.max);
  27368. }
  27369. });
  27370. /**
  27371. * @author bhouston / http://clara.io
  27372. */
  27373. var _startP = new Vector3();
  27374. var _startEnd = new Vector3();
  27375. function Line3(start, end) {
  27376. this.start = start !== undefined ? start : new Vector3();
  27377. this.end = end !== undefined ? end : new Vector3();
  27378. }
  27379. Object.assign(Line3.prototype, {
  27380. set: function (start, end) {
  27381. this.start.copy(start);
  27382. this.end.copy(end);
  27383. return this;
  27384. },
  27385. clone: function () {
  27386. return new this.constructor().copy(this);
  27387. },
  27388. copy: function (line) {
  27389. this.start.copy(line.start);
  27390. this.end.copy(line.end);
  27391. return this;
  27392. },
  27393. getCenter: function (target) {
  27394. if (target === undefined) {
  27395. console.warn('THREE.Line3: .getCenter() target is now required');
  27396. target = new Vector3();
  27397. }
  27398. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27399. },
  27400. delta: function (target) {
  27401. if (target === undefined) {
  27402. console.warn('THREE.Line3: .delta() target is now required');
  27403. target = new Vector3();
  27404. }
  27405. return target.subVectors(this.end, this.start);
  27406. },
  27407. distanceSq: function () {
  27408. return this.start.distanceToSquared(this.end);
  27409. },
  27410. distance: function () {
  27411. return this.start.distanceTo(this.end);
  27412. },
  27413. at: function (t, target) {
  27414. if (target === undefined) {
  27415. console.warn('THREE.Line3: .at() target is now required');
  27416. target = new Vector3();
  27417. }
  27418. return this.delta(target).multiplyScalar(t).add(this.start);
  27419. },
  27420. closestPointToPointParameter: function (point, clampToLine) {
  27421. _startP.subVectors(point, this.start);
  27422. _startEnd.subVectors(this.end, this.start);
  27423. var startEnd2 = _startEnd.dot(_startEnd);
  27424. var startEnd_startP = _startEnd.dot(_startP);
  27425. var t = startEnd_startP / startEnd2;
  27426. if (clampToLine) {
  27427. t = MathUtils.clamp(t, 0, 1);
  27428. }
  27429. return t;
  27430. },
  27431. closestPointToPoint: function (point, clampToLine, target) {
  27432. var t = this.closestPointToPointParameter(point, clampToLine);
  27433. if (target === undefined) {
  27434. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27435. target = new Vector3();
  27436. }
  27437. return this.delta(target).multiplyScalar(t).add(this.start);
  27438. },
  27439. applyMatrix4: function (matrix) {
  27440. this.start.applyMatrix4(matrix);
  27441. this.end.applyMatrix4(matrix);
  27442. return this;
  27443. },
  27444. equals: function (line) {
  27445. return line.start.equals(this.start) && line.end.equals(this.end);
  27446. }
  27447. });
  27448. /**
  27449. * @author alteredq / http://alteredqualia.com/
  27450. */
  27451. function ImmediateRenderObject(material) {
  27452. Object3D.call(this);
  27453. this.material = material;
  27454. this.render = function ()
  27455. /* renderCallback */
  27456. {};
  27457. }
  27458. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  27459. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27460. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27461. /**
  27462. * @author alteredq / http://alteredqualia.com/
  27463. * @author mrdoob / http://mrdoob.com/
  27464. * @author WestLangley / http://github.com/WestLangley
  27465. */
  27466. var _vector$8 = new Vector3();
  27467. function SpotLightHelper(light, color) {
  27468. Object3D.call(this);
  27469. this.light = light;
  27470. this.light.updateMatrixWorld();
  27471. this.matrix = light.matrixWorld;
  27472. this.matrixAutoUpdate = false;
  27473. this.color = color;
  27474. var geometry = new BufferGeometry();
  27475. var 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];
  27476. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  27477. var p1 = i / l * Math.PI * 2;
  27478. var p2 = j / l * Math.PI * 2;
  27479. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27480. }
  27481. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27482. var material = new LineBasicMaterial({
  27483. fog: false,
  27484. toneMapped: false
  27485. });
  27486. this.cone = new LineSegments(geometry, material);
  27487. this.add(this.cone);
  27488. this.update();
  27489. }
  27490. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  27491. SpotLightHelper.prototype.constructor = SpotLightHelper;
  27492. SpotLightHelper.prototype.dispose = function () {
  27493. this.cone.geometry.dispose();
  27494. this.cone.material.dispose();
  27495. };
  27496. SpotLightHelper.prototype.update = function () {
  27497. this.light.updateMatrixWorld();
  27498. var coneLength = this.light.distance ? this.light.distance : 1000;
  27499. var coneWidth = coneLength * Math.tan(this.light.angle);
  27500. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27501. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  27502. this.cone.lookAt(_vector$8);
  27503. if (this.color !== undefined) {
  27504. this.cone.material.color.set(this.color);
  27505. } else {
  27506. this.cone.material.color.copy(this.light.color);
  27507. }
  27508. };
  27509. /**
  27510. * @author Sean Griffin / http://twitter.com/sgrif
  27511. * @author Michael Guerrero / http://realitymeltdown.com
  27512. * @author mrdoob / http://mrdoob.com/
  27513. * @author ikerr / http://verold.com
  27514. * @author Mugen87 / https://github.com/Mugen87
  27515. */
  27516. var _vector$9 = new Vector3();
  27517. var _boneMatrix = new Matrix4();
  27518. var _matrixWorldInv = new Matrix4();
  27519. function getBoneList(object) {
  27520. var boneList = [];
  27521. if (object && object.isBone) {
  27522. boneList.push(object);
  27523. }
  27524. for (var i = 0; i < object.children.length; i++) {
  27525. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27526. }
  27527. return boneList;
  27528. }
  27529. function SkeletonHelper(object) {
  27530. var bones = getBoneList(object);
  27531. var geometry = new BufferGeometry();
  27532. var vertices = [];
  27533. var colors = [];
  27534. var color1 = new Color(0, 0, 1);
  27535. var color2 = new Color(0, 1, 0);
  27536. for (var i = 0; i < bones.length; i++) {
  27537. var bone = bones[i];
  27538. if (bone.parent && bone.parent.isBone) {
  27539. vertices.push(0, 0, 0);
  27540. vertices.push(0, 0, 0);
  27541. colors.push(color1.r, color1.g, color1.b);
  27542. colors.push(color2.r, color2.g, color2.b);
  27543. }
  27544. }
  27545. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27546. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27547. var material = new LineBasicMaterial({
  27548. vertexColors: true,
  27549. depthTest: false,
  27550. depthWrite: false,
  27551. toneMapped: false,
  27552. transparent: true
  27553. });
  27554. LineSegments.call(this, geometry, material);
  27555. this.root = object;
  27556. this.bones = bones;
  27557. this.matrix = object.matrixWorld;
  27558. this.matrixAutoUpdate = false;
  27559. }
  27560. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  27561. SkeletonHelper.prototype.constructor = SkeletonHelper;
  27562. SkeletonHelper.prototype.isSkeletonHelper = true;
  27563. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  27564. var bones = this.bones;
  27565. var geometry = this.geometry;
  27566. var position = geometry.getAttribute('position');
  27567. _matrixWorldInv.getInverse(this.root.matrixWorld);
  27568. for (var i = 0, j = 0; i < bones.length; i++) {
  27569. var bone = bones[i];
  27570. if (bone.parent && bone.parent.isBone) {
  27571. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27572. _vector$9.setFromMatrixPosition(_boneMatrix);
  27573. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  27574. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27575. _vector$9.setFromMatrixPosition(_boneMatrix);
  27576. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  27577. j += 2;
  27578. }
  27579. }
  27580. geometry.getAttribute('position').needsUpdate = true;
  27581. Object3D.prototype.updateMatrixWorld.call(this, force);
  27582. };
  27583. /**
  27584. * @author alteredq / http://alteredqualia.com/
  27585. * @author mrdoob / http://mrdoob.com/
  27586. */
  27587. function PointLightHelper(light, sphereSize, color) {
  27588. this.light = light;
  27589. this.light.updateMatrixWorld();
  27590. this.color = color;
  27591. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  27592. var material = new MeshBasicMaterial({
  27593. wireframe: true,
  27594. fog: false,
  27595. toneMapped: false
  27596. });
  27597. Mesh.call(this, geometry, material);
  27598. this.matrix = this.light.matrixWorld;
  27599. this.matrixAutoUpdate = false;
  27600. this.update();
  27601. /*
  27602. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27603. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27604. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27605. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27606. var d = light.distance;
  27607. if ( d === 0.0 ) {
  27608. this.lightDistance.visible = false;
  27609. } else {
  27610. this.lightDistance.scale.set( d, d, d );
  27611. }
  27612. this.add( this.lightDistance );
  27613. */
  27614. }
  27615. PointLightHelper.prototype = Object.create(Mesh.prototype);
  27616. PointLightHelper.prototype.constructor = PointLightHelper;
  27617. PointLightHelper.prototype.dispose = function () {
  27618. this.geometry.dispose();
  27619. this.material.dispose();
  27620. };
  27621. PointLightHelper.prototype.update = function () {
  27622. if (this.color !== undefined) {
  27623. this.material.color.set(this.color);
  27624. } else {
  27625. this.material.color.copy(this.light.color);
  27626. }
  27627. /*
  27628. var d = this.light.distance;
  27629. if ( d === 0.0 ) {
  27630. this.lightDistance.visible = false;
  27631. } else {
  27632. this.lightDistance.visible = true;
  27633. this.lightDistance.scale.set( d, d, d );
  27634. }
  27635. */
  27636. };
  27637. /**
  27638. * @author alteredq / http://alteredqualia.com/
  27639. * @author mrdoob / http://mrdoob.com/
  27640. * @author Mugen87 / https://github.com/Mugen87
  27641. */
  27642. var _vector$a = new Vector3();
  27643. var _color1 = new Color();
  27644. var _color2 = new Color();
  27645. function HemisphereLightHelper(light, size, color) {
  27646. Object3D.call(this);
  27647. this.light = light;
  27648. this.light.updateMatrixWorld();
  27649. this.matrix = light.matrixWorld;
  27650. this.matrixAutoUpdate = false;
  27651. this.color = color;
  27652. var geometry = new OctahedronBufferGeometry(size);
  27653. geometry.rotateY(Math.PI * 0.5);
  27654. this.material = new MeshBasicMaterial({
  27655. wireframe: true,
  27656. fog: false,
  27657. toneMapped: false
  27658. });
  27659. if (this.color === undefined) this.material.vertexColors = true;
  27660. var position = geometry.getAttribute('position');
  27661. var colors = new Float32Array(position.count * 3);
  27662. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27663. this.add(new Mesh(geometry, this.material));
  27664. this.update();
  27665. }
  27666. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  27667. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  27668. HemisphereLightHelper.prototype.dispose = function () {
  27669. this.children[0].geometry.dispose();
  27670. this.children[0].material.dispose();
  27671. };
  27672. HemisphereLightHelper.prototype.update = function () {
  27673. var mesh = this.children[0];
  27674. if (this.color !== undefined) {
  27675. this.material.color.set(this.color);
  27676. } else {
  27677. var colors = mesh.geometry.getAttribute('color');
  27678. _color1.copy(this.light.color);
  27679. _color2.copy(this.light.groundColor);
  27680. for (var i = 0, l = colors.count; i < l; i++) {
  27681. var color = i < l / 2 ? _color1 : _color2;
  27682. colors.setXYZ(i, color.r, color.g, color.b);
  27683. }
  27684. colors.needsUpdate = true;
  27685. }
  27686. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  27687. };
  27688. /**
  27689. * @author mrdoob / http://mrdoob.com/
  27690. */
  27691. function GridHelper(size, divisions, color1, color2) {
  27692. size = size || 10;
  27693. divisions = divisions || 10;
  27694. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27695. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27696. var center = divisions / 2;
  27697. var step = size / divisions;
  27698. var halfSize = size / 2;
  27699. var vertices = [],
  27700. colors = [];
  27701. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27702. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27703. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27704. var color = i === center ? color1 : color2;
  27705. color.toArray(colors, j);
  27706. j += 3;
  27707. color.toArray(colors, j);
  27708. j += 3;
  27709. color.toArray(colors, j);
  27710. j += 3;
  27711. color.toArray(colors, j);
  27712. j += 3;
  27713. }
  27714. var geometry = new BufferGeometry();
  27715. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27716. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27717. var material = new LineBasicMaterial({
  27718. vertexColors: true,
  27719. toneMapped: false
  27720. });
  27721. LineSegments.call(this, geometry, material);
  27722. }
  27723. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  27724. constructor: GridHelper,
  27725. copy: function (source) {
  27726. LineSegments.prototype.copy.call(this, source);
  27727. this.geometry.copy(source.geometry);
  27728. this.material.copy(source.material);
  27729. return this;
  27730. },
  27731. clone: function () {
  27732. return new this.constructor().copy(this);
  27733. }
  27734. });
  27735. /**
  27736. * @author mrdoob / http://mrdoob.com/
  27737. * @author Mugen87 / http://github.com/Mugen87
  27738. * @author Hectate / http://www.github.com/Hectate
  27739. */
  27740. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  27741. radius = radius || 10;
  27742. radials = radials || 16;
  27743. circles = circles || 8;
  27744. divisions = divisions || 64;
  27745. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27746. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27747. var vertices = [];
  27748. var colors = [];
  27749. var x, z;
  27750. var v, i, j, r, color; // create the radials
  27751. for (i = 0; i <= radials; i++) {
  27752. v = i / radials * (Math.PI * 2);
  27753. x = Math.sin(v) * radius;
  27754. z = Math.cos(v) * radius;
  27755. vertices.push(0, 0, 0);
  27756. vertices.push(x, 0, z);
  27757. color = i & 1 ? color1 : color2;
  27758. colors.push(color.r, color.g, color.b);
  27759. colors.push(color.r, color.g, color.b);
  27760. } // create the circles
  27761. for (i = 0; i <= circles; i++) {
  27762. color = i & 1 ? color1 : color2;
  27763. r = radius - radius / circles * i;
  27764. for (j = 0; j < divisions; j++) {
  27765. // first vertex
  27766. v = j / divisions * (Math.PI * 2);
  27767. x = Math.sin(v) * r;
  27768. z = Math.cos(v) * r;
  27769. vertices.push(x, 0, z);
  27770. colors.push(color.r, color.g, color.b); // second vertex
  27771. v = (j + 1) / divisions * (Math.PI * 2);
  27772. x = Math.sin(v) * r;
  27773. z = Math.cos(v) * r;
  27774. vertices.push(x, 0, z);
  27775. colors.push(color.r, color.g, color.b);
  27776. }
  27777. }
  27778. var geometry = new BufferGeometry();
  27779. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27780. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27781. var material = new LineBasicMaterial({
  27782. vertexColors: true,
  27783. toneMapped: false
  27784. });
  27785. LineSegments.call(this, geometry, material);
  27786. }
  27787. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  27788. PolarGridHelper.prototype.constructor = PolarGridHelper;
  27789. /**
  27790. * @author alteredq / http://alteredqualia.com/
  27791. * @author mrdoob / http://mrdoob.com/
  27792. * @author WestLangley / http://github.com/WestLangley
  27793. */
  27794. var _v1$5 = new Vector3();
  27795. var _v2$3 = new Vector3();
  27796. var _v3$1 = new Vector3();
  27797. function DirectionalLightHelper(light, size, color) {
  27798. Object3D.call(this);
  27799. this.light = light;
  27800. this.light.updateMatrixWorld();
  27801. this.matrix = light.matrixWorld;
  27802. this.matrixAutoUpdate = false;
  27803. this.color = color;
  27804. if (size === undefined) size = 1;
  27805. var geometry = new BufferGeometry();
  27806. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27807. var material = new LineBasicMaterial({
  27808. fog: false,
  27809. toneMapped: false
  27810. });
  27811. this.lightPlane = new Line(geometry, material);
  27812. this.add(this.lightPlane);
  27813. geometry = new BufferGeometry();
  27814. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27815. this.targetLine = new Line(geometry, material);
  27816. this.add(this.targetLine);
  27817. this.update();
  27818. }
  27819. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  27820. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  27821. DirectionalLightHelper.prototype.dispose = function () {
  27822. this.lightPlane.geometry.dispose();
  27823. this.lightPlane.material.dispose();
  27824. this.targetLine.geometry.dispose();
  27825. this.targetLine.material.dispose();
  27826. };
  27827. DirectionalLightHelper.prototype.update = function () {
  27828. _v1$5.setFromMatrixPosition(this.light.matrixWorld);
  27829. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27830. _v3$1.subVectors(_v2$3, _v1$5);
  27831. this.lightPlane.lookAt(_v2$3);
  27832. if (this.color !== undefined) {
  27833. this.lightPlane.material.color.set(this.color);
  27834. this.targetLine.material.color.set(this.color);
  27835. } else {
  27836. this.lightPlane.material.color.copy(this.light.color);
  27837. this.targetLine.material.color.copy(this.light.color);
  27838. }
  27839. this.targetLine.lookAt(_v2$3);
  27840. this.targetLine.scale.z = _v3$1.length();
  27841. };
  27842. /**
  27843. * @author alteredq / http://alteredqualia.com/
  27844. * @author Mugen87 / https://github.com/Mugen87
  27845. *
  27846. * - shows frustum, line of sight and up of the camera
  27847. * - suitable for fast updates
  27848. * - based on frustum visualization in lightgl.js shadowmap example
  27849. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27850. */
  27851. var _vector$b = new Vector3();
  27852. var _camera = new Camera();
  27853. function CameraHelper(camera) {
  27854. var geometry = new BufferGeometry();
  27855. var material = new LineBasicMaterial({
  27856. color: 0xffffff,
  27857. vertexColors: true,
  27858. toneMapped: false
  27859. });
  27860. var vertices = [];
  27861. var colors = [];
  27862. var pointMap = {}; // colors
  27863. var colorFrustum = new Color(0xffaa00);
  27864. var colorCone = new Color(0xff0000);
  27865. var colorUp = new Color(0x00aaff);
  27866. var colorTarget = new Color(0xffffff);
  27867. var colorCross = new Color(0x333333); // near
  27868. addLine('n1', 'n2', colorFrustum);
  27869. addLine('n2', 'n4', colorFrustum);
  27870. addLine('n4', 'n3', colorFrustum);
  27871. addLine('n3', 'n1', colorFrustum); // far
  27872. addLine('f1', 'f2', colorFrustum);
  27873. addLine('f2', 'f4', colorFrustum);
  27874. addLine('f4', 'f3', colorFrustum);
  27875. addLine('f3', 'f1', colorFrustum); // sides
  27876. addLine('n1', 'f1', colorFrustum);
  27877. addLine('n2', 'f2', colorFrustum);
  27878. addLine('n3', 'f3', colorFrustum);
  27879. addLine('n4', 'f4', colorFrustum); // cone
  27880. addLine('p', 'n1', colorCone);
  27881. addLine('p', 'n2', colorCone);
  27882. addLine('p', 'n3', colorCone);
  27883. addLine('p', 'n4', colorCone); // up
  27884. addLine('u1', 'u2', colorUp);
  27885. addLine('u2', 'u3', colorUp);
  27886. addLine('u3', 'u1', colorUp); // target
  27887. addLine('c', 't', colorTarget);
  27888. addLine('p', 'c', colorCross); // cross
  27889. addLine('cn1', 'cn2', colorCross);
  27890. addLine('cn3', 'cn4', colorCross);
  27891. addLine('cf1', 'cf2', colorCross);
  27892. addLine('cf3', 'cf4', colorCross);
  27893. function addLine(a, b, color) {
  27894. addPoint(a, color);
  27895. addPoint(b, color);
  27896. }
  27897. function addPoint(id, color) {
  27898. vertices.push(0, 0, 0);
  27899. colors.push(color.r, color.g, color.b);
  27900. if (pointMap[id] === undefined) {
  27901. pointMap[id] = [];
  27902. }
  27903. pointMap[id].push(vertices.length / 3 - 1);
  27904. }
  27905. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27906. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27907. LineSegments.call(this, geometry, material);
  27908. this.camera = camera;
  27909. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27910. this.matrix = camera.matrixWorld;
  27911. this.matrixAutoUpdate = false;
  27912. this.pointMap = pointMap;
  27913. this.update();
  27914. }
  27915. CameraHelper.prototype = Object.create(LineSegments.prototype);
  27916. CameraHelper.prototype.constructor = CameraHelper;
  27917. CameraHelper.prototype.update = function () {
  27918. var geometry = this.geometry;
  27919. var pointMap = this.pointMap;
  27920. var w = 1,
  27921. h = 1; // we need just camera projection matrix inverse
  27922. // world matrix must be identity
  27923. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27924. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27925. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27926. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27927. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27928. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27929. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27930. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27931. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27932. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27933. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27934. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27935. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27936. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27937. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27938. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27939. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27940. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27941. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27942. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27943. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27944. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27945. geometry.getAttribute('position').needsUpdate = true;
  27946. };
  27947. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27948. _vector$b.set(x, y, z).unproject(camera);
  27949. var points = pointMap[point];
  27950. if (points !== undefined) {
  27951. var position = geometry.getAttribute('position');
  27952. for (var i = 0, l = points.length; i < l; i++) {
  27953. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  27954. }
  27955. }
  27956. }
  27957. /**
  27958. * @author mrdoob / http://mrdoob.com/
  27959. * @author Mugen87 / http://github.com/Mugen87
  27960. */
  27961. var _box$3 = new Box3();
  27962. function BoxHelper(object, color) {
  27963. this.object = object;
  27964. if (color === undefined) color = 0xffff00;
  27965. var 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]);
  27966. var positions = new Float32Array(8 * 3);
  27967. var geometry = new BufferGeometry();
  27968. geometry.setIndex(new BufferAttribute(indices, 1));
  27969. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27970. LineSegments.call(this, geometry, new LineBasicMaterial({
  27971. color: color,
  27972. toneMapped: false
  27973. }));
  27974. this.matrixAutoUpdate = false;
  27975. this.update();
  27976. }
  27977. BoxHelper.prototype = Object.create(LineSegments.prototype);
  27978. BoxHelper.prototype.constructor = BoxHelper;
  27979. BoxHelper.prototype.update = function (object) {
  27980. if (object !== undefined) {
  27981. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27982. }
  27983. if (this.object !== undefined) {
  27984. _box$3.setFromObject(this.object);
  27985. }
  27986. if (_box$3.isEmpty()) return;
  27987. var min = _box$3.min;
  27988. var max = _box$3.max;
  27989. /*
  27990. 5____4
  27991. 1/___0/|
  27992. | 6__|_7
  27993. 2/___3/
  27994. 0: max.x, max.y, max.z
  27995. 1: min.x, max.y, max.z
  27996. 2: min.x, min.y, max.z
  27997. 3: max.x, min.y, max.z
  27998. 4: max.x, max.y, min.z
  27999. 5: min.x, max.y, min.z
  28000. 6: min.x, min.y, min.z
  28001. 7: max.x, min.y, min.z
  28002. */
  28003. var position = this.geometry.attributes.position;
  28004. var array = position.array;
  28005. array[0] = max.x;
  28006. array[1] = max.y;
  28007. array[2] = max.z;
  28008. array[3] = min.x;
  28009. array[4] = max.y;
  28010. array[5] = max.z;
  28011. array[6] = min.x;
  28012. array[7] = min.y;
  28013. array[8] = max.z;
  28014. array[9] = max.x;
  28015. array[10] = min.y;
  28016. array[11] = max.z;
  28017. array[12] = max.x;
  28018. array[13] = max.y;
  28019. array[14] = min.z;
  28020. array[15] = min.x;
  28021. array[16] = max.y;
  28022. array[17] = min.z;
  28023. array[18] = min.x;
  28024. array[19] = min.y;
  28025. array[20] = min.z;
  28026. array[21] = max.x;
  28027. array[22] = min.y;
  28028. array[23] = min.z;
  28029. position.needsUpdate = true;
  28030. this.geometry.computeBoundingSphere();
  28031. };
  28032. BoxHelper.prototype.setFromObject = function (object) {
  28033. this.object = object;
  28034. this.update();
  28035. return this;
  28036. };
  28037. BoxHelper.prototype.copy = function (source) {
  28038. LineSegments.prototype.copy.call(this, source);
  28039. this.object = source.object;
  28040. return this;
  28041. };
  28042. BoxHelper.prototype.clone = function () {
  28043. return new this.constructor().copy(this);
  28044. };
  28045. /**
  28046. * @author WestLangley / http://github.com/WestLangley
  28047. */
  28048. function Box3Helper(box, color) {
  28049. this.type = 'Box3Helper';
  28050. this.box = box;
  28051. color = color || 0xffff00;
  28052. var 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]);
  28053. var 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];
  28054. var geometry = new BufferGeometry();
  28055. geometry.setIndex(new BufferAttribute(indices, 1));
  28056. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28057. LineSegments.call(this, geometry, new LineBasicMaterial({
  28058. color: color,
  28059. toneMapped: false
  28060. }));
  28061. this.geometry.computeBoundingSphere();
  28062. }
  28063. Box3Helper.prototype = Object.create(LineSegments.prototype);
  28064. Box3Helper.prototype.constructor = Box3Helper;
  28065. Box3Helper.prototype.updateMatrixWorld = function (force) {
  28066. var box = this.box;
  28067. if (box.isEmpty()) return;
  28068. box.getCenter(this.position);
  28069. box.getSize(this.scale);
  28070. this.scale.multiplyScalar(0.5);
  28071. Object3D.prototype.updateMatrixWorld.call(this, force);
  28072. };
  28073. /**
  28074. * @author WestLangley / http://github.com/WestLangley
  28075. */
  28076. function PlaneHelper(plane, size, hex) {
  28077. this.type = 'PlaneHelper';
  28078. this.plane = plane;
  28079. this.size = size === undefined ? 1 : size;
  28080. var color = hex !== undefined ? hex : 0xffff00;
  28081. var 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];
  28082. var geometry = new BufferGeometry();
  28083. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28084. geometry.computeBoundingSphere();
  28085. Line.call(this, geometry, new LineBasicMaterial({
  28086. color: color,
  28087. toneMapped: false
  28088. })); //
  28089. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  28090. var geometry2 = new BufferGeometry();
  28091. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28092. geometry2.computeBoundingSphere();
  28093. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28094. color: color,
  28095. opacity: 0.2,
  28096. transparent: true,
  28097. depthWrite: false,
  28098. toneMapped: false
  28099. })));
  28100. }
  28101. PlaneHelper.prototype = Object.create(Line.prototype);
  28102. PlaneHelper.prototype.constructor = PlaneHelper;
  28103. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  28104. var scale = -this.plane.constant;
  28105. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  28106. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  28107. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28108. this.lookAt(this.plane.normal);
  28109. Object3D.prototype.updateMatrixWorld.call(this, force);
  28110. };
  28111. /**
  28112. * @author WestLangley / http://github.com/WestLangley
  28113. * @author zz85 / http://github.com/zz85
  28114. * @author bhouston / http://clara.io
  28115. *
  28116. * Creates an arrow for visualizing directions
  28117. *
  28118. * Parameters:
  28119. * dir - Vector3
  28120. * origin - Vector3
  28121. * length - Number
  28122. * color - color in hex value
  28123. * headLength - Number
  28124. * headWidth - Number
  28125. */
  28126. var _axis = new Vector3();
  28127. var _lineGeometry, _coneGeometry;
  28128. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  28129. // dir is assumed to be normalized
  28130. Object3D.call(this);
  28131. if (dir === undefined) dir = new Vector3(0, 0, 1);
  28132. if (origin === undefined) origin = new Vector3(0, 0, 0);
  28133. if (length === undefined) length = 1;
  28134. if (color === undefined) color = 0xffff00;
  28135. if (headLength === undefined) headLength = 0.2 * length;
  28136. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28137. if (_lineGeometry === undefined) {
  28138. _lineGeometry = new BufferGeometry();
  28139. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28140. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  28141. _coneGeometry.translate(0, -0.5, 0);
  28142. }
  28143. this.position.copy(origin);
  28144. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28145. color: color,
  28146. toneMapped: false
  28147. }));
  28148. this.line.matrixAutoUpdate = false;
  28149. this.add(this.line);
  28150. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28151. color: color,
  28152. toneMapped: false
  28153. }));
  28154. this.cone.matrixAutoUpdate = false;
  28155. this.add(this.cone);
  28156. this.setDirection(dir);
  28157. this.setLength(length, headLength, headWidth);
  28158. }
  28159. ArrowHelper.prototype = Object.create(Object3D.prototype);
  28160. ArrowHelper.prototype.constructor = ArrowHelper;
  28161. ArrowHelper.prototype.setDirection = function (dir) {
  28162. // dir is assumed to be normalized
  28163. if (dir.y > 0.99999) {
  28164. this.quaternion.set(0, 0, 0, 1);
  28165. } else if (dir.y < -0.99999) {
  28166. this.quaternion.set(1, 0, 0, 0);
  28167. } else {
  28168. _axis.set(dir.z, 0, -dir.x).normalize();
  28169. var radians = Math.acos(dir.y);
  28170. this.quaternion.setFromAxisAngle(_axis, radians);
  28171. }
  28172. };
  28173. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  28174. if (headLength === undefined) headLength = 0.2 * length;
  28175. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28176. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28177. this.line.updateMatrix();
  28178. this.cone.scale.set(headWidth, headLength, headWidth);
  28179. this.cone.position.y = length;
  28180. this.cone.updateMatrix();
  28181. };
  28182. ArrowHelper.prototype.setColor = function (color) {
  28183. this.line.material.color.set(color);
  28184. this.cone.material.color.set(color);
  28185. };
  28186. ArrowHelper.prototype.copy = function (source) {
  28187. Object3D.prototype.copy.call(this, source, false);
  28188. this.line.copy(source.line);
  28189. this.cone.copy(source.cone);
  28190. return this;
  28191. };
  28192. ArrowHelper.prototype.clone = function () {
  28193. return new this.constructor().copy(this);
  28194. };
  28195. /**
  28196. * @author sroucheray / http://sroucheray.org/
  28197. * @author mrdoob / http://mrdoob.com/
  28198. */
  28199. function AxesHelper(size) {
  28200. size = size || 1;
  28201. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28202. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28203. var geometry = new BufferGeometry();
  28204. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28205. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28206. var material = new LineBasicMaterial({
  28207. vertexColors: true,
  28208. toneMapped: false
  28209. });
  28210. LineSegments.call(this, geometry, material);
  28211. }
  28212. AxesHelper.prototype = Object.create(LineSegments.prototype);
  28213. AxesHelper.prototype.constructor = AxesHelper;
  28214. /**
  28215. * @author Emmett Lalish / elalish
  28216. *
  28217. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28218. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28219. * blur to be quickly accessed based on material roughness. It is packed into a
  28220. * special CubeUV format that allows us to perform custom interpolation so that
  28221. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28222. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28223. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28224. * higher roughness levels. In this way we maintain resolution to smoothly
  28225. * interpolate diffuse lighting while limiting sampling computation.
  28226. */
  28227. var LOD_MIN = 4;
  28228. var LOD_MAX = 8;
  28229. var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  28230. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28231. // geometric shadowing function. These sigma values squared must match the
  28232. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28233. var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  28234. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28235. // samples and exit early, but not recompile the shader.
  28236. var MAX_SAMPLES = 20;
  28237. var ENCODINGS = {
  28238. [LinearEncoding]: 0,
  28239. [sRGBEncoding]: 1,
  28240. [RGBEEncoding]: 2,
  28241. [RGBM7Encoding]: 3,
  28242. [RGBM16Encoding]: 4,
  28243. [RGBDEncoding]: 5,
  28244. [GammaEncoding]: 6
  28245. };
  28246. var _flatCamera = new OrthographicCamera();
  28247. var _blurMaterial = _getBlurShader(MAX_SAMPLES);
  28248. var _equirectShader = null;
  28249. var _cubemapShader = null;
  28250. var {
  28251. _lodPlanes,
  28252. _sizeLods,
  28253. _sigmas
  28254. } = _createPlanes();
  28255. var _pingPongRenderTarget = null;
  28256. var _renderer = null;
  28257. var _oldTarget = null; // Golden Ratio
  28258. var PHI = (1 + Math.sqrt(5)) / 2;
  28259. var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  28260. // same axis), used as axis directions evenly spread on a sphere.
  28261. var _axisDirections = [new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(0, PHI, INV_PHI), new Vector3(0, PHI, -INV_PHI), new Vector3(INV_PHI, 0, PHI), new Vector3(-INV_PHI, 0, PHI), new Vector3(PHI, INV_PHI, 0), new Vector3(-PHI, INV_PHI, 0)];
  28262. function PMREMGenerator(renderer) {
  28263. _renderer = renderer;
  28264. _compileMaterial(_blurMaterial);
  28265. }
  28266. PMREMGenerator.prototype = {
  28267. constructor: PMREMGenerator,
  28268. /**
  28269. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28270. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28271. * in radians to be applied to the scene before PMREM generation. Optional near
  28272. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28273. * is placed at the origin).
  28274. */
  28275. fromScene: function (scene, sigma = 0, near = 0.1, far = 100) {
  28276. _oldTarget = _renderer.getRenderTarget();
  28277. var cubeUVRenderTarget = _allocateTargets();
  28278. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  28279. if (sigma > 0) {
  28280. _blur(cubeUVRenderTarget, 0, 0, sigma);
  28281. }
  28282. _applyPMREM(cubeUVRenderTarget);
  28283. _cleanup(cubeUVRenderTarget);
  28284. return cubeUVRenderTarget;
  28285. },
  28286. /**
  28287. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28288. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28289. * as this matches best with the 256 x 256 cubemap output.
  28290. */
  28291. fromEquirectangular: function (equirectangular) {
  28292. equirectangular.magFilter = NearestFilter;
  28293. equirectangular.minFilter = NearestFilter;
  28294. equirectangular.generateMipmaps = false;
  28295. return this.fromCubemap(equirectangular);
  28296. },
  28297. /**
  28298. * Generates a PMREM from an cubemap texture, which can be either LDR
  28299. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28300. * as this matches best with the 256 x 256 cubemap output.
  28301. */
  28302. fromCubemap: function (cubemap) {
  28303. _oldTarget = _renderer.getRenderTarget();
  28304. var cubeUVRenderTarget = _allocateTargets(cubemap);
  28305. _textureToCubeUV(cubemap, cubeUVRenderTarget);
  28306. _applyPMREM(cubeUVRenderTarget);
  28307. _cleanup(cubeUVRenderTarget);
  28308. return cubeUVRenderTarget;
  28309. },
  28310. /**
  28311. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28312. * your texture's network fetch for increased concurrency.
  28313. */
  28314. compileCubemapShader: function () {
  28315. if (_cubemapShader == null) {
  28316. _cubemapShader = _getCubemapShader();
  28317. _compileMaterial(_cubemapShader);
  28318. }
  28319. },
  28320. /**
  28321. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28322. * your texture's network fetch for increased concurrency.
  28323. */
  28324. compileEquirectangularShader: function () {
  28325. if (_equirectShader == null) {
  28326. _equirectShader = _getEquirectShader();
  28327. _compileMaterial(_equirectShader);
  28328. }
  28329. },
  28330. /**
  28331. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28332. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28333. * one of them will cause any others to also become unusable.
  28334. */
  28335. dispose: function () {
  28336. _blurMaterial.dispose();
  28337. if (_cubemapShader != null) _cubemapShader.dispose();
  28338. if (_equirectShader != null) _equirectShader.dispose();
  28339. for (var i = 0; i < _lodPlanes.length; i++) {
  28340. _lodPlanes[i].dispose();
  28341. }
  28342. }
  28343. };
  28344. function _createPlanes() {
  28345. var _lodPlanes = [];
  28346. var _sizeLods = [];
  28347. var _sigmas = [];
  28348. var lod = LOD_MAX;
  28349. for (var i = 0; i < TOTAL_LODS; i++) {
  28350. var sizeLod = Math.pow(2, lod);
  28351. _sizeLods.push(sizeLod);
  28352. var sigma = 1.0 / sizeLod;
  28353. if (i > LOD_MAX - LOD_MIN) {
  28354. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  28355. } else if (i == 0) {
  28356. sigma = 0;
  28357. }
  28358. _sigmas.push(sigma);
  28359. var texelSize = 1.0 / (sizeLod - 1);
  28360. var min = -texelSize / 2;
  28361. var max = 1 + texelSize / 2;
  28362. var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  28363. var cubeFaces = 6;
  28364. var vertices = 6;
  28365. var positionSize = 3;
  28366. var uvSize = 2;
  28367. var faceIndexSize = 1;
  28368. var position = new Float32Array(positionSize * vertices * cubeFaces);
  28369. var uv = new Float32Array(uvSize * vertices * cubeFaces);
  28370. var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  28371. for (var face = 0; face < cubeFaces; face++) {
  28372. var x = face % 3 * 2 / 3 - 1;
  28373. var y = face > 2 ? 0 : -1;
  28374. var 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];
  28375. position.set(coordinates, positionSize * vertices * face);
  28376. uv.set(uv1, uvSize * vertices * face);
  28377. var fill = [face, face, face, face, face, face];
  28378. faceIndex.set(fill, faceIndexSize * vertices * face);
  28379. }
  28380. var planes = new BufferGeometry();
  28381. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  28382. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  28383. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  28384. _lodPlanes.push(planes);
  28385. if (lod > LOD_MIN) {
  28386. lod--;
  28387. }
  28388. }
  28389. return {
  28390. _lodPlanes,
  28391. _sizeLods,
  28392. _sigmas
  28393. };
  28394. }
  28395. function _allocateTargets(equirectangular) {
  28396. var params = {
  28397. magFilter: NearestFilter,
  28398. minFilter: NearestFilter,
  28399. generateMipmaps: false,
  28400. type: equirectangular ? equirectangular.type : UnsignedByteType,
  28401. format: equirectangular ? equirectangular.format : RGBEFormat,
  28402. encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
  28403. depthBuffer: false,
  28404. stencilBuffer: false
  28405. };
  28406. var cubeUVRenderTarget = _createRenderTarget(params);
  28407. cubeUVRenderTarget.depthBuffer = equirectangular ? false : true;
  28408. _pingPongRenderTarget = _createRenderTarget(params);
  28409. return cubeUVRenderTarget;
  28410. }
  28411. function _cleanup(outputTarget) {
  28412. _pingPongRenderTarget.dispose();
  28413. _renderer.setRenderTarget(_oldTarget);
  28414. outputTarget.scissorTest = false; // reset viewport and scissor
  28415. outputTarget.setSize(outputTarget.width, outputTarget.height);
  28416. }
  28417. function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  28418. var fov = 90;
  28419. var aspect = 1;
  28420. var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  28421. var upSign = [1, 1, 1, 1, -1, 1];
  28422. var forwardSign = [1, 1, -1, -1, -1, 1];
  28423. var outputEncoding = _renderer.outputEncoding;
  28424. var toneMapping = _renderer.toneMapping;
  28425. var toneMappingExposure = _renderer.toneMappingExposure;
  28426. var clearColor = _renderer.getClearColor();
  28427. var clearAlpha = _renderer.getClearAlpha();
  28428. _renderer.toneMapping = LinearToneMapping;
  28429. _renderer.toneMappingExposure = 1.0;
  28430. _renderer.outputEncoding = LinearEncoding;
  28431. scene.scale.z *= -1;
  28432. var background = scene.background;
  28433. if (background && background.isColor) {
  28434. background.convertSRGBToLinear(); // Convert linear to RGBE
  28435. var maxComponent = Math.max(background.r, background.g, background.b);
  28436. var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  28437. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  28438. var alpha = (fExp + 128.0) / 255.0;
  28439. _renderer.setClearColor(background, alpha);
  28440. scene.background = null;
  28441. }
  28442. for (var i = 0; i < 6; i++) {
  28443. var col = i % 3;
  28444. if (col == 0) {
  28445. cubeCamera.up.set(0, upSign[i], 0);
  28446. cubeCamera.lookAt(forwardSign[i], 0, 0);
  28447. } else if (col == 1) {
  28448. cubeCamera.up.set(0, 0, upSign[i]);
  28449. cubeCamera.lookAt(0, forwardSign[i], 0);
  28450. } else {
  28451. cubeCamera.up.set(0, upSign[i], 0);
  28452. cubeCamera.lookAt(0, 0, forwardSign[i]);
  28453. }
  28454. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  28455. _renderer.setRenderTarget(cubeUVRenderTarget);
  28456. _renderer.render(scene, cubeCamera);
  28457. }
  28458. _renderer.toneMapping = toneMapping;
  28459. _renderer.toneMappingExposure = toneMappingExposure;
  28460. _renderer.outputEncoding = outputEncoding;
  28461. _renderer.setClearColor(clearColor, clearAlpha);
  28462. scene.scale.z *= -1;
  28463. }
  28464. function _textureToCubeUV(texture, cubeUVRenderTarget) {
  28465. var scene = new Scene();
  28466. if (texture.isCubeTexture) {
  28467. if (_cubemapShader == null) {
  28468. _cubemapShader = _getCubemapShader();
  28469. }
  28470. } else {
  28471. if (_equirectShader == null) {
  28472. _equirectShader = _getEquirectShader();
  28473. }
  28474. }
  28475. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  28476. scene.add(new Mesh(_lodPlanes[0], material));
  28477. var uniforms = material.uniforms;
  28478. uniforms['envMap'].value = texture;
  28479. if (!texture.isCubeTexture) {
  28480. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  28481. }
  28482. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  28483. uniforms['outputEncoding'].value = ENCODINGS[texture.encoding];
  28484. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  28485. _renderer.setRenderTarget(cubeUVRenderTarget);
  28486. _renderer.render(scene, _flatCamera);
  28487. }
  28488. function _compileMaterial(material) {
  28489. var tmpScene = new Scene();
  28490. tmpScene.add(new Mesh(_lodPlanes[0], material));
  28491. _renderer.compile(tmpScene, _flatCamera);
  28492. }
  28493. function _createRenderTarget(params) {
  28494. var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  28495. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  28496. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  28497. cubeUVRenderTarget.scissorTest = true;
  28498. return cubeUVRenderTarget;
  28499. }
  28500. function _setViewport(target, x, y, width, height) {
  28501. target.viewport.set(x, y, width, height);
  28502. target.scissor.set(x, y, width, height);
  28503. }
  28504. function _applyPMREM(cubeUVRenderTarget) {
  28505. var autoClear = _renderer.autoClear;
  28506. _renderer.autoClear = false;
  28507. for (var i = 1; i < TOTAL_LODS; i++) {
  28508. var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  28509. var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  28510. _blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  28511. }
  28512. _renderer.autoClear = autoClear;
  28513. }
  28514. /**
  28515. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28516. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28517. * the blur latitudinally (around the poles), and then longitudinally (towards
  28518. * the poles) to approximate the orthogonally-separable blur. It is least
  28519. * accurate at the poles, but still does a decent job.
  28520. */
  28521. function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  28522. _halfBlur(cubeUVRenderTarget, _pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  28523. _halfBlur(_pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  28524. }
  28525. function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  28526. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  28527. console.error('blur direction must be either latitudinal or longitudinal!');
  28528. } // Number of standard deviations at which to cut off the discrete approximation.
  28529. var STANDARD_DEVIATIONS = 3;
  28530. var blurScene = new Scene();
  28531. blurScene.add(new Mesh(_lodPlanes[lodOut], _blurMaterial));
  28532. var blurUniforms = _blurMaterial.uniforms;
  28533. var pixels = _sizeLods[lodIn] - 1;
  28534. var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  28535. var sigmaPixels = sigmaRadians / radiansPerPixel;
  28536. var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  28537. if (samples > MAX_SAMPLES) {
  28538. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  28539. }
  28540. var weights = [];
  28541. var sum = 0;
  28542. for (var i = 0; i < MAX_SAMPLES; ++i) {
  28543. var x = i / sigmaPixels;
  28544. var weight = Math.exp(-x * x / 2);
  28545. weights.push(weight);
  28546. if (i == 0) {
  28547. sum += weight;
  28548. } else if (i < samples) {
  28549. sum += 2 * weight;
  28550. }
  28551. }
  28552. for (var i = 0; i < weights.length; i++) {
  28553. weights[i] = weights[i] / sum;
  28554. }
  28555. blurUniforms['envMap'].value = targetIn.texture;
  28556. blurUniforms['samples'].value = samples;
  28557. blurUniforms['weights'].value = weights;
  28558. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  28559. if (poleAxis) {
  28560. blurUniforms['poleAxis'].value = poleAxis;
  28561. }
  28562. blurUniforms['dTheta'].value = radiansPerPixel;
  28563. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  28564. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  28565. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  28566. var outputSize = _sizeLods[lodOut];
  28567. var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  28568. var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  28569. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  28570. _renderer.setRenderTarget(targetOut);
  28571. _renderer.render(blurScene, _flatCamera);
  28572. }
  28573. function _getBlurShader(maxSamples) {
  28574. var weights = new Float32Array(maxSamples);
  28575. var poleAxis = new Vector3(0, 1, 0);
  28576. var shaderMaterial = new RawShaderMaterial({
  28577. defines: {
  28578. 'n': maxSamples
  28579. },
  28580. uniforms: {
  28581. 'envMap': {
  28582. value: null
  28583. },
  28584. 'samples': {
  28585. value: 1
  28586. },
  28587. 'weights': {
  28588. value: weights
  28589. },
  28590. 'latitudinal': {
  28591. value: false
  28592. },
  28593. 'dTheta': {
  28594. value: 0
  28595. },
  28596. 'mipInt': {
  28597. value: 0
  28598. },
  28599. 'poleAxis': {
  28600. value: poleAxis
  28601. },
  28602. 'inputEncoding': {
  28603. value: ENCODINGS[LinearEncoding]
  28604. },
  28605. 'outputEncoding': {
  28606. value: ENCODINGS[LinearEncoding]
  28607. }
  28608. },
  28609. vertexShader: _getCommonVertexShader(),
  28610. fragmentShader: `
  28611. precision mediump float;
  28612. precision mediump int;
  28613. varying vec3 vOutputDirection;
  28614. uniform sampler2D envMap;
  28615. uniform int samples;
  28616. uniform float weights[n];
  28617. uniform bool latitudinal;
  28618. uniform float dTheta;
  28619. uniform float mipInt;
  28620. uniform vec3 poleAxis;
  28621. ${_getEncodings()}
  28622. #define ENVMAP_TYPE_CUBE_UV
  28623. #include <cube_uv_reflection_fragment>
  28624. vec3 getSample(float theta, vec3 axis) {
  28625. float cosTheta = cos(theta);
  28626. // Rodrigues' axis-angle rotation
  28627. vec3 sampleDirection = vOutputDirection * cosTheta
  28628. + cross(axis, vOutputDirection) * sin(theta)
  28629. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  28630. return bilinearCubeUV(envMap, sampleDirection, mipInt);
  28631. }
  28632. void main() {
  28633. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  28634. if (all(equal(axis, vec3(0.0))))
  28635. axis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);
  28636. axis = normalize(axis);
  28637. gl_FragColor = vec4(0.0);
  28638. gl_FragColor.rgb += weights[0] * getSample(0.0, axis);
  28639. for (int i = 1; i < n; i++) {
  28640. if (i >= samples)
  28641. break;
  28642. float theta = dTheta * float(i);
  28643. gl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);
  28644. gl_FragColor.rgb += weights[i] * getSample(theta, axis);
  28645. }
  28646. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28647. }
  28648. `,
  28649. blending: NoBlending,
  28650. depthTest: false,
  28651. depthWrite: false
  28652. });
  28653. shaderMaterial.type = 'SphericalGaussianBlur';
  28654. return shaderMaterial;
  28655. }
  28656. function _getEquirectShader() {
  28657. var texelSize = new Vector2(1, 1);
  28658. var shaderMaterial = new RawShaderMaterial({
  28659. uniforms: {
  28660. 'envMap': {
  28661. value: null
  28662. },
  28663. 'texelSize': {
  28664. value: texelSize
  28665. },
  28666. 'inputEncoding': {
  28667. value: ENCODINGS[LinearEncoding]
  28668. },
  28669. 'outputEncoding': {
  28670. value: ENCODINGS[LinearEncoding]
  28671. }
  28672. },
  28673. vertexShader: _getCommonVertexShader(),
  28674. fragmentShader: `
  28675. precision mediump float;
  28676. precision mediump int;
  28677. varying vec3 vOutputDirection;
  28678. uniform sampler2D envMap;
  28679. uniform vec2 texelSize;
  28680. ${_getEncodings()}
  28681. #define RECIPROCAL_PI 0.31830988618
  28682. #define RECIPROCAL_PI2 0.15915494
  28683. void main() {
  28684. gl_FragColor = vec4(0.0);
  28685. vec3 outputDirection = normalize(vOutputDirection);
  28686. vec2 uv;
  28687. uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  28688. uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
  28689. vec2 f = fract(uv / texelSize - 0.5);
  28690. uv -= f * texelSize;
  28691. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28692. uv.x += texelSize.x;
  28693. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28694. uv.y += texelSize.y;
  28695. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28696. uv.x -= texelSize.x;
  28697. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28698. vec3 tm = mix(tl, tr, f.x);
  28699. vec3 bm = mix(bl, br, f.x);
  28700. gl_FragColor.rgb = mix(tm, bm, f.y);
  28701. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28702. }
  28703. `,
  28704. blending: NoBlending,
  28705. depthTest: false,
  28706. depthWrite: false
  28707. });
  28708. shaderMaterial.type = 'EquirectangularToCubeUV';
  28709. return shaderMaterial;
  28710. }
  28711. function _getCubemapShader() {
  28712. var shaderMaterial = new RawShaderMaterial({
  28713. uniforms: {
  28714. 'envMap': {
  28715. value: null
  28716. },
  28717. 'inputEncoding': {
  28718. value: ENCODINGS[LinearEncoding]
  28719. },
  28720. 'outputEncoding': {
  28721. value: ENCODINGS[LinearEncoding]
  28722. }
  28723. },
  28724. vertexShader: _getCommonVertexShader(),
  28725. fragmentShader: `
  28726. precision mediump float;
  28727. precision mediump int;
  28728. varying vec3 vOutputDirection;
  28729. uniform samplerCube envMap;
  28730. ${_getEncodings()}
  28731. void main() {
  28732. gl_FragColor = vec4(0.0);
  28733. gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
  28734. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28735. }
  28736. `,
  28737. blending: NoBlending,
  28738. depthTest: false,
  28739. depthWrite: false
  28740. });
  28741. shaderMaterial.type = 'CubemapToCubeUV';
  28742. return shaderMaterial;
  28743. }
  28744. function _getCommonVertexShader() {
  28745. return `
  28746. precision mediump float;
  28747. precision mediump int;
  28748. attribute vec3 position;
  28749. attribute vec2 uv;
  28750. attribute float faceIndex;
  28751. varying vec3 vOutputDirection;
  28752. vec3 getDirection(vec2 uv, float face) {
  28753. uv = 2.0 * uv - 1.0;
  28754. vec3 direction = vec3(uv, 1.0);
  28755. if (face == 0.0) {
  28756. direction = direction.zyx;
  28757. direction.z *= -1.0;
  28758. } else if (face == 1.0) {
  28759. direction = direction.xzy;
  28760. direction.z *= -1.0;
  28761. } else if (face == 3.0) {
  28762. direction = direction.zyx;
  28763. direction.x *= -1.0;
  28764. } else if (face == 4.0) {
  28765. direction = direction.xzy;
  28766. direction.y *= -1.0;
  28767. } else if (face == 5.0) {
  28768. direction.xz *= -1.0;
  28769. }
  28770. return direction;
  28771. }
  28772. void main() {
  28773. vOutputDirection = getDirection(uv, faceIndex);
  28774. gl_Position = vec4( position, 1.0 );
  28775. }
  28776. `;
  28777. }
  28778. function _getEncodings() {
  28779. return `
  28780. uniform int inputEncoding;
  28781. uniform int outputEncoding;
  28782. #include <encodings_pars_fragment>
  28783. vec4 inputTexelToLinear(vec4 value){
  28784. if(inputEncoding == 0){
  28785. return value;
  28786. }else if(inputEncoding == 1){
  28787. return sRGBToLinear(value);
  28788. }else if(inputEncoding == 2){
  28789. return RGBEToLinear(value);
  28790. }else if(inputEncoding == 3){
  28791. return RGBMToLinear(value, 7.0);
  28792. }else if(inputEncoding == 4){
  28793. return RGBMToLinear(value, 16.0);
  28794. }else if(inputEncoding == 5){
  28795. return RGBDToLinear(value, 256.0);
  28796. }else{
  28797. return GammaToLinear(value, 2.2);
  28798. }
  28799. }
  28800. vec4 linearToOutputTexel(vec4 value){
  28801. if(outputEncoding == 0){
  28802. return value;
  28803. }else if(outputEncoding == 1){
  28804. return LinearTosRGB(value);
  28805. }else if(outputEncoding == 2){
  28806. return LinearToRGBE(value);
  28807. }else if(outputEncoding == 3){
  28808. return LinearToRGBM(value, 7.0);
  28809. }else if(outputEncoding == 4){
  28810. return LinearToRGBM(value, 16.0);
  28811. }else if(outputEncoding == 5){
  28812. return LinearToRGBD(value, 256.0);
  28813. }else{
  28814. return LinearToGamma(value, 2.2);
  28815. }
  28816. }
  28817. vec4 envMapTexelToLinear(vec4 color) {
  28818. return inputTexelToLinear(color);
  28819. }
  28820. `;
  28821. }
  28822. /**
  28823. * @author mrdoob / http://mrdoob.com/
  28824. */
  28825. function Face4(a, b, c, d, normal, color, materialIndex) {
  28826. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  28827. return new Face3(a, b, c, normal, color, materialIndex);
  28828. }
  28829. var LineStrip = 0;
  28830. exports.LineStrip = LineStrip;
  28831. var LinePieces = 1;
  28832. exports.LinePieces = LinePieces;
  28833. var NoColors = 0;
  28834. exports.NoColors = NoColors;
  28835. var FaceColors = 1;
  28836. exports.FaceColors = FaceColors;
  28837. var VertexColors = 2;
  28838. exports.VertexColors = VertexColors;
  28839. function MeshFaceMaterial(materials) {
  28840. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28841. return materials;
  28842. }
  28843. function MultiMaterial(materials) {
  28844. if (materials === undefined) materials = [];
  28845. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28846. materials.isMultiMaterial = true;
  28847. materials.materials = materials;
  28848. materials.clone = function () {
  28849. return materials.slice();
  28850. };
  28851. return materials;
  28852. }
  28853. function PointCloud(geometry, material) {
  28854. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28855. return new Points(geometry, material);
  28856. }
  28857. function Particle(material) {
  28858. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28859. return new Sprite(material);
  28860. }
  28861. function ParticleSystem(geometry, material) {
  28862. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28863. return new Points(geometry, material);
  28864. }
  28865. function PointCloudMaterial(parameters) {
  28866. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28867. return new PointsMaterial(parameters);
  28868. }
  28869. function ParticleBasicMaterial(parameters) {
  28870. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28871. return new PointsMaterial(parameters);
  28872. }
  28873. function ParticleSystemMaterial(parameters) {
  28874. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28875. return new PointsMaterial(parameters);
  28876. }
  28877. function Vertex(x, y, z) {
  28878. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28879. return new Vector3(x, y, z);
  28880. } //
  28881. function DynamicBufferAttribute(array, itemSize) {
  28882. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28883. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28884. }
  28885. function Int8Attribute(array, itemSize) {
  28886. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28887. return new Int8BufferAttribute(array, itemSize);
  28888. }
  28889. function Uint8Attribute(array, itemSize) {
  28890. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28891. return new Uint8BufferAttribute(array, itemSize);
  28892. }
  28893. function Uint8ClampedAttribute(array, itemSize) {
  28894. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28895. return new Uint8ClampedBufferAttribute(array, itemSize);
  28896. }
  28897. function Int16Attribute(array, itemSize) {
  28898. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28899. return new Int16BufferAttribute(array, itemSize);
  28900. }
  28901. function Uint16Attribute(array, itemSize) {
  28902. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28903. return new Uint16BufferAttribute(array, itemSize);
  28904. }
  28905. function Int32Attribute(array, itemSize) {
  28906. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28907. return new Int32BufferAttribute(array, itemSize);
  28908. }
  28909. function Uint32Attribute(array, itemSize) {
  28910. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28911. return new Uint32BufferAttribute(array, itemSize);
  28912. }
  28913. function Float32Attribute(array, itemSize) {
  28914. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28915. return new Float32BufferAttribute(array, itemSize);
  28916. }
  28917. function Float64Attribute(array, itemSize) {
  28918. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28919. return new Float64BufferAttribute(array, itemSize);
  28920. } //
  28921. Curve.create = function (construct, getPoint) {
  28922. console.log('THREE.Curve.create() has been deprecated');
  28923. construct.prototype = Object.create(Curve.prototype);
  28924. construct.prototype.constructor = construct;
  28925. construct.prototype.getPoint = getPoint;
  28926. return construct;
  28927. }; //
  28928. Object.assign(CurvePath.prototype, {
  28929. createPointsGeometry: function (divisions) {
  28930. 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)
  28931. var pts = this.getPoints(divisions);
  28932. return this.createGeometry(pts);
  28933. },
  28934. createSpacedPointsGeometry: function (divisions) {
  28935. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  28936. var pts = this.getSpacedPoints(divisions);
  28937. return this.createGeometry(pts);
  28938. },
  28939. createGeometry: function (points) {
  28940. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  28941. var geometry = new Geometry();
  28942. for (var i = 0, l = points.length; i < l; i++) {
  28943. var point = points[i];
  28944. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  28945. }
  28946. return geometry;
  28947. }
  28948. }); //
  28949. Object.assign(Path.prototype, {
  28950. fromPoints: function (points) {
  28951. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28952. return this.setFromPoints(points);
  28953. }
  28954. }); //
  28955. function ClosedSplineCurve3(points) {
  28956. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28957. CatmullRomCurve3.call(this, points);
  28958. this.type = 'catmullrom';
  28959. this.closed = true;
  28960. }
  28961. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28962. function SplineCurve3(points) {
  28963. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28964. CatmullRomCurve3.call(this, points);
  28965. this.type = 'catmullrom';
  28966. }
  28967. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28968. function Spline(points) {
  28969. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  28970. CatmullRomCurve3.call(this, points);
  28971. this.type = 'catmullrom';
  28972. }
  28973. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  28974. Object.assign(Spline.prototype, {
  28975. initFromArray: function ()
  28976. /* a */
  28977. {
  28978. console.error('THREE.Spline: .initFromArray() has been removed.');
  28979. },
  28980. getControlPointsArray: function ()
  28981. /* optionalTarget */
  28982. {
  28983. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  28984. },
  28985. reparametrizeByArcLength: function ()
  28986. /* samplingCoef */
  28987. {
  28988. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  28989. }
  28990. }); //
  28991. function AxisHelper(size) {
  28992. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28993. return new AxesHelper(size);
  28994. }
  28995. function BoundingBoxHelper(object, color) {
  28996. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28997. return new BoxHelper(object, color);
  28998. }
  28999. function EdgesHelper(object, hex) {
  29000. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29001. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29002. color: hex !== undefined ? hex : 0xffffff
  29003. }));
  29004. }
  29005. GridHelper.prototype.setColors = function () {
  29006. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29007. };
  29008. SkeletonHelper.prototype.update = function () {
  29009. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29010. };
  29011. function WireframeHelper(object, hex) {
  29012. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29013. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29014. color: hex !== undefined ? hex : 0xffffff
  29015. }));
  29016. } //
  29017. Object.assign(Loader.prototype, {
  29018. extractUrlBase: function (url) {
  29019. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29020. return LoaderUtils.extractUrlBase(url);
  29021. }
  29022. });
  29023. Loader.Handlers = {
  29024. add: function ()
  29025. /* regex, loader */
  29026. {
  29027. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29028. },
  29029. get: function ()
  29030. /* file */
  29031. {
  29032. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29033. }
  29034. };
  29035. function XHRLoader(manager) {
  29036. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29037. return new FileLoader(manager);
  29038. }
  29039. function BinaryTextureLoader(manager) {
  29040. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29041. return new DataTextureLoader(manager);
  29042. }
  29043. Object.assign(ObjectLoader.prototype, {
  29044. setTexturePath: function (value) {
  29045. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29046. return this.setResourcePath(value);
  29047. }
  29048. }); //
  29049. Object.assign(Box2.prototype, {
  29050. center: function (optionalTarget) {
  29051. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29052. return this.getCenter(optionalTarget);
  29053. },
  29054. empty: function () {
  29055. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29056. return this.isEmpty();
  29057. },
  29058. isIntersectionBox: function (box) {
  29059. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29060. return this.intersectsBox(box);
  29061. },
  29062. size: function (optionalTarget) {
  29063. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29064. return this.getSize(optionalTarget);
  29065. }
  29066. });
  29067. Object.assign(Box3.prototype, {
  29068. center: function (optionalTarget) {
  29069. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29070. return this.getCenter(optionalTarget);
  29071. },
  29072. empty: function () {
  29073. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29074. return this.isEmpty();
  29075. },
  29076. isIntersectionBox: function (box) {
  29077. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29078. return this.intersectsBox(box);
  29079. },
  29080. isIntersectionSphere: function (sphere) {
  29081. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29082. return this.intersectsSphere(sphere);
  29083. },
  29084. size: function (optionalTarget) {
  29085. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29086. return this.getSize(optionalTarget);
  29087. }
  29088. });
  29089. Frustum.prototype.setFromMatrix = function (m) {
  29090. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  29091. return this.setFromProjectionMatrix(m);
  29092. };
  29093. Line3.prototype.center = function (optionalTarget) {
  29094. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29095. return this.getCenter(optionalTarget);
  29096. };
  29097. Object.assign(MathUtils, {
  29098. random16: function () {
  29099. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29100. return Math.random();
  29101. },
  29102. nearestPowerOfTwo: function (value) {
  29103. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29104. return MathUtils.floorPowerOfTwo(value);
  29105. },
  29106. nextPowerOfTwo: function (value) {
  29107. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29108. return MathUtils.ceilPowerOfTwo(value);
  29109. }
  29110. });
  29111. Object.assign(Matrix3.prototype, {
  29112. flattenToArrayOffset: function (array, offset) {
  29113. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29114. return this.toArray(array, offset);
  29115. },
  29116. multiplyVector3: function (vector) {
  29117. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29118. return vector.applyMatrix3(this);
  29119. },
  29120. multiplyVector3Array: function ()
  29121. /* a */
  29122. {
  29123. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29124. },
  29125. applyToBufferAttribute: function (attribute) {
  29126. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  29127. return attribute.applyMatrix3(this);
  29128. },
  29129. applyToVector3Array: function ()
  29130. /* array, offset, length */
  29131. {
  29132. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29133. }
  29134. });
  29135. Object.assign(Matrix4.prototype, {
  29136. extractPosition: function (m) {
  29137. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29138. return this.copyPosition(m);
  29139. },
  29140. flattenToArrayOffset: function (array, offset) {
  29141. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29142. return this.toArray(array, offset);
  29143. },
  29144. getPosition: function () {
  29145. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29146. return new Vector3().setFromMatrixColumn(this, 3);
  29147. },
  29148. setRotationFromQuaternion: function (q) {
  29149. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29150. return this.makeRotationFromQuaternion(q);
  29151. },
  29152. multiplyToArray: function () {
  29153. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29154. },
  29155. multiplyVector3: function (vector) {
  29156. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29157. return vector.applyMatrix4(this);
  29158. },
  29159. multiplyVector4: function (vector) {
  29160. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29161. return vector.applyMatrix4(this);
  29162. },
  29163. multiplyVector3Array: function ()
  29164. /* a */
  29165. {
  29166. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29167. },
  29168. rotateAxis: function (v) {
  29169. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29170. v.transformDirection(this);
  29171. },
  29172. crossVector: function (vector) {
  29173. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29174. return vector.applyMatrix4(this);
  29175. },
  29176. translate: function () {
  29177. console.error('THREE.Matrix4: .translate() has been removed.');
  29178. },
  29179. rotateX: function () {
  29180. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29181. },
  29182. rotateY: function () {
  29183. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29184. },
  29185. rotateZ: function () {
  29186. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29187. },
  29188. rotateByAxis: function () {
  29189. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29190. },
  29191. applyToBufferAttribute: function (attribute) {
  29192. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  29193. return attribute.applyMatrix4(this);
  29194. },
  29195. applyToVector3Array: function ()
  29196. /* array, offset, length */
  29197. {
  29198. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29199. },
  29200. makeFrustum: function (left, right, bottom, top, near, far) {
  29201. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29202. return this.makePerspective(left, right, top, bottom, near, far);
  29203. }
  29204. });
  29205. Plane.prototype.isIntersectionLine = function (line) {
  29206. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29207. return this.intersectsLine(line);
  29208. };
  29209. Quaternion.prototype.multiplyVector3 = function (vector) {
  29210. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29211. return vector.applyQuaternion(this);
  29212. };
  29213. Object.assign(Ray.prototype, {
  29214. isIntersectionBox: function (box) {
  29215. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29216. return this.intersectsBox(box);
  29217. },
  29218. isIntersectionPlane: function (plane) {
  29219. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29220. return this.intersectsPlane(plane);
  29221. },
  29222. isIntersectionSphere: function (sphere) {
  29223. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29224. return this.intersectsSphere(sphere);
  29225. }
  29226. });
  29227. Object.assign(Triangle.prototype, {
  29228. area: function () {
  29229. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29230. return this.getArea();
  29231. },
  29232. barycoordFromPoint: function (point, target) {
  29233. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29234. return this.getBarycoord(point, target);
  29235. },
  29236. midpoint: function (target) {
  29237. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29238. return this.getMidpoint(target);
  29239. },
  29240. normal: function (target) {
  29241. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29242. return this.getNormal(target);
  29243. },
  29244. plane: function (target) {
  29245. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29246. return this.getPlane(target);
  29247. }
  29248. });
  29249. Object.assign(Triangle, {
  29250. barycoordFromPoint: function (point, a, b, c, target) {
  29251. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29252. return Triangle.getBarycoord(point, a, b, c, target);
  29253. },
  29254. normal: function (a, b, c, target) {
  29255. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29256. return Triangle.getNormal(a, b, c, target);
  29257. }
  29258. });
  29259. Object.assign(Shape.prototype, {
  29260. extractAllPoints: function (divisions) {
  29261. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29262. return this.extractPoints(divisions);
  29263. },
  29264. extrude: function (options) {
  29265. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29266. return new ExtrudeGeometry(this, options);
  29267. },
  29268. makeGeometry: function (options) {
  29269. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29270. return new ShapeGeometry(this, options);
  29271. }
  29272. });
  29273. Object.assign(Vector2.prototype, {
  29274. fromAttribute: function (attribute, index, offset) {
  29275. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29276. return this.fromBufferAttribute(attribute, index, offset);
  29277. },
  29278. distanceToManhattan: function (v) {
  29279. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29280. return this.manhattanDistanceTo(v);
  29281. },
  29282. lengthManhattan: function () {
  29283. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29284. return this.manhattanLength();
  29285. }
  29286. });
  29287. Object.assign(Vector3.prototype, {
  29288. setEulerFromRotationMatrix: function () {
  29289. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29290. },
  29291. setEulerFromQuaternion: function () {
  29292. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29293. },
  29294. getPositionFromMatrix: function (m) {
  29295. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29296. return this.setFromMatrixPosition(m);
  29297. },
  29298. getScaleFromMatrix: function (m) {
  29299. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29300. return this.setFromMatrixScale(m);
  29301. },
  29302. getColumnFromMatrix: function (index, matrix) {
  29303. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29304. return this.setFromMatrixColumn(matrix, index);
  29305. },
  29306. applyProjection: function (m) {
  29307. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29308. return this.applyMatrix4(m);
  29309. },
  29310. fromAttribute: function (attribute, index, offset) {
  29311. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29312. return this.fromBufferAttribute(attribute, index, offset);
  29313. },
  29314. distanceToManhattan: function (v) {
  29315. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29316. return this.manhattanDistanceTo(v);
  29317. },
  29318. lengthManhattan: function () {
  29319. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29320. return this.manhattanLength();
  29321. }
  29322. });
  29323. Object.assign(Vector4.prototype, {
  29324. fromAttribute: function (attribute, index, offset) {
  29325. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29326. return this.fromBufferAttribute(attribute, index, offset);
  29327. },
  29328. lengthManhattan: function () {
  29329. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29330. return this.manhattanLength();
  29331. }
  29332. }); //
  29333. Object.assign(Geometry.prototype, {
  29334. computeTangents: function () {
  29335. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29336. },
  29337. computeLineDistances: function () {
  29338. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29339. },
  29340. applyMatrix: function (matrix) {
  29341. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29342. return this.applyMatrix4(matrix);
  29343. }
  29344. });
  29345. Object.assign(Object3D.prototype, {
  29346. getChildByName: function (name) {
  29347. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29348. return this.getObjectByName(name);
  29349. },
  29350. renderDepth: function () {
  29351. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29352. },
  29353. translate: function (distance, axis) {
  29354. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29355. return this.translateOnAxis(axis, distance);
  29356. },
  29357. getWorldRotation: function () {
  29358. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29359. },
  29360. applyMatrix: function (matrix) {
  29361. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  29362. return this.applyMatrix4(matrix);
  29363. }
  29364. });
  29365. Object.defineProperties(Object3D.prototype, {
  29366. eulerOrder: {
  29367. get: function () {
  29368. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29369. return this.rotation.order;
  29370. },
  29371. set: function (value) {
  29372. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29373. this.rotation.order = value;
  29374. }
  29375. },
  29376. useQuaternion: {
  29377. get: function () {
  29378. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29379. },
  29380. set: function () {
  29381. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29382. }
  29383. }
  29384. });
  29385. Object.assign(Mesh.prototype, {
  29386. setDrawMode: function () {
  29387. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29388. }
  29389. });
  29390. Object.defineProperties(Mesh.prototype, {
  29391. drawMode: {
  29392. get: function () {
  29393. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  29394. return TrianglesDrawMode;
  29395. },
  29396. set: function () {
  29397. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29398. }
  29399. }
  29400. });
  29401. Object.defineProperties(LOD.prototype, {
  29402. objects: {
  29403. get: function () {
  29404. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29405. return this.levels;
  29406. }
  29407. }
  29408. });
  29409. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29410. get: function () {
  29411. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29412. },
  29413. set: function () {
  29414. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29415. }
  29416. });
  29417. SkinnedMesh.prototype.initBones = function () {
  29418. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29419. };
  29420. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29421. get: function () {
  29422. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29423. return this.arcLengthDivisions;
  29424. },
  29425. set: function (value) {
  29426. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29427. this.arcLengthDivisions = value;
  29428. }
  29429. }); //
  29430. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29431. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29432. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29433. this.setFocalLength(focalLength);
  29434. }; //
  29435. Object.defineProperties(Light.prototype, {
  29436. onlyShadow: {
  29437. set: function () {
  29438. console.warn('THREE.Light: .onlyShadow has been removed.');
  29439. }
  29440. },
  29441. shadowCameraFov: {
  29442. set: function (value) {
  29443. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29444. this.shadow.camera.fov = value;
  29445. }
  29446. },
  29447. shadowCameraLeft: {
  29448. set: function (value) {
  29449. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29450. this.shadow.camera.left = value;
  29451. }
  29452. },
  29453. shadowCameraRight: {
  29454. set: function (value) {
  29455. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29456. this.shadow.camera.right = value;
  29457. }
  29458. },
  29459. shadowCameraTop: {
  29460. set: function (value) {
  29461. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29462. this.shadow.camera.top = value;
  29463. }
  29464. },
  29465. shadowCameraBottom: {
  29466. set: function (value) {
  29467. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29468. this.shadow.camera.bottom = value;
  29469. }
  29470. },
  29471. shadowCameraNear: {
  29472. set: function (value) {
  29473. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29474. this.shadow.camera.near = value;
  29475. }
  29476. },
  29477. shadowCameraFar: {
  29478. set: function (value) {
  29479. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29480. this.shadow.camera.far = value;
  29481. }
  29482. },
  29483. shadowCameraVisible: {
  29484. set: function () {
  29485. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29486. }
  29487. },
  29488. shadowBias: {
  29489. set: function (value) {
  29490. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29491. this.shadow.bias = value;
  29492. }
  29493. },
  29494. shadowDarkness: {
  29495. set: function () {
  29496. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29497. }
  29498. },
  29499. shadowMapWidth: {
  29500. set: function (value) {
  29501. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29502. this.shadow.mapSize.width = value;
  29503. }
  29504. },
  29505. shadowMapHeight: {
  29506. set: function (value) {
  29507. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29508. this.shadow.mapSize.height = value;
  29509. }
  29510. }
  29511. }); //
  29512. Object.defineProperties(BufferAttribute.prototype, {
  29513. length: {
  29514. get: function () {
  29515. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29516. return this.array.length;
  29517. }
  29518. },
  29519. dynamic: {
  29520. get: function () {
  29521. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  29522. return this.usage === DynamicDrawUsage;
  29523. },
  29524. set: function ()
  29525. /* value */
  29526. {
  29527. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  29528. this.setUsage(DynamicDrawUsage);
  29529. }
  29530. }
  29531. });
  29532. Object.assign(BufferAttribute.prototype, {
  29533. setDynamic: function (value) {
  29534. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  29535. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  29536. return this;
  29537. },
  29538. copyIndicesArray: function ()
  29539. /* indices */
  29540. {
  29541. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29542. },
  29543. setArray: function ()
  29544. /* array */
  29545. {
  29546. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29547. }
  29548. });
  29549. Object.assign(BufferGeometry.prototype, {
  29550. addIndex: function (index) {
  29551. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29552. this.setIndex(index);
  29553. },
  29554. addAttribute: function (name, attribute) {
  29555. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  29556. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  29557. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  29558. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  29559. }
  29560. if (name === 'index') {
  29561. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  29562. this.setIndex(attribute);
  29563. return this;
  29564. }
  29565. return this.setAttribute(name, attribute);
  29566. },
  29567. addDrawCall: function (start, count, indexOffset) {
  29568. if (indexOffset !== undefined) {
  29569. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29570. }
  29571. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29572. this.addGroup(start, count);
  29573. },
  29574. clearDrawCalls: function () {
  29575. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29576. this.clearGroups();
  29577. },
  29578. computeTangents: function () {
  29579. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29580. },
  29581. computeOffsets: function () {
  29582. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29583. },
  29584. removeAttribute: function (name) {
  29585. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  29586. return this.deleteAttribute(name);
  29587. },
  29588. applyMatrix: function (matrix) {
  29589. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29590. return this.applyMatrix4(matrix);
  29591. }
  29592. });
  29593. Object.defineProperties(BufferGeometry.prototype, {
  29594. drawcalls: {
  29595. get: function () {
  29596. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29597. return this.groups;
  29598. }
  29599. },
  29600. offsets: {
  29601. get: function () {
  29602. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29603. return this.groups;
  29604. }
  29605. }
  29606. });
  29607. Object.defineProperties(Raycaster.prototype, {
  29608. linePrecision: {
  29609. get: function () {
  29610. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  29611. return this.params.Line.threshold;
  29612. },
  29613. set: function (value) {
  29614. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  29615. this.params.Line.threshold = value;
  29616. }
  29617. }
  29618. });
  29619. Object.defineProperties(InterleavedBuffer.prototype, {
  29620. dynamic: {
  29621. get: function () {
  29622. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  29623. return this.usage === DynamicDrawUsage;
  29624. },
  29625. set: function (value) {
  29626. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  29627. this.setUsage(value);
  29628. }
  29629. }
  29630. });
  29631. Object.assign(InterleavedBuffer.prototype, {
  29632. setDynamic: function (value) {
  29633. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  29634. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  29635. return this;
  29636. },
  29637. setArray: function ()
  29638. /* array */
  29639. {
  29640. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29641. }
  29642. }); //
  29643. Object.assign(ExtrudeBufferGeometry.prototype, {
  29644. getArrays: function () {
  29645. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29646. },
  29647. addShapeList: function () {
  29648. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29649. },
  29650. addShape: function () {
  29651. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29652. }
  29653. }); //
  29654. Object.defineProperties(Uniform.prototype, {
  29655. dynamic: {
  29656. set: function () {
  29657. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29658. }
  29659. },
  29660. onUpdate: {
  29661. value: function () {
  29662. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29663. return this;
  29664. }
  29665. }
  29666. }); //
  29667. Object.defineProperties(Material.prototype, {
  29668. wrapAround: {
  29669. get: function () {
  29670. console.warn('THREE.Material: .wrapAround has been removed.');
  29671. },
  29672. set: function () {
  29673. console.warn('THREE.Material: .wrapAround has been removed.');
  29674. }
  29675. },
  29676. overdraw: {
  29677. get: function () {
  29678. console.warn('THREE.Material: .overdraw has been removed.');
  29679. },
  29680. set: function () {
  29681. console.warn('THREE.Material: .overdraw has been removed.');
  29682. }
  29683. },
  29684. wrapRGB: {
  29685. get: function () {
  29686. console.warn('THREE.Material: .wrapRGB has been removed.');
  29687. return new Color();
  29688. }
  29689. },
  29690. shading: {
  29691. get: function () {
  29692. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29693. },
  29694. set: function (value) {
  29695. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29696. this.flatShading = value === FlatShading;
  29697. }
  29698. },
  29699. stencilMask: {
  29700. get: function () {
  29701. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29702. return this.stencilFuncMask;
  29703. },
  29704. set: function (value) {
  29705. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29706. this.stencilFuncMask = value;
  29707. }
  29708. }
  29709. });
  29710. Object.defineProperties(MeshPhongMaterial.prototype, {
  29711. metal: {
  29712. get: function () {
  29713. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29714. return false;
  29715. },
  29716. set: function () {
  29717. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29718. }
  29719. }
  29720. });
  29721. Object.defineProperties(ShaderMaterial.prototype, {
  29722. derivatives: {
  29723. get: function () {
  29724. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29725. return this.extensions.derivatives;
  29726. },
  29727. set: function (value) {
  29728. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29729. this.extensions.derivatives = value;
  29730. }
  29731. }
  29732. }); //
  29733. Object.assign(WebGLRenderer.prototype, {
  29734. clearTarget: function (renderTarget, color, depth, stencil) {
  29735. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29736. this.setRenderTarget(renderTarget);
  29737. this.clear(color, depth, stencil);
  29738. },
  29739. animate: function (callback) {
  29740. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29741. this.setAnimationLoop(callback);
  29742. },
  29743. getCurrentRenderTarget: function () {
  29744. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29745. return this.getRenderTarget();
  29746. },
  29747. getMaxAnisotropy: function () {
  29748. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29749. return this.capabilities.getMaxAnisotropy();
  29750. },
  29751. getPrecision: function () {
  29752. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29753. return this.capabilities.precision;
  29754. },
  29755. resetGLState: function () {
  29756. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  29757. return this.state.reset();
  29758. },
  29759. supportsFloatTextures: function () {
  29760. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  29761. return this.extensions.get('OES_texture_float');
  29762. },
  29763. supportsHalfFloatTextures: function () {
  29764. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  29765. return this.extensions.get('OES_texture_half_float');
  29766. },
  29767. supportsStandardDerivatives: function () {
  29768. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  29769. return this.extensions.get('OES_standard_derivatives');
  29770. },
  29771. supportsCompressedTextureS3TC: function () {
  29772. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  29773. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  29774. },
  29775. supportsCompressedTexturePVRTC: function () {
  29776. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  29777. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  29778. },
  29779. supportsBlendMinMax: function () {
  29780. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  29781. return this.extensions.get('EXT_blend_minmax');
  29782. },
  29783. supportsVertexTextures: function () {
  29784. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  29785. return this.capabilities.vertexTextures;
  29786. },
  29787. supportsInstancedArrays: function () {
  29788. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  29789. return this.extensions.get('ANGLE_instanced_arrays');
  29790. },
  29791. enableScissorTest: function (boolean) {
  29792. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  29793. this.setScissorTest(boolean);
  29794. },
  29795. initMaterial: function () {
  29796. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  29797. },
  29798. addPrePlugin: function () {
  29799. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  29800. },
  29801. addPostPlugin: function () {
  29802. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  29803. },
  29804. updateShadowMap: function () {
  29805. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  29806. },
  29807. setFaceCulling: function () {
  29808. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  29809. },
  29810. allocTextureUnit: function () {
  29811. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  29812. },
  29813. setTexture: function () {
  29814. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  29815. },
  29816. setTexture2D: function () {
  29817. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  29818. },
  29819. setTextureCube: function () {
  29820. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  29821. },
  29822. getActiveMipMapLevel: function () {
  29823. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  29824. return this.getActiveMipmapLevel();
  29825. }
  29826. });
  29827. Object.defineProperties(WebGLRenderer.prototype, {
  29828. shadowMapEnabled: {
  29829. get: function () {
  29830. return this.shadowMap.enabled;
  29831. },
  29832. set: function (value) {
  29833. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  29834. this.shadowMap.enabled = value;
  29835. }
  29836. },
  29837. shadowMapType: {
  29838. get: function () {
  29839. return this.shadowMap.type;
  29840. },
  29841. set: function (value) {
  29842. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  29843. this.shadowMap.type = value;
  29844. }
  29845. },
  29846. shadowMapCullFace: {
  29847. get: function () {
  29848. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29849. return undefined;
  29850. },
  29851. set: function ()
  29852. /* value */
  29853. {
  29854. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29855. }
  29856. },
  29857. context: {
  29858. get: function () {
  29859. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29860. return this.getContext();
  29861. }
  29862. },
  29863. vr: {
  29864. get: function () {
  29865. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  29866. return this.xr;
  29867. }
  29868. },
  29869. gammaInput: {
  29870. get: function () {
  29871. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29872. return false;
  29873. },
  29874. set: function () {
  29875. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29876. }
  29877. },
  29878. gammaOutput: {
  29879. get: function () {
  29880. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29881. return false;
  29882. },
  29883. set: function (value) {
  29884. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29885. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  29886. }
  29887. }
  29888. });
  29889. Object.defineProperties(WebGLShadowMap.prototype, {
  29890. cullFace: {
  29891. get: function () {
  29892. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29893. return undefined;
  29894. },
  29895. set: function ()
  29896. /* cullFace */
  29897. {
  29898. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29899. }
  29900. },
  29901. renderReverseSided: {
  29902. get: function () {
  29903. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29904. return undefined;
  29905. },
  29906. set: function () {
  29907. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29908. }
  29909. },
  29910. renderSingleSided: {
  29911. get: function () {
  29912. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29913. return undefined;
  29914. },
  29915. set: function () {
  29916. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29917. }
  29918. }
  29919. });
  29920. function WebGLRenderTargetCube(width, height, options) {
  29921. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  29922. return new WebGLCubeRenderTarget(width, options);
  29923. } //
  29924. Object.defineProperties(WebGLRenderTarget.prototype, {
  29925. wrapS: {
  29926. get: function () {
  29927. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29928. return this.texture.wrapS;
  29929. },
  29930. set: function (value) {
  29931. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29932. this.texture.wrapS = value;
  29933. }
  29934. },
  29935. wrapT: {
  29936. get: function () {
  29937. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29938. return this.texture.wrapT;
  29939. },
  29940. set: function (value) {
  29941. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29942. this.texture.wrapT = value;
  29943. }
  29944. },
  29945. magFilter: {
  29946. get: function () {
  29947. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29948. return this.texture.magFilter;
  29949. },
  29950. set: function (value) {
  29951. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29952. this.texture.magFilter = value;
  29953. }
  29954. },
  29955. minFilter: {
  29956. get: function () {
  29957. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29958. return this.texture.minFilter;
  29959. },
  29960. set: function (value) {
  29961. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29962. this.texture.minFilter = value;
  29963. }
  29964. },
  29965. anisotropy: {
  29966. get: function () {
  29967. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29968. return this.texture.anisotropy;
  29969. },
  29970. set: function (value) {
  29971. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29972. this.texture.anisotropy = value;
  29973. }
  29974. },
  29975. offset: {
  29976. get: function () {
  29977. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29978. return this.texture.offset;
  29979. },
  29980. set: function (value) {
  29981. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29982. this.texture.offset = value;
  29983. }
  29984. },
  29985. repeat: {
  29986. get: function () {
  29987. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29988. return this.texture.repeat;
  29989. },
  29990. set: function (value) {
  29991. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29992. this.texture.repeat = value;
  29993. }
  29994. },
  29995. format: {
  29996. get: function () {
  29997. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29998. return this.texture.format;
  29999. },
  30000. set: function (value) {
  30001. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30002. this.texture.format = value;
  30003. }
  30004. },
  30005. type: {
  30006. get: function () {
  30007. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30008. return this.texture.type;
  30009. },
  30010. set: function (value) {
  30011. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30012. this.texture.type = value;
  30013. }
  30014. },
  30015. generateMipmaps: {
  30016. get: function () {
  30017. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30018. return this.texture.generateMipmaps;
  30019. },
  30020. set: function (value) {
  30021. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30022. this.texture.generateMipmaps = value;
  30023. }
  30024. }
  30025. }); //
  30026. Object.defineProperties(Audio.prototype, {
  30027. load: {
  30028. value: function (file) {
  30029. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30030. var scope = this;
  30031. var audioLoader = new AudioLoader();
  30032. audioLoader.load(file, function (buffer) {
  30033. scope.setBuffer(buffer);
  30034. });
  30035. return this;
  30036. }
  30037. },
  30038. startTime: {
  30039. set: function () {
  30040. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  30041. }
  30042. }
  30043. });
  30044. AudioAnalyser.prototype.getData = function () {
  30045. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30046. return this.getFrequencyData();
  30047. }; //
  30048. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30049. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30050. return this.update(renderer, scene);
  30051. }; //
  30052. var GeometryUtils = {
  30053. merge: function (geometry1, geometry2, materialIndexOffset) {
  30054. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30055. var matrix;
  30056. if (geometry2.isMesh) {
  30057. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30058. matrix = geometry2.matrix;
  30059. geometry2 = geometry2.geometry;
  30060. }
  30061. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30062. },
  30063. center: function (geometry) {
  30064. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30065. return geometry.center();
  30066. }
  30067. };
  30068. exports.GeometryUtils = GeometryUtils;
  30069. ImageUtils.crossOrigin = undefined;
  30070. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30071. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30072. var loader = new TextureLoader();
  30073. loader.setCrossOrigin(this.crossOrigin);
  30074. var texture = loader.load(url, onLoad, undefined, onError);
  30075. if (mapping) texture.mapping = mapping;
  30076. return texture;
  30077. };
  30078. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30079. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30080. var loader = new CubeTextureLoader();
  30081. loader.setCrossOrigin(this.crossOrigin);
  30082. var texture = loader.load(urls, onLoad, undefined, onError);
  30083. if (mapping) texture.mapping = mapping;
  30084. return texture;
  30085. };
  30086. ImageUtils.loadCompressedTexture = function () {
  30087. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30088. };
  30089. ImageUtils.loadCompressedTextureCube = function () {
  30090. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30091. }; //
  30092. function CanvasRenderer() {
  30093. console.error('THREE.CanvasRenderer has been removed');
  30094. } //
  30095. function JSONLoader() {
  30096. console.error('THREE.JSONLoader has been removed.');
  30097. } //
  30098. var SceneUtils = {
  30099. createMultiMaterialObject: function ()
  30100. /* geometry, materials */
  30101. {
  30102. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30103. },
  30104. detach: function ()
  30105. /* child, parent, scene */
  30106. {
  30107. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30108. },
  30109. attach: function ()
  30110. /* child, scene, parent */
  30111. {
  30112. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30113. }
  30114. }; //
  30115. exports.SceneUtils = SceneUtils;
  30116. function LensFlare() {
  30117. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  30118. }
  30119. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30120. /* eslint-disable no-undef */
  30121. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30122. detail: {
  30123. revision: REVISION
  30124. }
  30125. }));
  30126. /* eslint-enable no-undef */
  30127. }
  30128. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  30129. // shim for using process in browser
  30130. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  30131. // don't break things. But we need to wrap it in a try catch in case it is
  30132. // wrapped in strict mode code which doesn't define any globals. It's inside a
  30133. // function because try/catches deoptimize in certain engines.
  30134. var cachedSetTimeout;
  30135. var cachedClearTimeout;
  30136. function defaultSetTimout() {
  30137. throw new Error('setTimeout has not been defined');
  30138. }
  30139. function defaultClearTimeout() {
  30140. throw new Error('clearTimeout has not been defined');
  30141. }
  30142. (function () {
  30143. try {
  30144. if (typeof setTimeout === 'function') {
  30145. cachedSetTimeout = setTimeout;
  30146. } else {
  30147. cachedSetTimeout = defaultSetTimout;
  30148. }
  30149. } catch (e) {
  30150. cachedSetTimeout = defaultSetTimout;
  30151. }
  30152. try {
  30153. if (typeof clearTimeout === 'function') {
  30154. cachedClearTimeout = clearTimeout;
  30155. } else {
  30156. cachedClearTimeout = defaultClearTimeout;
  30157. }
  30158. } catch (e) {
  30159. cachedClearTimeout = defaultClearTimeout;
  30160. }
  30161. })();
  30162. function runTimeout(fun) {
  30163. if (cachedSetTimeout === setTimeout) {
  30164. //normal enviroments in sane situations
  30165. return setTimeout(fun, 0);
  30166. } // if setTimeout wasn't available but was latter defined
  30167. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  30168. cachedSetTimeout = setTimeout;
  30169. return setTimeout(fun, 0);
  30170. }
  30171. try {
  30172. // when when somebody has screwed with setTimeout but no I.E. maddness
  30173. return cachedSetTimeout(fun, 0);
  30174. } catch (e) {
  30175. try {
  30176. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30177. return cachedSetTimeout.call(null, fun, 0);
  30178. } catch (e) {
  30179. // 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
  30180. return cachedSetTimeout.call(this, fun, 0);
  30181. }
  30182. }
  30183. }
  30184. function runClearTimeout(marker) {
  30185. if (cachedClearTimeout === clearTimeout) {
  30186. //normal enviroments in sane situations
  30187. return clearTimeout(marker);
  30188. } // if clearTimeout wasn't available but was latter defined
  30189. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  30190. cachedClearTimeout = clearTimeout;
  30191. return clearTimeout(marker);
  30192. }
  30193. try {
  30194. // when when somebody has screwed with setTimeout but no I.E. maddness
  30195. return cachedClearTimeout(marker);
  30196. } catch (e) {
  30197. try {
  30198. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30199. return cachedClearTimeout.call(null, marker);
  30200. } catch (e) {
  30201. // 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.
  30202. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  30203. return cachedClearTimeout.call(this, marker);
  30204. }
  30205. }
  30206. }
  30207. var queue = [];
  30208. var draining = false;
  30209. var currentQueue;
  30210. var queueIndex = -1;
  30211. function cleanUpNextTick() {
  30212. if (!draining || !currentQueue) {
  30213. return;
  30214. }
  30215. draining = false;
  30216. if (currentQueue.length) {
  30217. queue = currentQueue.concat(queue);
  30218. } else {
  30219. queueIndex = -1;
  30220. }
  30221. if (queue.length) {
  30222. drainQueue();
  30223. }
  30224. }
  30225. function drainQueue() {
  30226. if (draining) {
  30227. return;
  30228. }
  30229. var timeout = runTimeout(cleanUpNextTick);
  30230. draining = true;
  30231. var len = queue.length;
  30232. while (len) {
  30233. currentQueue = queue;
  30234. queue = [];
  30235. while (++queueIndex < len) {
  30236. if (currentQueue) {
  30237. currentQueue[queueIndex].run();
  30238. }
  30239. }
  30240. queueIndex = -1;
  30241. len = queue.length;
  30242. }
  30243. currentQueue = null;
  30244. draining = false;
  30245. runClearTimeout(timeout);
  30246. }
  30247. process.nextTick = function (fun) {
  30248. var args = new Array(arguments.length - 1);
  30249. if (arguments.length > 1) {
  30250. for (var i = 1; i < arguments.length; i++) {
  30251. args[i - 1] = arguments[i];
  30252. }
  30253. }
  30254. queue.push(new Item(fun, args));
  30255. if (queue.length === 1 && !draining) {
  30256. runTimeout(drainQueue);
  30257. }
  30258. }; // v8 likes predictible objects
  30259. function Item(fun, array) {
  30260. this.fun = fun;
  30261. this.array = array;
  30262. }
  30263. Item.prototype.run = function () {
  30264. this.fun.apply(null, this.array);
  30265. };
  30266. process.title = 'browser';
  30267. process.env = {};
  30268. process.argv = [];
  30269. process.version = ''; // empty string to avoid regexp issues
  30270. process.versions = {};
  30271. function noop() {}
  30272. process.on = noop;
  30273. process.addListener = noop;
  30274. process.once = noop;
  30275. process.off = noop;
  30276. process.removeListener = noop;
  30277. process.removeAllListeners = noop;
  30278. process.emit = noop;
  30279. process.prependListener = noop;
  30280. process.prependOnceListener = noop;
  30281. process.listeners = function (name) {
  30282. return [];
  30283. };
  30284. process.binding = function (name) {
  30285. throw new Error('process.binding is not supported');
  30286. };
  30287. process.cwd = function () {
  30288. return '/';
  30289. };
  30290. process.chdir = function (dir) {
  30291. throw new Error('process.chdir is not supported');
  30292. };
  30293. process.umask = function () {
  30294. return 0;
  30295. };
  30296. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  30297. var process = require("process");
  30298. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  30299. // backported and transplited with Babel, with backwards-compat fixes
  30300. // Copyright Joyent, Inc. and other Node contributors.
  30301. //
  30302. // Permission is hereby granted, free of charge, to any person obtaining a
  30303. // copy of this software and associated documentation files (the
  30304. // "Software"), to deal in the Software without restriction, including
  30305. // without limitation the rights to use, copy, modify, merge, publish,
  30306. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30307. // persons to whom the Software is furnished to do so, subject to the
  30308. // following conditions:
  30309. //
  30310. // The above copyright notice and this permission notice shall be included
  30311. // in all copies or substantial portions of the Software.
  30312. //
  30313. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30314. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30315. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30316. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30317. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30318. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30319. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30320. // resolves . and .. elements in a path array with directory names there
  30321. // must be no slashes, empty elements, or device names (c:\) in the array
  30322. // (so also no leading and trailing slashes - it does not distinguish
  30323. // relative and absolute paths)
  30324. function normalizeArray(parts, allowAboveRoot) {
  30325. // if the path tries to go above the root, `up` ends up > 0
  30326. var up = 0;
  30327. for (var i = parts.length - 1; i >= 0; i--) {
  30328. var last = parts[i];
  30329. if (last === '.') {
  30330. parts.splice(i, 1);
  30331. } else if (last === '..') {
  30332. parts.splice(i, 1);
  30333. up++;
  30334. } else if (up) {
  30335. parts.splice(i, 1);
  30336. up--;
  30337. }
  30338. }
  30339. // if the path is allowed to go above the root, restore leading ..s
  30340. if (allowAboveRoot) {
  30341. for (; up--; up) {
  30342. parts.unshift('..');
  30343. }
  30344. }
  30345. return parts;
  30346. }
  30347. // path.resolve([from ...], to)
  30348. // posix version
  30349. exports.resolve = function() {
  30350. var resolvedPath = '',
  30351. resolvedAbsolute = false;
  30352. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  30353. var path = (i >= 0) ? arguments[i] : process.cwd();
  30354. // Skip empty and invalid entries
  30355. if (typeof path !== 'string') {
  30356. throw new TypeError('Arguments to path.resolve must be strings');
  30357. } else if (!path) {
  30358. continue;
  30359. }
  30360. resolvedPath = path + '/' + resolvedPath;
  30361. resolvedAbsolute = path.charAt(0) === '/';
  30362. }
  30363. // At this point the path should be resolved to a full absolute path, but
  30364. // handle relative paths to be safe (might happen when process.cwd() fails)
  30365. // Normalize the path
  30366. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  30367. return !!p;
  30368. }), !resolvedAbsolute).join('/');
  30369. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  30370. };
  30371. // path.normalize(path)
  30372. // posix version
  30373. exports.normalize = function(path) {
  30374. var isAbsolute = exports.isAbsolute(path),
  30375. trailingSlash = substr(path, -1) === '/';
  30376. // Normalize the path
  30377. path = normalizeArray(filter(path.split('/'), function(p) {
  30378. return !!p;
  30379. }), !isAbsolute).join('/');
  30380. if (!path && !isAbsolute) {
  30381. path = '.';
  30382. }
  30383. if (path && trailingSlash) {
  30384. path += '/';
  30385. }
  30386. return (isAbsolute ? '/' : '') + path;
  30387. };
  30388. // posix version
  30389. exports.isAbsolute = function(path) {
  30390. return path.charAt(0) === '/';
  30391. };
  30392. // posix version
  30393. exports.join = function() {
  30394. var paths = Array.prototype.slice.call(arguments, 0);
  30395. return exports.normalize(filter(paths, function(p, index) {
  30396. if (typeof p !== 'string') {
  30397. throw new TypeError('Arguments to path.join must be strings');
  30398. }
  30399. return p;
  30400. }).join('/'));
  30401. };
  30402. // path.relative(from, to)
  30403. // posix version
  30404. exports.relative = function(from, to) {
  30405. from = exports.resolve(from).substr(1);
  30406. to = exports.resolve(to).substr(1);
  30407. function trim(arr) {
  30408. var start = 0;
  30409. for (; start < arr.length; start++) {
  30410. if (arr[start] !== '') break;
  30411. }
  30412. var end = arr.length - 1;
  30413. for (; end >= 0; end--) {
  30414. if (arr[end] !== '') break;
  30415. }
  30416. if (start > end) return [];
  30417. return arr.slice(start, end - start + 1);
  30418. }
  30419. var fromParts = trim(from.split('/'));
  30420. var toParts = trim(to.split('/'));
  30421. var length = Math.min(fromParts.length, toParts.length);
  30422. var samePartsLength = length;
  30423. for (var i = 0; i < length; i++) {
  30424. if (fromParts[i] !== toParts[i]) {
  30425. samePartsLength = i;
  30426. break;
  30427. }
  30428. }
  30429. var outputParts = [];
  30430. for (var i = samePartsLength; i < fromParts.length; i++) {
  30431. outputParts.push('..');
  30432. }
  30433. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  30434. return outputParts.join('/');
  30435. };
  30436. exports.sep = '/';
  30437. exports.delimiter = ':';
  30438. exports.dirname = function (path) {
  30439. if (typeof path !== 'string') path = path + '';
  30440. if (path.length === 0) return '.';
  30441. var code = path.charCodeAt(0);
  30442. var hasRoot = code === 47 /*/*/;
  30443. var end = -1;
  30444. var matchedSlash = true;
  30445. for (var i = path.length - 1; i >= 1; --i) {
  30446. code = path.charCodeAt(i);
  30447. if (code === 47 /*/*/) {
  30448. if (!matchedSlash) {
  30449. end = i;
  30450. break;
  30451. }
  30452. } else {
  30453. // We saw the first non-path separator
  30454. matchedSlash = false;
  30455. }
  30456. }
  30457. if (end === -1) return hasRoot ? '/' : '.';
  30458. if (hasRoot && end === 1) {
  30459. // return '//';
  30460. // Backwards-compat fix:
  30461. return '/';
  30462. }
  30463. return path.slice(0, end);
  30464. };
  30465. function basename(path) {
  30466. if (typeof path !== 'string') path = path + '';
  30467. var start = 0;
  30468. var end = -1;
  30469. var matchedSlash = true;
  30470. var i;
  30471. for (i = path.length - 1; i >= 0; --i) {
  30472. if (path.charCodeAt(i) === 47 /*/*/) {
  30473. // If we reached a path separator that was not part of a set of path
  30474. // separators at the end of the string, stop now
  30475. if (!matchedSlash) {
  30476. start = i + 1;
  30477. break;
  30478. }
  30479. } else if (end === -1) {
  30480. // We saw the first non-path separator, mark this as the end of our
  30481. // path component
  30482. matchedSlash = false;
  30483. end = i + 1;
  30484. }
  30485. }
  30486. if (end === -1) return '';
  30487. return path.slice(start, end);
  30488. }
  30489. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  30490. // in new Node.js versions, so only basename() above is backported here
  30491. exports.basename = function (path, ext) {
  30492. var f = basename(path);
  30493. if (ext && f.substr(-1 * ext.length) === ext) {
  30494. f = f.substr(0, f.length - ext.length);
  30495. }
  30496. return f;
  30497. };
  30498. exports.extname = function (path) {
  30499. if (typeof path !== 'string') path = path + '';
  30500. var startDot = -1;
  30501. var startPart = 0;
  30502. var end = -1;
  30503. var matchedSlash = true;
  30504. // Track the state of characters (if any) we see before our first dot and
  30505. // after any path separator we find
  30506. var preDotState = 0;
  30507. for (var i = path.length - 1; i >= 0; --i) {
  30508. var code = path.charCodeAt(i);
  30509. if (code === 47 /*/*/) {
  30510. // If we reached a path separator that was not part of a set of path
  30511. // separators at the end of the string, stop now
  30512. if (!matchedSlash) {
  30513. startPart = i + 1;
  30514. break;
  30515. }
  30516. continue;
  30517. }
  30518. if (end === -1) {
  30519. // We saw the first non-path separator, mark this as the end of our
  30520. // extension
  30521. matchedSlash = false;
  30522. end = i + 1;
  30523. }
  30524. if (code === 46 /*.*/) {
  30525. // If this is our first dot, mark it as the start of our extension
  30526. if (startDot === -1)
  30527. startDot = i;
  30528. else if (preDotState !== 1)
  30529. preDotState = 1;
  30530. } else if (startDot !== -1) {
  30531. // We saw a non-dot and non-path separator before our dot, so we should
  30532. // have a good chance at having a non-empty extension
  30533. preDotState = -1;
  30534. }
  30535. }
  30536. if (startDot === -1 || end === -1 ||
  30537. // We saw a non-dot character immediately before the dot
  30538. preDotState === 0 ||
  30539. // The (right-most) trimmed path component is exactly '..'
  30540. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  30541. return '';
  30542. }
  30543. return path.slice(startDot, end);
  30544. };
  30545. function filter (xs, f) {
  30546. if (xs.filter) return xs.filter(f);
  30547. var res = [];
  30548. for (var i = 0; i < xs.length; i++) {
  30549. if (f(xs[i], i, xs)) res.push(xs[i]);
  30550. }
  30551. return res;
  30552. }
  30553. // String.prototype.substr - negative index don't work in IE8
  30554. var substr = 'ab'.substr(-1) === 'b'
  30555. ? function (str, start, len) { return str.substr(start, len) }
  30556. : function (str, start, len) {
  30557. if (start < 0) start = str.length + start;
  30558. return str.substr(start, len);
  30559. }
  30560. ;
  30561. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  30562. "use strict";
  30563. Object.defineProperty(exports, "__esModule", {
  30564. value: true
  30565. });
  30566. exports.LRUCache = void 0;
  30567. // Fires at the end of the frame and before the next one
  30568. function enqueueMicrotask(callback) {
  30569. Promise.resolve().then(callback);
  30570. }
  30571. class LRUCache {
  30572. constructor() {
  30573. // options
  30574. this.maxSize = 800;
  30575. this.minSize = 600;
  30576. this.unloadPercent = 0.05;
  30577. this.usedSet = new Set();
  30578. this.itemSet = new Set();
  30579. this.itemList = [];
  30580. this.callbacks = new Map();
  30581. this.unloadPriorityCallback = null;
  30582. } // Returns whether or not the cache has reached the maximum size
  30583. isFull() {
  30584. return this.itemSet.size >= this.maxSize;
  30585. }
  30586. add(item, removeCb) {
  30587. const itemSet = this.itemSet;
  30588. if (itemSet.has(item)) {
  30589. return false;
  30590. }
  30591. if (this.isFull()) {
  30592. return false;
  30593. }
  30594. const usedSet = this.usedSet;
  30595. const itemList = this.itemList;
  30596. const callbacks = this.callbacks;
  30597. itemList.push(item);
  30598. usedSet.add(item);
  30599. itemSet.add(item);
  30600. callbacks.set(item, removeCb);
  30601. return true;
  30602. }
  30603. remove(item) {
  30604. const usedSet = this.usedSet;
  30605. const itemSet = this.itemSet;
  30606. const itemList = this.itemList;
  30607. const callbacks = this.callbacks;
  30608. if (itemSet.has(item)) {
  30609. callbacks.get(item)(item);
  30610. const index = itemList.indexOf(item);
  30611. itemList.splice(index, 1);
  30612. usedSet.delete(item);
  30613. itemSet.delete(item);
  30614. callbacks.delete(item);
  30615. return true;
  30616. }
  30617. return false;
  30618. }
  30619. markUsed(item) {
  30620. const itemSet = this.itemSet;
  30621. const usedSet = this.usedSet;
  30622. if (itemSet.has(item) && !usedSet.has(item)) {
  30623. const itemList = this.itemList;
  30624. const index = itemList.indexOf(item);
  30625. itemList.splice(index, 1);
  30626. itemList.push(item);
  30627. usedSet.add(item);
  30628. }
  30629. }
  30630. markAllUnused() {
  30631. this.usedSet.clear();
  30632. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  30633. // Maybe call it "cleanup" or "unloadToMinSize"
  30634. unloadUnusedContent() {
  30635. const unloadPercent = this.unloadPercent;
  30636. const targetSize = this.minSize;
  30637. const itemList = this.itemList;
  30638. const itemSet = this.itemSet;
  30639. const usedSet = this.usedSet;
  30640. const callbacks = this.callbacks;
  30641. const unused = itemList.length - usedSet.size;
  30642. const excess = itemList.length - targetSize;
  30643. const unloadPriorityCallback = this.unloadPriorityCallback;
  30644. if (excess > 0 && unused > 0) {
  30645. if (unloadPriorityCallback) {
  30646. // used items should be at the end of the array
  30647. itemList.sort((a, b) => {
  30648. const usedA = usedSet.has(a);
  30649. const usedB = usedSet.has(b);
  30650. if (usedA && usedB) {
  30651. // If they're both used then don't bother moving them
  30652. return 0;
  30653. } else if (!usedA && !usedB) {
  30654. // Use the sort function otherwise
  30655. // higher priority should be further to the left
  30656. return unloadPriorityCallback(b) - unloadPriorityCallback(a);
  30657. } else {
  30658. // If one is used and the other is not move the used one towards the end of the array
  30659. return usedA ? 1 : -1;
  30660. }
  30661. });
  30662. } // address corner cases where the minSize might be zero or smaller than maxSize - minSize,
  30663. // which would result in a very small or no items being unloaded.
  30664. const unusedExcess = Math.min(excess, unused);
  30665. const maxUnload = Math.max(targetSize * unloadPercent, unusedExcess * unloadPercent);
  30666. let nodesToUnload = Math.min(maxUnload, unused);
  30667. nodesToUnload = Math.ceil(nodesToUnload);
  30668. const removedItems = itemList.splice(0, nodesToUnload);
  30669. for (let i = 0, l = removedItems.length; i < l; i++) {
  30670. const item = removedItems[i];
  30671. callbacks.get(item)(item);
  30672. itemSet.delete(item);
  30673. callbacks.delete(item);
  30674. }
  30675. }
  30676. }
  30677. scheduleUnload(markAllUnused = true) {
  30678. if (!this.scheduled) {
  30679. this.scheduled = true;
  30680. enqueueMicrotask(() => {
  30681. this.scheduled = false;
  30682. this.unloadUnusedContent();
  30683. if (markAllUnused) {
  30684. this.markAllUnused();
  30685. }
  30686. });
  30687. }
  30688. }
  30689. }
  30690. exports.LRUCache = LRUCache;
  30691. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  30692. "use strict";
  30693. Object.defineProperty(exports, "__esModule", {
  30694. value: true
  30695. });
  30696. exports.PriorityQueue = void 0;
  30697. // Fires at the end of the frame and before the next one
  30698. function enqueueMicrotask(callback) {
  30699. Promise.resolve().then(callback);
  30700. }
  30701. class PriorityQueue {
  30702. constructor() {
  30703. // options
  30704. this.maxJobs = 6;
  30705. this.items = [];
  30706. this.callbacks = new Map();
  30707. this.currJobs = 0;
  30708. this.scheduled = false;
  30709. this.autoUpdate = true;
  30710. this.priorityCallback = () => {
  30711. throw new Error('PriorityQueue: PriorityCallback function not defined.');
  30712. };
  30713. }
  30714. sort() {
  30715. const priorityCallback = this.priorityCallback;
  30716. const items = this.items;
  30717. items.sort((a, b) => {
  30718. return priorityCallback(a) - priorityCallback(b);
  30719. });
  30720. }
  30721. add(item, callback) {
  30722. return new Promise((resolve, reject) => {
  30723. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  30724. const items = this.items;
  30725. const callbacks = this.callbacks;
  30726. items.push(item);
  30727. callbacks.set(item, prCallback);
  30728. if (this.autoUpdate) {
  30729. this.scheduleJobRun();
  30730. }
  30731. });
  30732. }
  30733. remove(item) {
  30734. const items = this.items;
  30735. const callbacks = this.callbacks;
  30736. const index = items.indexOf(item);
  30737. if (index !== -1) {
  30738. items.splice(index, 1);
  30739. callbacks.delete(item);
  30740. }
  30741. }
  30742. tryRunJobs() {
  30743. this.sort();
  30744. const items = this.items;
  30745. const callbacks = this.callbacks;
  30746. const maxJobs = this.maxJobs;
  30747. let currJobs = this.currJobs;
  30748. while (maxJobs > currJobs && items.length > 0) {
  30749. currJobs++;
  30750. const item = items.pop();
  30751. const callback = callbacks.get(item);
  30752. callbacks.delete(item);
  30753. callback(item).then(() => {
  30754. this.currJobs--;
  30755. if (this.autoUpdate) {
  30756. this.scheduleJobRun();
  30757. }
  30758. }).catch(() => {
  30759. this.currJobs--;
  30760. if (this.autoUpdate) {
  30761. this.scheduleJobRun();
  30762. }
  30763. });
  30764. }
  30765. this.currJobs = currJobs;
  30766. }
  30767. scheduleJobRun() {
  30768. if (!this.scheduled) {
  30769. enqueueMicrotask(() => {
  30770. this.tryRunJobs();
  30771. this.scheduled = false;
  30772. });
  30773. this.scheduled = true;
  30774. }
  30775. }
  30776. }
  30777. exports.PriorityQueue = PriorityQueue;
  30778. },{}],"../src/base/constants.js":[function(require,module,exports) {
  30779. "use strict";
  30780. Object.defineProperty(exports, "__esModule", {
  30781. value: true
  30782. });
  30783. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  30784. const UNLOADED = 0;
  30785. exports.UNLOADED = UNLOADED;
  30786. const LOADING = 1;
  30787. exports.LOADING = LOADING;
  30788. const PARSING = 2;
  30789. exports.PARSING = PARSING;
  30790. const LOADED = 3;
  30791. exports.LOADED = LOADED;
  30792. const FAILED = 4;
  30793. exports.FAILED = FAILED;
  30794. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  30795. "use strict";
  30796. Object.defineProperty(exports, "__esModule", {
  30797. value: true
  30798. });
  30799. exports.traverseSet = traverseSet;
  30800. exports.determineFrustumSet = determineFrustumSet;
  30801. exports.markUsedSetLeaves = markUsedSetLeaves;
  30802. exports.skipTraversal = skipTraversal;
  30803. exports.toggleTiles = toggleTiles;
  30804. var _constants = require("./constants.js");
  30805. // Checks whether this tile was last used on the given frame.
  30806. function isUsedThisFrame(tile, frameCount) {
  30807. return tile.__lastFrameVisited === frameCount && tile.__used;
  30808. } // Resets the frame frame information for the given tile
  30809. function resetFrameState(tile, frameCount) {
  30810. if (tile.__lastFrameVisited !== frameCount) {
  30811. tile.__lastFrameVisited = frameCount;
  30812. tile.__used = false;
  30813. tile.__inFrustum = false;
  30814. tile.__isLeaf = false;
  30815. tile.__visible = false;
  30816. tile.__active = false;
  30817. tile.__error = 0;
  30818. tile.__childrenWereVisible = false;
  30819. tile.__allChildrenLoaded = false;
  30820. }
  30821. } // Recursively mark tiles used down to the next tile with content
  30822. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  30823. resetFrameState(tile, frameCount);
  30824. tile.__used = true;
  30825. lruCache.markUsed(tile);
  30826. if (tile.__contentEmpty) {
  30827. const children = tile.children;
  30828. for (let i = 0, l = children.length; i < l; i++) {
  30829. recursivelyMarkUsed(children[i], frameCount, lruCache);
  30830. }
  30831. }
  30832. } // Helper function for recursively traversing a tileset. If `beforeCb` returns `true` then the
  30833. // traversal will end early.
  30834. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  30835. if (beforeCb && beforeCb(tile, parent, depth)) {
  30836. if (afterCb) {
  30837. afterCb(tile, parent, depth);
  30838. }
  30839. return;
  30840. }
  30841. const children = tile.children;
  30842. for (let i = 0, l = children.length; i < l; i++) {
  30843. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  30844. }
  30845. if (afterCb) {
  30846. afterCb(tile, parent, depth);
  30847. }
  30848. } // Determine which tiles are within the camera frustum.
  30849. // TODO: this is marking items as used in the lrucache, which means some data is
  30850. // being kept around that isn't being used -- is that okay?
  30851. function determineFrustumSet(tile, renderer) {
  30852. const stats = renderer.stats;
  30853. const frameCount = renderer.frameCount;
  30854. const errorTarget = renderer.errorTarget;
  30855. const maxDepth = renderer.maxDepth;
  30856. const loadSiblings = renderer.loadSiblings;
  30857. const lruCache = renderer.lruCache;
  30858. resetFrameState(tile, frameCount); // Early out if this tile is not within view.
  30859. const inFrustum = renderer.tileInView(tile);
  30860. if (inFrustum === false) {
  30861. return false;
  30862. }
  30863. tile.__used = true;
  30864. lruCache.markUsed(tile);
  30865. tile.__inFrustum = true;
  30866. stats.inFrustum++; // Early out if this tile has less error than we're targeting.
  30867. if (!tile.__contentEmpty) {
  30868. const error = renderer.calculateError(tile);
  30869. tile.__error = error;
  30870. if (error <= errorTarget) {
  30871. return true;
  30872. }
  30873. } // Early out if we've reached the maximum allowed depth.
  30874. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  30875. return true;
  30876. } // Traverse children and see if any children are in view.
  30877. let anyChildrenUsed = false;
  30878. const children = tile.children;
  30879. for (let i = 0, l = children.length; i < l; i++) {
  30880. const c = children[i];
  30881. const r = determineFrustumSet(c, renderer);
  30882. anyChildrenUsed = anyChildrenUsed || r;
  30883. } // If there are children within view and we are loading siblings then mark
  30884. // all sibling tiles as used, as well.
  30885. if (anyChildrenUsed && loadSiblings) {
  30886. for (let i = 0, l = children.length; i < l; i++) {
  30887. const c = children[i];
  30888. recursivelyMarkUsed(c, frameCount, lruCache);
  30889. }
  30890. }
  30891. return true;
  30892. } // Traverse and mark the tiles that are at the leaf nodes of the "used" tree.
  30893. function markUsedSetLeaves(tile, renderer) {
  30894. const stats = renderer.stats;
  30895. const frameCount = renderer.frameCount;
  30896. if (!isUsedThisFrame(tile, frameCount)) {
  30897. return;
  30898. }
  30899. stats.used++; // This tile is a leaf if none of the children had been used.
  30900. const children = tile.children;
  30901. let anyChildrenUsed = false;
  30902. for (let i = 0, l = children.length; i < l; i++) {
  30903. const c = children[i];
  30904. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  30905. }
  30906. if (!anyChildrenUsed) {
  30907. // TODO: This isn't necessarily right because it's possible that a parent tile is considered in the
  30908. // frustum while the child tiles are not, making them unused. If all children have loaded and were properly
  30909. // considered to be in the used set then we shouldn't set ourselves to a leaf here.
  30910. tile.__isLeaf = true;
  30911. } else {
  30912. let childrenWereVisible = false;
  30913. let allChildrenLoaded = true;
  30914. for (let i = 0, l = children.length; i < l; i++) {
  30915. const c = children[i];
  30916. markUsedSetLeaves(c, renderer);
  30917. childrenWereVisible = childrenWereVisible || c.__wasSetVisible || c.__childrenWereVisible;
  30918. if (isUsedThisFrame(c, frameCount)) {
  30919. const childLoaded = !c.__contentEmpty && c.__loadingState === _constants.LOADED || c.__allChildrenLoaded;
  30920. allChildrenLoaded = allChildrenLoaded && childLoaded;
  30921. }
  30922. }
  30923. tile.__childrenWereVisible = childrenWereVisible;
  30924. tile.__allChildrenLoaded = allChildrenLoaded;
  30925. }
  30926. } // Skip past tiles we consider unrenderable because they are outside the error threshold.
  30927. function skipTraversal(tile, renderer) {
  30928. const stats = renderer.stats;
  30929. const frameCount = renderer.frameCount;
  30930. if (!isUsedThisFrame(tile, frameCount)) {
  30931. return;
  30932. }
  30933. const parent = tile.parent;
  30934. const parentDepthToParent = parent ? parent.__depthFromRenderedParent : -1;
  30935. tile.__depthFromRenderedParent = parentDepthToParent; // Request the tile contents or mark it as visible if we've found a leaf.
  30936. const lruCache = renderer.lruCache;
  30937. if (tile.__isLeaf) {
  30938. tile.__depthFromRenderedParent++;
  30939. if (tile.__loadingState === _constants.LOADED) {
  30940. if (tile.__inFrustum) {
  30941. tile.__visible = true;
  30942. stats.visible++;
  30943. }
  30944. tile.__active = true;
  30945. stats.active++;
  30946. } else if (!lruCache.isFull()) {
  30947. renderer.requestTileContents(tile);
  30948. }
  30949. return;
  30950. }
  30951. const errorRequirement = (renderer.errorTarget + 1) * renderer.errorThreshold;
  30952. const meetsSSE = tile.__error <= errorRequirement;
  30953. const hasContent = !tile.__contentEmpty;
  30954. const loadedContent = tile.__loadingState === _constants.LOADED && !tile.__contentEmpty;
  30955. const childrenWereVisible = tile.__childrenWereVisible;
  30956. const children = tile.children;
  30957. let allChildrenHaveContent = tile.__allChildrenLoaded; // Increment the relative depth of the node to the nearest rendered parent if it has content
  30958. // and is being rendered.
  30959. if (meetsSSE && hasContent) {
  30960. tile.__depthFromRenderedParent++;
  30961. } // If we've met the SSE requirements and we can load content then fire a fetch.
  30962. if (meetsSSE && !loadedContent && !lruCache.isFull() && hasContent) {
  30963. renderer.requestTileContents(tile);
  30964. } // Only mark this tile as visible if it meets the screen space error requirements, has loaded content, not
  30965. // all children have loaded yet, and if no children were visible last frame. We want to keep children visible
  30966. // that _were_ visible to avoid a pop in level of detail as the camera moves around and parent / sibling tiles
  30967. // load in.
  30968. if (meetsSSE && !allChildrenHaveContent && !childrenWereVisible) {
  30969. if (loadedContent) {
  30970. if (tile.__inFrustum) {
  30971. tile.__visible = true;
  30972. stats.visible++;
  30973. }
  30974. tile.__active = true;
  30975. stats.active++; // load the child content if we've found that we've been loaded so we can move down to the next tile
  30976. // layer when the data has loaded.
  30977. for (let i = 0, l = children.length; i < l; i++) {
  30978. const c = children[i];
  30979. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  30980. c.__depthFromRenderedParent = tile.__depthFromRenderedParent + 1;
  30981. renderer.requestTileContents(c);
  30982. }
  30983. }
  30984. }
  30985. return;
  30986. }
  30987. for (let i = 0, l = children.length; i < l; i++) {
  30988. const c = children[i];
  30989. if (isUsedThisFrame(c, frameCount)) {
  30990. skipTraversal(c, renderer);
  30991. }
  30992. }
  30993. } // Final traverse to toggle tile visibility.
  30994. function toggleTiles(tile, renderer) {
  30995. const frameCount = renderer.frameCount;
  30996. const isUsed = isUsedThisFrame(tile, frameCount);
  30997. if (isUsed || tile.__usedLastFrame) {
  30998. let setActive = false;
  30999. let setVisible = false;
  31000. if (isUsed) {
  31001. // enable visibility if active due to shadows
  31002. setActive = tile.__active;
  31003. if (renderer.displayActiveTiles) {
  31004. setVisible = tile.__active || tile.__visible;
  31005. } else {
  31006. setVisible = tile.__visible;
  31007. }
  31008. } // If the active or visible state changed then call the functions.
  31009. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  31010. if (tile.__wasSetActive !== setActive) {
  31011. renderer.setTileActive(tile, setActive);
  31012. }
  31013. if (tile.__wasSetVisible !== setVisible) {
  31014. renderer.setTileVisible(tile, setVisible);
  31015. }
  31016. }
  31017. tile.__wasSetActive = setActive;
  31018. tile.__wasSetVisible = setVisible;
  31019. tile.__usedLastFrame = isUsed;
  31020. const children = tile.children;
  31021. for (let i = 0, l = children.length; i < l; i++) {
  31022. const c = children[i];
  31023. toggleTiles(c, renderer);
  31024. }
  31025. }
  31026. }
  31027. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  31028. "use strict";
  31029. Object.defineProperty(exports, "__esModule", {
  31030. value: true
  31031. });
  31032. exports.TilesRendererBase = void 0;
  31033. var _path = _interopRequireDefault(require("path"));
  31034. var _LRUCache = require("../utilities/LRUCache.js");
  31035. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  31036. var _traverseFunctions = require("./traverseFunctions.js");
  31037. var _constants = require("./constants.js");
  31038. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31039. // Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  31040. const priorityCallback = tile => 1 / (tile.__depthFromRenderedParent + 1);
  31041. class TilesRendererBase {
  31042. get rootTileSet() {
  31043. const tileSet = this.tileSets[this.rootURL];
  31044. if (!tileSet || tileSet instanceof Promise) {
  31045. return null;
  31046. } else {
  31047. return tileSet;
  31048. }
  31049. }
  31050. get root() {
  31051. const tileSet = this.rootTileSet;
  31052. return tileSet ? tileSet.root : null;
  31053. }
  31054. constructor(url) {
  31055. // state
  31056. this.tileSets = {};
  31057. this.rootURL = url;
  31058. this.fetchOptions = {};
  31059. const lruCache = new _LRUCache.LRUCache();
  31060. lruCache.unloadPriorityCallback = priorityCallback;
  31061. const downloadQueue = new _PriorityQueue.PriorityQueue();
  31062. downloadQueue.maxJobs = 4;
  31063. downloadQueue.priorityCallback = priorityCallback;
  31064. const parseQueue = new _PriorityQueue.PriorityQueue();
  31065. parseQueue.maxJobs = 1;
  31066. parseQueue.priorityCallback = priorityCallback;
  31067. this.lruCache = lruCache;
  31068. this.downloadQueue = downloadQueue;
  31069. this.parseQueue = parseQueue;
  31070. this.stats = {
  31071. parsing: 0,
  31072. downloading: 0,
  31073. inFrustum: 0,
  31074. used: 0,
  31075. active: 0,
  31076. visible: 0
  31077. };
  31078. this.frameCount = 0; // options
  31079. this.errorTarget = 6.0;
  31080. this.errorThreshold = Infinity;
  31081. this.loadSiblings = true;
  31082. this.displayActiveTiles = false;
  31083. this.maxDepth = Infinity;
  31084. }
  31085. traverse(beforecb, aftercb) {
  31086. const tileSets = this.tileSets;
  31087. const rootTileSet = tileSets[this.rootURL];
  31088. if (!rootTileSet || !rootTileSet.root) return;
  31089. (0, _traverseFunctions.traverseSet)(rootTileSet.root, beforecb, aftercb);
  31090. } // Public API
  31091. update() {
  31092. const stats = this.stats;
  31093. const lruCache = this.lruCache;
  31094. const tileSets = this.tileSets;
  31095. const rootTileSet = tileSets[this.rootURL];
  31096. if (!(this.rootURL in tileSets)) {
  31097. this.loadTileSet(this.rootURL);
  31098. return;
  31099. } else if (!rootTileSet || !rootTileSet.root) {
  31100. return;
  31101. }
  31102. const root = rootTileSet.root;
  31103. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  31104. (0, _traverseFunctions.determineFrustumSet)(root, this);
  31105. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  31106. (0, _traverseFunctions.skipTraversal)(root, this);
  31107. (0, _traverseFunctions.toggleTiles)(root, this);
  31108. lruCache.scheduleUnload();
  31109. } // Overrideable
  31110. parseTile(buffer, tile, extension) {
  31111. return null;
  31112. }
  31113. disposeTile(tile) {}
  31114. preprocessNode(tile, parentTile, tileSetDir) {
  31115. if (tile.content) {
  31116. // Fix old file formats
  31117. if (!('uri' in tile.content) && 'url' in tile.content) {
  31118. tile.content.uri = tile.content.url;
  31119. delete tile.content.url;
  31120. }
  31121. if (tile.content.uri) {
  31122. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  31123. } // NOTE: fix for some cases where tilesets provide the bounding volume
  31124. // but volumes are not present.
  31125. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  31126. delete tile.content.boundingVolume;
  31127. }
  31128. }
  31129. tile.parent = parentTile;
  31130. tile.children = tile.children || [];
  31131. tile.__contentEmpty = !tile.content || !tile.content.uri;
  31132. tile.__error = 0.0;
  31133. tile.__inFrustum = false;
  31134. tile.__isLeaf = false;
  31135. tile.__usedLastFrame = false;
  31136. tile.__used = false;
  31137. tile.__wasSetVisible = false;
  31138. tile.__visible = false;
  31139. tile.__childrenWereVisible = false;
  31140. tile.__allChildrenLoaded = false;
  31141. tile.__wasSetActive = false;
  31142. tile.__active = false;
  31143. tile.__loadingState = _constants.UNLOADED;
  31144. tile.__loadIndex = 0;
  31145. tile.__loadAbort = null;
  31146. tile.__depthFromRenderedParent = -1;
  31147. if (parentTile === null) {
  31148. tile.__depth = 0;
  31149. } else {
  31150. tile.__depth = parentTile.__depth + 1;
  31151. }
  31152. }
  31153. setTileActive(tile, state) {}
  31154. setTileVisible(tile, state) {}
  31155. calculateError(tile) {
  31156. return 0;
  31157. }
  31158. tileInView(tile) {
  31159. return true;
  31160. } // Private Functions
  31161. loadTileSet(url) {
  31162. const tileSets = this.tileSets;
  31163. if (!(url in tileSets)) {
  31164. const pr = fetch(url, this.fetchOptions).then(res => {
  31165. if (res.ok) {
  31166. return res.json();
  31167. } else {
  31168. throw new Error(`Status ${res.status} (${res.statusText})`);
  31169. }
  31170. }).then(json => {
  31171. const version = json.asset.version;
  31172. console.assert(version === '1.0' || version === '0.0');
  31173. const basePath = _path.default.dirname(url);
  31174. (0, _traverseFunctions.traverseSet)(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  31175. tileSets[url] = json;
  31176. });
  31177. pr.catch(e => {
  31178. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  31179. console.error(e);
  31180. delete tileSets[url];
  31181. });
  31182. tileSets[url] = pr;
  31183. }
  31184. return Promise.resolve(tileSets[url]);
  31185. }
  31186. requestTileContents(tile) {
  31187. // If the tile is already being loaded then don't
  31188. // start it again.
  31189. if (tile.__loadingState !== _constants.UNLOADED) {
  31190. return;
  31191. }
  31192. const stats = this.stats;
  31193. const lruCache = this.lruCache;
  31194. const downloadQueue = this.downloadQueue;
  31195. const parseQueue = this.parseQueue;
  31196. lruCache.add(tile, t => {
  31197. // Stop the load if it's started
  31198. if (t.__loadingState === _constants.LOADING) {
  31199. t.__loadAbort.abort();
  31200. t.__loadAbort = null;
  31201. } else {
  31202. this.disposeTile(t);
  31203. } // Decrement stats
  31204. if (t.__loadingState === _constants.LOADING) {
  31205. stats.downloading--;
  31206. } else if (t.__loadingState === _constants.PARSING) {
  31207. stats.parsing--;
  31208. }
  31209. t.__buffer = null;
  31210. t.__loadingState = _constants.UNLOADED;
  31211. t.__loadIndex++;
  31212. parseQueue.remove(t);
  31213. downloadQueue.remove(t);
  31214. }); // Track a new load index so we avoid the condition where this load is stopped and
  31215. // another begins soon after so we don't parse twice.
  31216. tile.__loadIndex++;
  31217. const loadIndex = tile.__loadIndex;
  31218. const controller = new AbortController();
  31219. const signal = controller.signal;
  31220. stats.downloading++;
  31221. tile.__loadAbort = controller;
  31222. tile.__loadingState = _constants.LOADING;
  31223. downloadQueue.add(tile, tile => {
  31224. if (tile.__loadIndex !== loadIndex) {
  31225. return Promise.resolve();
  31226. }
  31227. return fetch(tile.content.uri, Object.assign({
  31228. signal
  31229. }, this.fetchOptions));
  31230. }).then(res => {
  31231. if (tile.__loadIndex !== loadIndex) {
  31232. return;
  31233. }
  31234. if (res.ok) {
  31235. return res.arrayBuffer();
  31236. } else {
  31237. throw new Error(`Failed to load model with error code ${res.status}`);
  31238. }
  31239. }).then(buffer => {
  31240. // if it has been unloaded then the tile has been disposed
  31241. if (tile.__loadIndex !== loadIndex) {
  31242. return;
  31243. }
  31244. stats.downloading--;
  31245. stats.parsing++;
  31246. tile.__loadAbort = null;
  31247. tile.__loadingState = _constants.PARSING;
  31248. tile.__buffer = buffer;
  31249. return parseQueue.add(tile, tile => {
  31250. // if it has been unloaded then the tile has been disposed
  31251. if (tile.__loadIndex !== loadIndex) {
  31252. return Promise.resolve();
  31253. }
  31254. const uri = tile.content.uri;
  31255. const extension = uri.split(/\./g).pop();
  31256. const buffer = tile.__buffer;
  31257. tile.__buffer = null;
  31258. return this.parseTile(buffer, tile, extension);
  31259. });
  31260. }).then(() => {
  31261. // if it has been unloaded then the tile has been disposed
  31262. if (tile.__loadIndex !== loadIndex) {
  31263. return;
  31264. }
  31265. stats.parsing--;
  31266. tile.__loadingState = _constants.LOADED;
  31267. if (tile.__wasSetVisible) {
  31268. this.setTileVisible(tile, true);
  31269. }
  31270. if (tile.__wasSetActive) {
  31271. this.setTileActive(tile, true);
  31272. }
  31273. }).catch(e => {
  31274. // if it has been unloaded then the tile has been disposed
  31275. if (tile.__loadIndex !== loadIndex) {
  31276. return;
  31277. }
  31278. if (e.name !== 'AbortError') {
  31279. console.error('TilesRenderer : Failed to load tile.');
  31280. console.error(e);
  31281. tile.__loadingState = _constants.FAILED;
  31282. } else {
  31283. lruCache.remove(tile);
  31284. }
  31285. });
  31286. }
  31287. }
  31288. exports.TilesRendererBase = TilesRendererBase;
  31289. },{"path":"../node_modules/path-browserify/index.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/base/B3DMLoaderBase.js":[function(require,module,exports) {
  31290. "use strict";
  31291. Object.defineProperty(exports, "__esModule", {
  31292. value: true
  31293. });
  31294. exports.B3DMLoaderBase = void 0;
  31295. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  31296. // convert an array of numbers to a string
  31297. function arrayToString(array) {
  31298. let str = '';
  31299. for (let i = 0, l = array.length; i < l; i++) {
  31300. str += String.fromCharCode(array[i]);
  31301. }
  31302. return str;
  31303. }
  31304. class B3DMLoaderBase {
  31305. constructor() {
  31306. this.fetchOptions = {};
  31307. }
  31308. load(url) {
  31309. return fetch(url, this.fetchOptions).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  31310. }
  31311. parse(buffer) {
  31312. const dataView = new DataView(buffer); // 28-byte header
  31313. // 4 bytes
  31314. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  31315. console.assert(magic === 'b3dm'); // 4 bytes
  31316. const version = dataView.getUint32(4, true);
  31317. console.assert(version === 1); // 4 bytes
  31318. const byteLength = dataView.getUint32(8, true);
  31319. console.assert(byteLength === buffer.byteLength); // 4 bytes
  31320. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  31321. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  31322. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  31323. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  31324. const featureTableStart = 28;
  31325. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  31326. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  31327. const featureTable = { ...jsonFeatureTable
  31328. }; // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  31329. // TODO: dereference the json feature table data in to the binary array.
  31330. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  31331. // TODO: The feature table contains data with implicit stride and data types, which means we can't parse it into arrays
  31332. // unless they are specified ahead of time?s
  31333. // Batch Table
  31334. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  31335. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  31336. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  31337. const batchTable = { ...jsonBatchTable
  31338. }; // dereference the json batch table data in to the binary array.
  31339. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  31340. // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  31341. const batchLength = jsonFeatureTable.BATCH_LENGTH;
  31342. for (const key in jsonBatchTable) {
  31343. const feature = jsonBatchTable[key];
  31344. if (Array.isArray(feature)) {
  31345. batchTable[key] = {
  31346. type: 'SCALAR',
  31347. stride: 1,
  31348. data: feature
  31349. };
  31350. } else {
  31351. let stride;
  31352. let data;
  31353. const arrayStart = batchTableStart + batchTableJSONByteLength;
  31354. const arrayLength = batchLength * stride + feature.byteOffset;
  31355. switch (feature.type) {
  31356. case 'SCALAR':
  31357. stride = 1;
  31358. break;
  31359. case 'VEC2':
  31360. stride = 2;
  31361. break;
  31362. case 'VEC3':
  31363. stride = 3;
  31364. break;
  31365. case 'VEC4':
  31366. stride = 4;
  31367. break;
  31368. }
  31369. switch (feature.componentType) {
  31370. case 'BYTE':
  31371. data = new Int8Array(buffer, arrayStart, arrayLength);
  31372. break;
  31373. case 'UNSIGNED_BYTE':
  31374. data = new Uint8Array(buffer, arrayStart, arrayLength);
  31375. break;
  31376. case 'SHORT':
  31377. data = new Int16Array(buffer, arrayStart, arrayLength);
  31378. break;
  31379. case 'UNSIGNED_SHORT':
  31380. data = new Uint16Array(buffer, arrayStart, arrayLength);
  31381. break;
  31382. case 'INT':
  31383. data = new Int32Array(buffer, arrayStart, arrayLength);
  31384. break;
  31385. case 'UNSIGNED_INT':
  31386. data = new Uint32Array(buffer, arrayStart, arrayLength);
  31387. break;
  31388. case 'FLOAT':
  31389. data = new Float32Array(buffer, arrayStart, arrayLength);
  31390. break;
  31391. case 'DOUBLE':
  31392. data = new Float64Array(buffer, arrayStart, arrayLength);
  31393. break;
  31394. }
  31395. batchTable[key] = {
  31396. type: feature.type,
  31397. stride,
  31398. data
  31399. };
  31400. }
  31401. }
  31402. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  31403. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  31404. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  31405. return {
  31406. version,
  31407. featureTable,
  31408. batchTable,
  31409. glbBytes
  31410. };
  31411. }
  31412. }
  31413. exports.B3DMLoaderBase = B3DMLoaderBase;
  31414. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  31415. "use strict";
  31416. Object.defineProperty(exports, "__esModule", {
  31417. value: true
  31418. });
  31419. exports.GLTFLoader = void 0;
  31420. var _threeModule = require("../../../build/three.module.js");
  31421. /**
  31422. * @author Rich Tibbett / https://github.com/richtr
  31423. * @author mrdoob / http://mrdoob.com/
  31424. * @author Tony Parisi / http://www.tonyparisi.com/
  31425. * @author Takahiro / https://github.com/takahirox
  31426. * @author Don McCurdy / https://www.donmccurdy.com
  31427. */
  31428. var GLTFLoader = function () {
  31429. function GLTFLoader(manager) {
  31430. _threeModule.Loader.call(this, manager);
  31431. this.dracoLoader = null;
  31432. this.ddsLoader = null;
  31433. }
  31434. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  31435. constructor: GLTFLoader,
  31436. load: function (url, onLoad, onProgress, onError) {
  31437. var scope = this;
  31438. var resourcePath;
  31439. if (this.resourcePath !== '') {
  31440. resourcePath = this.resourcePath;
  31441. } else if (this.path !== '') {
  31442. resourcePath = this.path;
  31443. } else {
  31444. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  31445. } // Tells the LoadingManager to track an extra item, which resolves after
  31446. // the model is fully loaded. This means the count of items loaded will
  31447. // be incorrect, but ensures manager.onLoad() does not fire early.
  31448. scope.manager.itemStart(url);
  31449. var _onError = function (e) {
  31450. if (onError) {
  31451. onError(e);
  31452. } else {
  31453. console.error(e);
  31454. }
  31455. scope.manager.itemError(url);
  31456. scope.manager.itemEnd(url);
  31457. };
  31458. var loader = new _threeModule.FileLoader(scope.manager);
  31459. loader.setPath(this.path);
  31460. loader.setResponseType('arraybuffer');
  31461. if (scope.crossOrigin === 'use-credentials') {
  31462. loader.setWithCredentials(true);
  31463. }
  31464. loader.load(url, function (data) {
  31465. try {
  31466. scope.parse(data, resourcePath, function (gltf) {
  31467. onLoad(gltf);
  31468. scope.manager.itemEnd(url);
  31469. }, _onError);
  31470. } catch (e) {
  31471. _onError(e);
  31472. }
  31473. }, onProgress, _onError);
  31474. },
  31475. setDRACOLoader: function (dracoLoader) {
  31476. this.dracoLoader = dracoLoader;
  31477. return this;
  31478. },
  31479. setDDSLoader: function (ddsLoader) {
  31480. this.ddsLoader = ddsLoader;
  31481. return this;
  31482. },
  31483. parse: function (data, path, onLoad, onError) {
  31484. var content;
  31485. var extensions = {};
  31486. if (typeof data === 'string') {
  31487. content = data;
  31488. } else {
  31489. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  31490. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  31491. try {
  31492. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  31493. } catch (error) {
  31494. if (onError) onError(error);
  31495. return;
  31496. }
  31497. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  31498. } else {
  31499. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  31500. }
  31501. }
  31502. var json = JSON.parse(content);
  31503. if (json.asset === undefined || json.asset.version[0] < 2) {
  31504. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  31505. return;
  31506. }
  31507. if (json.extensionsUsed) {
  31508. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  31509. var extensionName = json.extensionsUsed[i];
  31510. var extensionsRequired = json.extensionsRequired || [];
  31511. switch (extensionName) {
  31512. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  31513. extensions[extensionName] = new GLTFLightsExtension(json);
  31514. break;
  31515. case EXTENSIONS.KHR_MATERIALS_CLEARCOAT:
  31516. extensions[extensionName] = new GLTFMaterialsClearcoatExtension();
  31517. break;
  31518. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  31519. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  31520. break;
  31521. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  31522. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  31523. break;
  31524. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  31525. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  31526. break;
  31527. case EXTENSIONS.MSFT_TEXTURE_DDS:
  31528. extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader);
  31529. break;
  31530. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  31531. extensions[extensionName] = new GLTFTextureTransformExtension();
  31532. break;
  31533. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  31534. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  31535. break;
  31536. default:
  31537. if (extensionsRequired.indexOf(extensionName) >= 0) {
  31538. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  31539. }
  31540. }
  31541. }
  31542. }
  31543. var parser = new GLTFParser(json, extensions, {
  31544. path: path || this.resourcePath || '',
  31545. crossOrigin: this.crossOrigin,
  31546. manager: this.manager
  31547. });
  31548. parser.parse(onLoad, onError);
  31549. }
  31550. });
  31551. /* GLTFREGISTRY */
  31552. function GLTFRegistry() {
  31553. var objects = {};
  31554. return {
  31555. get: function (key) {
  31556. return objects[key];
  31557. },
  31558. add: function (key, object) {
  31559. objects[key] = object;
  31560. },
  31561. remove: function (key) {
  31562. delete objects[key];
  31563. },
  31564. removeAll: function () {
  31565. objects = {};
  31566. }
  31567. };
  31568. }
  31569. /*********************************/
  31570. /********** EXTENSIONS ***********/
  31571. /*********************************/
  31572. var EXTENSIONS = {
  31573. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  31574. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  31575. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  31576. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  31577. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  31578. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  31579. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  31580. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  31581. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  31582. };
  31583. /**
  31584. * DDS Texture Extension
  31585. *
  31586. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  31587. *
  31588. */
  31589. function GLTFTextureDDSExtension(ddsLoader) {
  31590. if (!ddsLoader) {
  31591. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  31592. }
  31593. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  31594. this.ddsLoader = ddsLoader;
  31595. }
  31596. /**
  31597. * Punctual Lights Extension
  31598. *
  31599. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  31600. */
  31601. function GLTFLightsExtension(json) {
  31602. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  31603. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  31604. this.lightDefs = extension.lights || [];
  31605. }
  31606. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  31607. var lightDef = this.lightDefs[lightIndex];
  31608. var lightNode;
  31609. var color = new _threeModule.Color(0xffffff);
  31610. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  31611. var range = lightDef.range !== undefined ? lightDef.range : 0;
  31612. switch (lightDef.type) {
  31613. case 'directional':
  31614. lightNode = new _threeModule.DirectionalLight(color);
  31615. lightNode.target.position.set(0, 0, -1);
  31616. lightNode.add(lightNode.target);
  31617. break;
  31618. case 'point':
  31619. lightNode = new _threeModule.PointLight(color);
  31620. lightNode.distance = range;
  31621. break;
  31622. case 'spot':
  31623. lightNode = new _threeModule.SpotLight(color);
  31624. lightNode.distance = range; // Handle spotlight properties.
  31625. lightDef.spot = lightDef.spot || {};
  31626. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  31627. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  31628. lightNode.angle = lightDef.spot.outerConeAngle;
  31629. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  31630. lightNode.target.position.set(0, 0, -1);
  31631. lightNode.add(lightNode.target);
  31632. break;
  31633. default:
  31634. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  31635. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  31636. // here, because node-level parsing will only override position if explicitly specified.
  31637. lightNode.position.set(0, 0, 0);
  31638. lightNode.decay = 2;
  31639. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  31640. lightNode.name = lightDef.name || 'light_' + lightIndex;
  31641. return Promise.resolve(lightNode);
  31642. };
  31643. /**
  31644. * Unlit Materials Extension
  31645. *
  31646. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  31647. */
  31648. function GLTFMaterialsUnlitExtension() {
  31649. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  31650. }
  31651. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  31652. return _threeModule.MeshBasicMaterial;
  31653. };
  31654. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  31655. var pending = [];
  31656. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31657. materialParams.opacity = 1.0;
  31658. var metallicRoughness = materialDef.pbrMetallicRoughness;
  31659. if (metallicRoughness) {
  31660. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31661. var array = metallicRoughness.baseColorFactor;
  31662. materialParams.color.fromArray(array);
  31663. materialParams.opacity = array[3];
  31664. }
  31665. if (metallicRoughness.baseColorTexture !== undefined) {
  31666. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31667. }
  31668. }
  31669. return Promise.all(pending);
  31670. };
  31671. /**
  31672. * Clearcoat Materials Extension
  31673. *
  31674. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  31675. */
  31676. function GLTFMaterialsClearcoatExtension() {
  31677. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  31678. }
  31679. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function () {
  31680. return _threeModule.MeshPhysicalMaterial;
  31681. };
  31682. GLTFMaterialsClearcoatExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  31683. var pending = [];
  31684. var extension = materialDef.extensions[this.name];
  31685. if (extension.clearcoatFactor !== undefined) {
  31686. materialParams.clearcoat = extension.clearcoatFactor;
  31687. }
  31688. if (extension.clearcoatTexture !== undefined) {
  31689. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  31690. }
  31691. if (extension.clearcoatRoughnessFactor !== undefined) {
  31692. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  31693. }
  31694. if (extension.clearcoatRoughnessTexture !== undefined) {
  31695. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  31696. }
  31697. if (extension.clearcoatNormalTexture !== undefined) {
  31698. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  31699. if (extension.clearcoatNormalTexture.scale !== undefined) {
  31700. var scale = extension.clearcoatNormalTexture.scale;
  31701. materialParams.clearcoatNormalScale = new _threeModule.Vector2(scale, scale);
  31702. }
  31703. }
  31704. return Promise.all(pending);
  31705. };
  31706. /* BINARY EXTENSION */
  31707. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  31708. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  31709. var BINARY_EXTENSION_CHUNK_TYPES = {
  31710. JSON: 0x4E4F534A,
  31711. BIN: 0x004E4942
  31712. };
  31713. function GLTFBinaryExtension(data) {
  31714. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  31715. this.content = null;
  31716. this.body = null;
  31717. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  31718. this.header = {
  31719. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  31720. version: headerView.getUint32(4, true),
  31721. length: headerView.getUint32(8, true)
  31722. };
  31723. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  31724. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  31725. } else if (this.header.version < 2.0) {
  31726. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  31727. }
  31728. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  31729. var chunkIndex = 0;
  31730. while (chunkIndex < chunkView.byteLength) {
  31731. var chunkLength = chunkView.getUint32(chunkIndex, true);
  31732. chunkIndex += 4;
  31733. var chunkType = chunkView.getUint32(chunkIndex, true);
  31734. chunkIndex += 4;
  31735. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  31736. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  31737. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  31738. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  31739. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  31740. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  31741. } // Clients must ignore chunks with unknown types.
  31742. chunkIndex += chunkLength;
  31743. }
  31744. if (this.content === null) {
  31745. throw new Error('THREE.GLTFLoader: JSON content not found.');
  31746. }
  31747. }
  31748. /**
  31749. * DRACO Mesh Compression Extension
  31750. *
  31751. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  31752. */
  31753. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  31754. if (!dracoLoader) {
  31755. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  31756. }
  31757. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  31758. this.json = json;
  31759. this.dracoLoader = dracoLoader;
  31760. this.dracoLoader.preload();
  31761. }
  31762. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  31763. var json = this.json;
  31764. var dracoLoader = this.dracoLoader;
  31765. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  31766. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  31767. var threeAttributeMap = {};
  31768. var attributeNormalizedMap = {};
  31769. var attributeTypeMap = {};
  31770. for (var attributeName in gltfAttributeMap) {
  31771. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  31772. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  31773. }
  31774. for (attributeName in primitive.attributes) {
  31775. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  31776. if (gltfAttributeMap[attributeName] !== undefined) {
  31777. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  31778. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  31779. attributeTypeMap[threeAttributeName] = componentType;
  31780. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  31781. }
  31782. }
  31783. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  31784. return new Promise(function (resolve) {
  31785. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  31786. for (var attributeName in geometry.attributes) {
  31787. var attribute = geometry.attributes[attributeName];
  31788. var normalized = attributeNormalizedMap[attributeName];
  31789. if (normalized !== undefined) attribute.normalized = normalized;
  31790. }
  31791. resolve(geometry);
  31792. }, threeAttributeMap, attributeTypeMap);
  31793. });
  31794. });
  31795. };
  31796. /**
  31797. * Texture Transform Extension
  31798. *
  31799. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  31800. */
  31801. function GLTFTextureTransformExtension() {
  31802. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  31803. }
  31804. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  31805. texture = texture.clone();
  31806. if (transform.offset !== undefined) {
  31807. texture.offset.fromArray(transform.offset);
  31808. }
  31809. if (transform.rotation !== undefined) {
  31810. texture.rotation = transform.rotation;
  31811. }
  31812. if (transform.scale !== undefined) {
  31813. texture.repeat.fromArray(transform.scale);
  31814. }
  31815. if (transform.texCoord !== undefined) {
  31816. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  31817. }
  31818. texture.needsUpdate = true;
  31819. return texture;
  31820. };
  31821. /**
  31822. * Specular-Glossiness Extension
  31823. *
  31824. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  31825. */
  31826. /**
  31827. * A sub class of StandardMaterial with some of the functionality
  31828. * changed via the `onBeforeCompile` callback
  31829. * @pailhead
  31830. */
  31831. function GLTFMeshStandardSGMaterial(params) {
  31832. _threeModule.MeshStandardMaterial.call(this);
  31833. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  31834. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  31835. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  31836. 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');
  31837. 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');
  31838. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', '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.rgb;'].join('\n');
  31839. var uniforms = {
  31840. specular: {
  31841. value: new _threeModule.Color().setHex(0xffffff)
  31842. },
  31843. glossiness: {
  31844. value: 1
  31845. },
  31846. specularMap: {
  31847. value: null
  31848. },
  31849. glossinessMap: {
  31850. value: null
  31851. }
  31852. };
  31853. this._extraUniforms = uniforms; // please see #14031 or #13198 for an alternate approach
  31854. this.onBeforeCompile = function (shader) {
  31855. for (var uniformName in uniforms) {
  31856. shader.uniforms[uniformName] = uniforms[uniformName];
  31857. }
  31858. shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;');
  31859. shader.fragmentShader = shader.fragmentShader.replace('uniform float metalness;', 'uniform float glossiness;');
  31860. shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk);
  31861. shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk);
  31862. shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_fragment>', specularMapFragmentChunk);
  31863. shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk);
  31864. shader.fragmentShader = shader.fragmentShader.replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  31865. };
  31866. /*eslint-disable*/
  31867. Object.defineProperties(this, {
  31868. specular: {
  31869. get: function () {
  31870. return uniforms.specular.value;
  31871. },
  31872. set: function (v) {
  31873. uniforms.specular.value = v;
  31874. }
  31875. },
  31876. specularMap: {
  31877. get: function () {
  31878. return uniforms.specularMap.value;
  31879. },
  31880. set: function (v) {
  31881. uniforms.specularMap.value = v;
  31882. }
  31883. },
  31884. glossiness: {
  31885. get: function () {
  31886. return uniforms.glossiness.value;
  31887. },
  31888. set: function (v) {
  31889. uniforms.glossiness.value = v;
  31890. }
  31891. },
  31892. glossinessMap: {
  31893. get: function () {
  31894. return uniforms.glossinessMap.value;
  31895. },
  31896. set: function (v) {
  31897. uniforms.glossinessMap.value = v; //how about something like this - @pailhead
  31898. if (v) {
  31899. this.defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  31900. this.defines.USE_ROUGHNESSMAP = '';
  31901. } else {
  31902. delete this.defines.USE_ROUGHNESSMAP;
  31903. delete this.defines.USE_GLOSSINESSMAP;
  31904. }
  31905. }
  31906. }
  31907. });
  31908. /*eslint-enable*/
  31909. delete this.metalness;
  31910. delete this.roughness;
  31911. delete this.metalnessMap;
  31912. delete this.roughnessMap;
  31913. this.setValues(params);
  31914. }
  31915. GLTFMeshStandardSGMaterial.prototype = Object.create(_threeModule.MeshStandardMaterial.prototype);
  31916. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  31917. GLTFMeshStandardSGMaterial.prototype.copy = function (source) {
  31918. _threeModule.MeshStandardMaterial.prototype.copy.call(this, source);
  31919. this.specularMap = source.specularMap;
  31920. this.specular.copy(source.specular);
  31921. this.glossinessMap = source.glossinessMap;
  31922. this.glossiness = source.glossiness;
  31923. delete this.metalness;
  31924. delete this.roughness;
  31925. delete this.metalnessMap;
  31926. delete this.roughnessMap;
  31927. return this;
  31928. };
  31929. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  31930. return {
  31931. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  31932. 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'],
  31933. getMaterialType: function () {
  31934. return GLTFMeshStandardSGMaterial;
  31935. },
  31936. extendParams: function (materialParams, materialDef, parser) {
  31937. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  31938. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31939. materialParams.opacity = 1.0;
  31940. var pending = [];
  31941. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  31942. var array = pbrSpecularGlossiness.diffuseFactor;
  31943. materialParams.color.fromArray(array);
  31944. materialParams.opacity = array[3];
  31945. }
  31946. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  31947. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  31948. }
  31949. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  31950. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  31951. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  31952. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  31953. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  31954. }
  31955. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  31956. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  31957. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  31958. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  31959. }
  31960. return Promise.all(pending);
  31961. },
  31962. createMaterial: function (materialParams) {
  31963. var material = new GLTFMeshStandardSGMaterial(materialParams);
  31964. material.fog = true;
  31965. material.color = materialParams.color;
  31966. material.map = materialParams.map === undefined ? null : materialParams.map;
  31967. material.lightMap = null;
  31968. material.lightMapIntensity = 1.0;
  31969. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  31970. material.aoMapIntensity = 1.0;
  31971. material.emissive = materialParams.emissive;
  31972. material.emissiveIntensity = 1.0;
  31973. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  31974. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  31975. material.bumpScale = 1;
  31976. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  31977. material.normalMapType = _threeModule.TangentSpaceNormalMap;
  31978. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  31979. material.displacementMap = null;
  31980. material.displacementScale = 1;
  31981. material.displacementBias = 0;
  31982. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  31983. material.specular = materialParams.specular;
  31984. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  31985. material.glossiness = materialParams.glossiness;
  31986. material.alphaMap = null;
  31987. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  31988. material.envMapIntensity = 1.0;
  31989. material.refractionRatio = 0.98;
  31990. return material;
  31991. }
  31992. };
  31993. }
  31994. /**
  31995. * Mesh Quantization Extension
  31996. *
  31997. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  31998. */
  31999. function GLTFMeshQuantizationExtension() {
  32000. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  32001. }
  32002. /*********************************/
  32003. /********** INTERPOLATION ********/
  32004. /*********************************/
  32005. // Spline Interpolation
  32006. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  32007. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  32008. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  32009. }
  32010. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  32011. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  32012. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  32013. // Copies a sample value to the result buffer. See description of glTF
  32014. // CUBICSPLINE values layout in interpolate_() function below.
  32015. var result = this.resultBuffer,
  32016. values = this.sampleValues,
  32017. valueSize = this.valueSize,
  32018. offset = index * valueSize * 3 + valueSize;
  32019. for (var i = 0; i !== valueSize; i++) {
  32020. result[i] = values[offset + i];
  32021. }
  32022. return result;
  32023. };
  32024. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  32025. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  32026. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  32027. var result = this.resultBuffer;
  32028. var values = this.sampleValues;
  32029. var stride = this.valueSize;
  32030. var stride2 = stride * 2;
  32031. var stride3 = stride * 3;
  32032. var td = t1 - t0;
  32033. var p = (t - t0) / td;
  32034. var pp = p * p;
  32035. var ppp = pp * p;
  32036. var offset1 = i1 * stride3;
  32037. var offset0 = offset1 - stride3;
  32038. var s2 = -2 * ppp + 3 * pp;
  32039. var s3 = ppp - pp;
  32040. var s0 = 1 - s2;
  32041. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  32042. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  32043. for (var i = 0; i !== stride; i++) {
  32044. var p0 = values[offset0 + i + stride]; // splineVertex_k
  32045. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  32046. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  32047. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  32048. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  32049. }
  32050. return result;
  32051. };
  32052. /*********************************/
  32053. /********** INTERNALS ************/
  32054. /*********************************/
  32055. /* CONSTANTS */
  32056. var WEBGL_CONSTANTS = {
  32057. FLOAT: 5126,
  32058. //FLOAT_MAT2: 35674,
  32059. FLOAT_MAT3: 35675,
  32060. FLOAT_MAT4: 35676,
  32061. FLOAT_VEC2: 35664,
  32062. FLOAT_VEC3: 35665,
  32063. FLOAT_VEC4: 35666,
  32064. LINEAR: 9729,
  32065. REPEAT: 10497,
  32066. SAMPLER_2D: 35678,
  32067. POINTS: 0,
  32068. LINES: 1,
  32069. LINE_LOOP: 2,
  32070. LINE_STRIP: 3,
  32071. TRIANGLES: 4,
  32072. TRIANGLE_STRIP: 5,
  32073. TRIANGLE_FAN: 6,
  32074. UNSIGNED_BYTE: 5121,
  32075. UNSIGNED_SHORT: 5123
  32076. };
  32077. var WEBGL_COMPONENT_TYPES = {
  32078. 5120: Int8Array,
  32079. 5121: Uint8Array,
  32080. 5122: Int16Array,
  32081. 5123: Uint16Array,
  32082. 5125: Uint32Array,
  32083. 5126: Float32Array
  32084. };
  32085. var WEBGL_FILTERS = {
  32086. 9728: _threeModule.NearestFilter,
  32087. 9729: _threeModule.LinearFilter,
  32088. 9984: _threeModule.NearestMipmapNearestFilter,
  32089. 9985: _threeModule.LinearMipmapNearestFilter,
  32090. 9986: _threeModule.NearestMipmapLinearFilter,
  32091. 9987: _threeModule.LinearMipmapLinearFilter
  32092. };
  32093. var WEBGL_WRAPPINGS = {
  32094. 33071: _threeModule.ClampToEdgeWrapping,
  32095. 33648: _threeModule.MirroredRepeatWrapping,
  32096. 10497: _threeModule.RepeatWrapping
  32097. };
  32098. var WEBGL_TYPE_SIZES = {
  32099. 'SCALAR': 1,
  32100. 'VEC2': 2,
  32101. 'VEC3': 3,
  32102. 'VEC4': 4,
  32103. 'MAT2': 4,
  32104. 'MAT3': 9,
  32105. 'MAT4': 16
  32106. };
  32107. var ATTRIBUTES = {
  32108. POSITION: 'position',
  32109. NORMAL: 'normal',
  32110. TANGENT: 'tangent',
  32111. TEXCOORD_0: 'uv',
  32112. TEXCOORD_1: 'uv2',
  32113. COLOR_0: 'color',
  32114. WEIGHTS_0: 'skinWeight',
  32115. JOINTS_0: 'skinIndex'
  32116. };
  32117. var PATH_PROPERTIES = {
  32118. scale: 'scale',
  32119. translation: 'position',
  32120. rotation: 'quaternion',
  32121. weights: 'morphTargetInfluences'
  32122. };
  32123. var INTERPOLATION = {
  32124. CUBICSPLINE: undefined,
  32125. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  32126. // keyframe track will be initialized with a default interpolation type, then modified.
  32127. LINEAR: _threeModule.InterpolateLinear,
  32128. STEP: _threeModule.InterpolateDiscrete
  32129. };
  32130. var ALPHA_MODES = {
  32131. OPAQUE: 'OPAQUE',
  32132. MASK: 'MASK',
  32133. BLEND: 'BLEND'
  32134. };
  32135. var MIME_TYPE_FORMATS = {
  32136. 'image/png': _threeModule.RGBAFormat,
  32137. 'image/jpeg': _threeModule.RGBFormat
  32138. };
  32139. /* UTILITY FUNCTIONS */
  32140. function resolveURL(url, path) {
  32141. // Invalid URL
  32142. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  32143. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  32144. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  32145. } // Absolute URL http://,https://,//
  32146. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  32147. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  32148. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  32149. return path + url;
  32150. }
  32151. /**
  32152. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  32153. */
  32154. function createDefaultMaterial(cache) {
  32155. if (cache['DefaultMaterial'] === undefined) {
  32156. cache['DefaultMaterial'] = new _threeModule.MeshStandardMaterial({
  32157. color: 0xFFFFFF,
  32158. emissive: 0x000000,
  32159. metalness: 1,
  32160. roughness: 1,
  32161. transparent: false,
  32162. depthTest: true,
  32163. side: _threeModule.FrontSide
  32164. });
  32165. }
  32166. return cache['DefaultMaterial'];
  32167. }
  32168. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  32169. // Add unknown glTF extensions to an object's userData.
  32170. for (var name in objectDef.extensions) {
  32171. if (knownExtensions[name] === undefined) {
  32172. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  32173. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  32174. }
  32175. }
  32176. }
  32177. /**
  32178. * @param {Object3D|Material|BufferGeometry} object
  32179. * @param {GLTF.definition} gltfDef
  32180. */
  32181. function assignExtrasToUserData(object, gltfDef) {
  32182. if (gltfDef.extras !== undefined) {
  32183. if (typeof gltfDef.extras === 'object') {
  32184. Object.assign(object.userData, gltfDef.extras);
  32185. } else {
  32186. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  32187. }
  32188. }
  32189. }
  32190. /**
  32191. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  32192. *
  32193. * @param {BufferGeometry} geometry
  32194. * @param {Array<GLTF.Target>} targets
  32195. * @param {GLTFParser} parser
  32196. * @return {Promise<BufferGeometry>}
  32197. */
  32198. function addMorphTargets(geometry, targets, parser) {
  32199. var hasMorphPosition = false;
  32200. var hasMorphNormal = false;
  32201. for (var i = 0, il = targets.length; i < il; i++) {
  32202. var target = targets[i];
  32203. if (target.POSITION !== undefined) hasMorphPosition = true;
  32204. if (target.NORMAL !== undefined) hasMorphNormal = true;
  32205. if (hasMorphPosition && hasMorphNormal) break;
  32206. }
  32207. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  32208. var pendingPositionAccessors = [];
  32209. var pendingNormalAccessors = [];
  32210. for (var i = 0, il = targets.length; i < il; i++) {
  32211. var target = targets[i];
  32212. if (hasMorphPosition) {
  32213. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  32214. pendingPositionAccessors.push(pendingAccessor);
  32215. }
  32216. if (hasMorphNormal) {
  32217. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  32218. pendingNormalAccessors.push(pendingAccessor);
  32219. }
  32220. }
  32221. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  32222. var morphPositions = accessors[0];
  32223. var morphNormals = accessors[1];
  32224. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  32225. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  32226. geometry.morphTargetsRelative = true;
  32227. return geometry;
  32228. });
  32229. }
  32230. /**
  32231. * @param {Mesh} mesh
  32232. * @param {GLTF.Mesh} meshDef
  32233. */
  32234. function updateMorphTargets(mesh, meshDef) {
  32235. mesh.updateMorphTargets();
  32236. if (meshDef.weights !== undefined) {
  32237. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  32238. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  32239. }
  32240. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  32241. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  32242. var targetNames = meshDef.extras.targetNames;
  32243. if (mesh.morphTargetInfluences.length === targetNames.length) {
  32244. mesh.morphTargetDictionary = {};
  32245. for (var i = 0, il = targetNames.length; i < il; i++) {
  32246. mesh.morphTargetDictionary[targetNames[i]] = i;
  32247. }
  32248. } else {
  32249. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  32250. }
  32251. }
  32252. }
  32253. function createPrimitiveKey(primitiveDef) {
  32254. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  32255. var geometryKey;
  32256. if (dracoExtension) {
  32257. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  32258. } else {
  32259. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  32260. }
  32261. return geometryKey;
  32262. }
  32263. function createAttributesKey(attributes) {
  32264. var attributesKey = '';
  32265. var keys = Object.keys(attributes).sort();
  32266. for (var i = 0, il = keys.length; i < il; i++) {
  32267. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  32268. }
  32269. return attributesKey;
  32270. }
  32271. /* GLTF PARSER */
  32272. function GLTFParser(json, extensions, options) {
  32273. this.json = json || {};
  32274. this.extensions = extensions || {};
  32275. this.options = options || {}; // loader object cache
  32276. this.cache = new GLTFRegistry(); // BufferGeometry caching
  32277. this.primitiveCache = {};
  32278. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  32279. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  32280. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  32281. this.fileLoader.setResponseType('arraybuffer');
  32282. if (this.options.crossOrigin === 'use-credentials') {
  32283. this.fileLoader.setWithCredentials(true);
  32284. }
  32285. }
  32286. GLTFParser.prototype.parse = function (onLoad, onError) {
  32287. var parser = this;
  32288. var json = this.json;
  32289. var extensions = this.extensions; // Clear the loader cache
  32290. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  32291. this.markDefs();
  32292. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  32293. var result = {
  32294. scene: dependencies[0][json.scene || 0],
  32295. scenes: dependencies[0],
  32296. animations: dependencies[1],
  32297. cameras: dependencies[2],
  32298. asset: json.asset,
  32299. parser: parser,
  32300. userData: {}
  32301. };
  32302. addUnknownExtensionsToUserData(extensions, result, json);
  32303. assignExtrasToUserData(result, json);
  32304. onLoad(result);
  32305. }).catch(onError);
  32306. };
  32307. /**
  32308. * Marks the special nodes/meshes in json for efficient parse.
  32309. */
  32310. GLTFParser.prototype.markDefs = function () {
  32311. var nodeDefs = this.json.nodes || [];
  32312. var skinDefs = this.json.skins || [];
  32313. var meshDefs = this.json.meshes || [];
  32314. var meshReferences = {};
  32315. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  32316. // Object3D. Use the skins' joint references to mark bones.
  32317. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  32318. var joints = skinDefs[skinIndex].joints;
  32319. for (var i = 0, il = joints.length; i < il; i++) {
  32320. nodeDefs[joints[i]].isBone = true;
  32321. }
  32322. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  32323. // avoid having more than one Mesh with the same name, count
  32324. // references and rename instances below.
  32325. //
  32326. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  32327. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  32328. var nodeDef = nodeDefs[nodeIndex];
  32329. if (nodeDef.mesh !== undefined) {
  32330. if (meshReferences[nodeDef.mesh] === undefined) {
  32331. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  32332. }
  32333. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  32334. // a SkinnedMesh or Mesh. Use the node's mesh reference
  32335. // to mark SkinnedMesh if node has skin.
  32336. if (nodeDef.skin !== undefined) {
  32337. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  32338. }
  32339. }
  32340. }
  32341. this.json.meshReferences = meshReferences;
  32342. this.json.meshUses = meshUses;
  32343. };
  32344. /**
  32345. * Requests the specified dependency asynchronously, with caching.
  32346. * @param {string} type
  32347. * @param {number} index
  32348. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  32349. */
  32350. GLTFParser.prototype.getDependency = function (type, index) {
  32351. var cacheKey = type + ':' + index;
  32352. var dependency = this.cache.get(cacheKey);
  32353. if (!dependency) {
  32354. switch (type) {
  32355. case 'scene':
  32356. dependency = this.loadScene(index);
  32357. break;
  32358. case 'node':
  32359. dependency = this.loadNode(index);
  32360. break;
  32361. case 'mesh':
  32362. dependency = this.loadMesh(index);
  32363. break;
  32364. case 'accessor':
  32365. dependency = this.loadAccessor(index);
  32366. break;
  32367. case 'bufferView':
  32368. dependency = this.loadBufferView(index);
  32369. break;
  32370. case 'buffer':
  32371. dependency = this.loadBuffer(index);
  32372. break;
  32373. case 'material':
  32374. dependency = this.loadMaterial(index);
  32375. break;
  32376. case 'texture':
  32377. dependency = this.loadTexture(index);
  32378. break;
  32379. case 'skin':
  32380. dependency = this.loadSkin(index);
  32381. break;
  32382. case 'animation':
  32383. dependency = this.loadAnimation(index);
  32384. break;
  32385. case 'camera':
  32386. dependency = this.loadCamera(index);
  32387. break;
  32388. case 'light':
  32389. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  32390. break;
  32391. default:
  32392. throw new Error('Unknown type: ' + type);
  32393. }
  32394. this.cache.add(cacheKey, dependency);
  32395. }
  32396. return dependency;
  32397. };
  32398. /**
  32399. * Requests all dependencies of the specified type asynchronously, with caching.
  32400. * @param {string} type
  32401. * @return {Promise<Array<Object>>}
  32402. */
  32403. GLTFParser.prototype.getDependencies = function (type) {
  32404. var dependencies = this.cache.get(type);
  32405. if (!dependencies) {
  32406. var parser = this;
  32407. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  32408. dependencies = Promise.all(defs.map(function (def, index) {
  32409. return parser.getDependency(type, index);
  32410. }));
  32411. this.cache.add(type, dependencies);
  32412. }
  32413. return dependencies;
  32414. };
  32415. /**
  32416. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32417. * @param {number} bufferIndex
  32418. * @return {Promise<ArrayBuffer>}
  32419. */
  32420. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  32421. var bufferDef = this.json.buffers[bufferIndex];
  32422. var loader = this.fileLoader;
  32423. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  32424. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  32425. } // If present, GLB container is required to be the first buffer.
  32426. if (bufferDef.uri === undefined && bufferIndex === 0) {
  32427. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  32428. }
  32429. var options = this.options;
  32430. return new Promise(function (resolve, reject) {
  32431. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  32432. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  32433. });
  32434. });
  32435. };
  32436. /**
  32437. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32438. * @param {number} bufferViewIndex
  32439. * @return {Promise<ArrayBuffer>}
  32440. */
  32441. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  32442. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  32443. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  32444. var byteLength = bufferViewDef.byteLength || 0;
  32445. var byteOffset = bufferViewDef.byteOffset || 0;
  32446. return buffer.slice(byteOffset, byteOffset + byteLength);
  32447. });
  32448. };
  32449. /**
  32450. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  32451. * @param {number} accessorIndex
  32452. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  32453. */
  32454. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  32455. var parser = this;
  32456. var json = this.json;
  32457. var accessorDef = this.json.accessors[accessorIndex];
  32458. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  32459. // Ignore empty accessors, which may be used to declare runtime
  32460. // information about attributes coming from another source (e.g. Draco
  32461. // compression extension).
  32462. return Promise.resolve(null);
  32463. }
  32464. var pendingBufferViews = [];
  32465. if (accessorDef.bufferView !== undefined) {
  32466. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  32467. } else {
  32468. pendingBufferViews.push(null);
  32469. }
  32470. if (accessorDef.sparse !== undefined) {
  32471. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  32472. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  32473. }
  32474. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  32475. var bufferView = bufferViews[0];
  32476. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  32477. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  32478. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  32479. var itemBytes = elementBytes * itemSize;
  32480. var byteOffset = accessorDef.byteOffset || 0;
  32481. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  32482. var normalized = accessorDef.normalized === true;
  32483. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  32484. if (byteStride && byteStride !== itemBytes) {
  32485. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  32486. // This makes sure that IBA.count reflects accessor.count properly
  32487. var ibSlice = Math.floor(byteOffset / byteStride);
  32488. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  32489. var ib = parser.cache.get(ibCacheKey);
  32490. if (!ib) {
  32491. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  32492. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  32493. parser.cache.add(ibCacheKey, ib);
  32494. }
  32495. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  32496. } else {
  32497. if (bufferView === null) {
  32498. array = new TypedArray(accessorDef.count * itemSize);
  32499. } else {
  32500. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  32501. }
  32502. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  32503. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  32504. if (accessorDef.sparse !== undefined) {
  32505. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  32506. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  32507. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  32508. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  32509. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  32510. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  32511. if (bufferView !== null) {
  32512. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  32513. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  32514. }
  32515. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  32516. var index = sparseIndices[i];
  32517. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  32518. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  32519. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  32520. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  32521. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  32522. }
  32523. }
  32524. return bufferAttribute;
  32525. });
  32526. };
  32527. /**
  32528. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  32529. * @param {number} textureIndex
  32530. * @return {Promise<THREE.Texture>}
  32531. */
  32532. GLTFParser.prototype.loadTexture = function (textureIndex) {
  32533. var parser = this;
  32534. var json = this.json;
  32535. var options = this.options;
  32536. var textureLoader = this.textureLoader;
  32537. var URL = self.URL || self.webkitURL;
  32538. var textureDef = json.textures[textureIndex];
  32539. var textureExtensions = textureDef.extensions || {};
  32540. var source;
  32541. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  32542. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  32543. } else {
  32544. source = json.images[textureDef.source];
  32545. }
  32546. var sourceURI = source.uri;
  32547. var isObjectURL = false;
  32548. if (source.bufferView !== undefined) {
  32549. // Load binary image data from bufferView, if provided.
  32550. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  32551. isObjectURL = true;
  32552. var blob = new Blob([bufferView], {
  32553. type: source.mimeType
  32554. });
  32555. sourceURI = URL.createObjectURL(blob);
  32556. return sourceURI;
  32557. });
  32558. }
  32559. return Promise.resolve(sourceURI).then(function (sourceURI) {
  32560. // Load Texture resource.
  32561. var loader = options.manager.getHandler(sourceURI);
  32562. if (!loader) {
  32563. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  32564. }
  32565. return new Promise(function (resolve, reject) {
  32566. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  32567. });
  32568. }).then(function (texture) {
  32569. // Clean up resources and configure Texture.
  32570. if (isObjectURL === true) {
  32571. URL.revokeObjectURL(sourceURI);
  32572. }
  32573. texture.flipY = false;
  32574. if (textureDef.name) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  32575. if (source.mimeType in MIME_TYPE_FORMATS) {
  32576. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  32577. }
  32578. var samplers = json.samplers || {};
  32579. var sampler = samplers[textureDef.sampler] || {};
  32580. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  32581. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  32582. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  32583. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  32584. return texture;
  32585. });
  32586. };
  32587. /**
  32588. * Asynchronously assigns a texture to the given material parameters.
  32589. * @param {Object} materialParams
  32590. * @param {string} mapName
  32591. * @param {Object} mapDef
  32592. * @return {Promise}
  32593. */
  32594. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  32595. var parser = this;
  32596. return this.getDependency('texture', mapDef.index).then(function (texture) {
  32597. if (!texture.isCompressedTexture) {
  32598. switch (mapName) {
  32599. case 'aoMap':
  32600. case 'emissiveMap':
  32601. case 'metalnessMap':
  32602. case 'normalMap':
  32603. case 'roughnessMap':
  32604. texture.format = _threeModule.RGBFormat;
  32605. break;
  32606. }
  32607. } // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  32608. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  32609. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  32610. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  32611. }
  32612. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  32613. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  32614. if (transform) {
  32615. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  32616. }
  32617. }
  32618. materialParams[mapName] = texture;
  32619. });
  32620. };
  32621. /**
  32622. * Assigns final material to a Mesh, Line, or Points instance. The instance
  32623. * already has a material (generated from the glTF material options alone)
  32624. * but reuse of the same glTF material may require multiple threejs materials
  32625. * to accomodate different primitive types, defines, etc. New materials will
  32626. * be created if necessary, and reused from a cache.
  32627. * @param {Object3D} mesh Mesh, Line, or Points instance.
  32628. */
  32629. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  32630. var geometry = mesh.geometry;
  32631. var material = mesh.material;
  32632. var useVertexTangents = geometry.attributes.tangent !== undefined;
  32633. var useVertexColors = geometry.attributes.color !== undefined;
  32634. var useFlatShading = geometry.attributes.normal === undefined;
  32635. var useSkinning = mesh.isSkinnedMesh === true;
  32636. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  32637. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  32638. if (mesh.isPoints) {
  32639. var cacheKey = 'PointsMaterial:' + material.uuid;
  32640. var pointsMaterial = this.cache.get(cacheKey);
  32641. if (!pointsMaterial) {
  32642. pointsMaterial = new _threeModule.PointsMaterial();
  32643. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  32644. pointsMaterial.color.copy(material.color);
  32645. pointsMaterial.map = material.map;
  32646. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  32647. this.cache.add(cacheKey, pointsMaterial);
  32648. }
  32649. material = pointsMaterial;
  32650. } else if (mesh.isLine) {
  32651. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  32652. var lineMaterial = this.cache.get(cacheKey);
  32653. if (!lineMaterial) {
  32654. lineMaterial = new _threeModule.LineBasicMaterial();
  32655. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  32656. lineMaterial.color.copy(material.color);
  32657. this.cache.add(cacheKey, lineMaterial);
  32658. }
  32659. material = lineMaterial;
  32660. } // Clone the material if it will be modified
  32661. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  32662. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  32663. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  32664. if (useSkinning) cacheKey += 'skinning:';
  32665. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  32666. if (useVertexColors) cacheKey += 'vertex-colors:';
  32667. if (useFlatShading) cacheKey += 'flat-shading:';
  32668. if (useMorphTargets) cacheKey += 'morph-targets:';
  32669. if (useMorphNormals) cacheKey += 'morph-normals:';
  32670. var cachedMaterial = this.cache.get(cacheKey);
  32671. if (!cachedMaterial) {
  32672. cachedMaterial = material.clone();
  32673. if (useSkinning) cachedMaterial.skinning = true;
  32674. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  32675. if (useVertexColors) cachedMaterial.vertexColors = true;
  32676. if (useFlatShading) cachedMaterial.flatShading = true;
  32677. if (useMorphTargets) cachedMaterial.morphTargets = true;
  32678. if (useMorphNormals) cachedMaterial.morphNormals = true;
  32679. this.cache.add(cacheKey, cachedMaterial);
  32680. }
  32681. material = cachedMaterial;
  32682. } // workarounds for mesh and geometry
  32683. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  32684. geometry.setAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  32685. } // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  32686. if (material.normalScale && !useVertexTangents) {
  32687. material.normalScale.y = -material.normalScale.y;
  32688. }
  32689. if (material.clearcoatNormalScale && !useVertexTangents) {
  32690. material.clearcoatNormalScale.y = -material.clearcoatNormalScale.y;
  32691. }
  32692. mesh.material = material;
  32693. };
  32694. /**
  32695. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  32696. * @param {number} materialIndex
  32697. * @return {Promise<Material>}
  32698. */
  32699. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  32700. var parser = this;
  32701. var json = this.json;
  32702. var extensions = this.extensions;
  32703. var materialDef = json.materials[materialIndex];
  32704. var materialType;
  32705. var materialParams = {};
  32706. var materialExtensions = materialDef.extensions || {};
  32707. var pending = [];
  32708. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  32709. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  32710. materialType = sgExtension.getMaterialType();
  32711. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  32712. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  32713. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  32714. materialType = kmuExtension.getMaterialType();
  32715. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  32716. } else {
  32717. // Specification:
  32718. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  32719. materialType = _threeModule.MeshStandardMaterial;
  32720. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  32721. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32722. materialParams.opacity = 1.0;
  32723. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  32724. var array = metallicRoughness.baseColorFactor;
  32725. materialParams.color.fromArray(array);
  32726. materialParams.opacity = array[3];
  32727. }
  32728. if (metallicRoughness.baseColorTexture !== undefined) {
  32729. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  32730. }
  32731. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  32732. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  32733. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  32734. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  32735. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  32736. }
  32737. }
  32738. if (materialDef.doubleSided === true) {
  32739. materialParams.side = _threeModule.DoubleSide;
  32740. }
  32741. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  32742. if (alphaMode === ALPHA_MODES.BLEND) {
  32743. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  32744. materialParams.depthWrite = false;
  32745. } else {
  32746. materialParams.transparent = false;
  32747. if (alphaMode === ALPHA_MODES.MASK) {
  32748. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  32749. }
  32750. }
  32751. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32752. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  32753. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  32754. if (materialDef.normalTexture.scale !== undefined) {
  32755. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  32756. }
  32757. }
  32758. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32759. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  32760. if (materialDef.occlusionTexture.strength !== undefined) {
  32761. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  32762. }
  32763. }
  32764. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32765. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  32766. }
  32767. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32768. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  32769. }
  32770. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT]) {
  32771. var clearcoatExtension = extensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT];
  32772. materialType = clearcoatExtension.getMaterialType();
  32773. pending.push(clearcoatExtension.extendParams(materialParams, {
  32774. extensions: materialExtensions
  32775. }, parser));
  32776. }
  32777. return Promise.all(pending).then(function () {
  32778. var material;
  32779. if (materialType === GLTFMeshStandardSGMaterial) {
  32780. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  32781. } else {
  32782. material = new materialType(materialParams);
  32783. }
  32784. if (materialDef.name) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  32785. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  32786. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  32787. assignExtrasToUserData(material, materialDef);
  32788. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  32789. return material;
  32790. });
  32791. };
  32792. /**
  32793. * @param {BufferGeometry} geometry
  32794. * @param {GLTF.Primitive} primitiveDef
  32795. * @param {GLTFParser} parser
  32796. */
  32797. function computeBounds(geometry, primitiveDef, parser) {
  32798. var attributes = primitiveDef.attributes;
  32799. var box = new _threeModule.Box3();
  32800. if (attributes.POSITION !== undefined) {
  32801. var accessor = parser.json.accessors[attributes.POSITION];
  32802. var min = accessor.min;
  32803. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  32804. if (min !== undefined && max !== undefined) {
  32805. box.set(new _threeModule.Vector3(min[0], min[1], min[2]), new _threeModule.Vector3(max[0], max[1], max[2]));
  32806. } else {
  32807. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  32808. return;
  32809. }
  32810. } else {
  32811. return;
  32812. }
  32813. var targets = primitiveDef.targets;
  32814. if (targets !== undefined) {
  32815. var maxDisplacement = new _threeModule.Vector3();
  32816. var vector = new _threeModule.Vector3();
  32817. for (var i = 0, il = targets.length; i < il; i++) {
  32818. var target = targets[i];
  32819. if (target.POSITION !== undefined) {
  32820. var accessor = parser.json.accessors[target.POSITION];
  32821. var min = accessor.min;
  32822. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  32823. if (min !== undefined && max !== undefined) {
  32824. // we need to get max of absolute components because target weight is [-1,1]
  32825. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
  32826. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
  32827. 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
  32828. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  32829. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  32830. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  32831. maxDisplacement.max(vector);
  32832. } else {
  32833. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  32834. }
  32835. }
  32836. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  32837. box.expandByVector(maxDisplacement);
  32838. }
  32839. geometry.boundingBox = box;
  32840. var sphere = new _threeModule.Sphere();
  32841. box.getCenter(sphere.center);
  32842. sphere.radius = box.min.distanceTo(box.max) / 2;
  32843. geometry.boundingSphere = sphere;
  32844. }
  32845. /**
  32846. * @param {BufferGeometry} geometry
  32847. * @param {GLTF.Primitive} primitiveDef
  32848. * @param {GLTFParser} parser
  32849. * @return {Promise<BufferGeometry>}
  32850. */
  32851. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  32852. var attributes = primitiveDef.attributes;
  32853. var pending = [];
  32854. function assignAttributeAccessor(accessorIndex, attributeName) {
  32855. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  32856. geometry.setAttribute(attributeName, accessor);
  32857. });
  32858. }
  32859. for (var gltfAttributeName in attributes) {
  32860. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  32861. if (threeAttributeName in geometry.attributes) continue;
  32862. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  32863. }
  32864. if (primitiveDef.indices !== undefined && !geometry.index) {
  32865. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  32866. geometry.setIndex(accessor);
  32867. });
  32868. pending.push(accessor);
  32869. }
  32870. assignExtrasToUserData(geometry, primitiveDef);
  32871. computeBounds(geometry, primitiveDef, parser);
  32872. return Promise.all(pending).then(function () {
  32873. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  32874. });
  32875. }
  32876. /**
  32877. * @param {BufferGeometry} geometry
  32878. * @param {Number} drawMode
  32879. * @return {BufferGeometry}
  32880. */
  32881. function toTrianglesDrawMode(geometry, drawMode) {
  32882. var index = geometry.getIndex(); // generate index if not present
  32883. if (index === null) {
  32884. var indices = [];
  32885. var position = geometry.getAttribute('position');
  32886. if (position !== undefined) {
  32887. for (var i = 0; i < position.count; i++) {
  32888. indices.push(i);
  32889. }
  32890. geometry.setIndex(indices);
  32891. index = geometry.getIndex();
  32892. } else {
  32893. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  32894. return geometry;
  32895. }
  32896. } //
  32897. var numberOfTriangles = index.count - 2;
  32898. var newIndices = [];
  32899. if (drawMode === _threeModule.TriangleFanDrawMode) {
  32900. // gl.TRIANGLE_FAN
  32901. for (var i = 1; i <= numberOfTriangles; i++) {
  32902. newIndices.push(index.getX(0));
  32903. newIndices.push(index.getX(i));
  32904. newIndices.push(index.getX(i + 1));
  32905. }
  32906. } else {
  32907. // gl.TRIANGLE_STRIP
  32908. for (var i = 0; i < numberOfTriangles; i++) {
  32909. if (i % 2 === 0) {
  32910. newIndices.push(index.getX(i));
  32911. newIndices.push(index.getX(i + 1));
  32912. newIndices.push(index.getX(i + 2));
  32913. } else {
  32914. newIndices.push(index.getX(i + 2));
  32915. newIndices.push(index.getX(i + 1));
  32916. newIndices.push(index.getX(i));
  32917. }
  32918. }
  32919. }
  32920. if (newIndices.length / 3 !== numberOfTriangles) {
  32921. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  32922. } // build final geometry
  32923. var newGeometry = geometry.clone();
  32924. newGeometry.setIndex(newIndices);
  32925. return newGeometry;
  32926. }
  32927. /**
  32928. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  32929. *
  32930. * Creates BufferGeometries from primitives.
  32931. *
  32932. * @param {Array<GLTF.Primitive>} primitives
  32933. * @return {Promise<Array<BufferGeometry>>}
  32934. */
  32935. GLTFParser.prototype.loadGeometries = function (primitives) {
  32936. var parser = this;
  32937. var extensions = this.extensions;
  32938. var cache = this.primitiveCache;
  32939. function createDracoPrimitive(primitive) {
  32940. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  32941. return addPrimitiveAttributes(geometry, primitive, parser);
  32942. });
  32943. }
  32944. var pending = [];
  32945. for (var i = 0, il = primitives.length; i < il; i++) {
  32946. var primitive = primitives[i];
  32947. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  32948. var cached = cache[cacheKey];
  32949. if (cached) {
  32950. // Use the cached geometry if it exists
  32951. pending.push(cached.promise);
  32952. } else {
  32953. var geometryPromise;
  32954. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  32955. // Use DRACO geometry if available
  32956. geometryPromise = createDracoPrimitive(primitive);
  32957. } else {
  32958. // Otherwise create a new geometry
  32959. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  32960. } // Cache this geometry
  32961. cache[cacheKey] = {
  32962. primitive: primitive,
  32963. promise: geometryPromise
  32964. };
  32965. pending.push(geometryPromise);
  32966. }
  32967. }
  32968. return Promise.all(pending);
  32969. };
  32970. /**
  32971. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  32972. * @param {number} meshIndex
  32973. * @return {Promise<Group|Mesh|SkinnedMesh>}
  32974. */
  32975. GLTFParser.prototype.loadMesh = function (meshIndex) {
  32976. var parser = this;
  32977. var json = this.json;
  32978. var meshDef = json.meshes[meshIndex];
  32979. var primitives = meshDef.primitives;
  32980. var pending = [];
  32981. for (var i = 0, il = primitives.length; i < il; i++) {
  32982. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  32983. pending.push(material);
  32984. }
  32985. pending.push(parser.loadGeometries(primitives));
  32986. return Promise.all(pending).then(function (results) {
  32987. var materials = results.slice(0, results.length - 1);
  32988. var geometries = results[results.length - 1];
  32989. var meshes = [];
  32990. for (var i = 0, il = geometries.length; i < il; i++) {
  32991. var geometry = geometries[i];
  32992. var primitive = primitives[i]; // 1. create Mesh
  32993. var mesh;
  32994. var material = materials[i];
  32995. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  32996. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  32997. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  32998. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  32999. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  33000. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  33001. mesh.normalizeSkinWeights();
  33002. }
  33003. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  33004. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleStripDrawMode);
  33005. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  33006. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleFanDrawMode);
  33007. }
  33008. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  33009. mesh = new _threeModule.LineSegments(geometry, material);
  33010. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  33011. mesh = new _threeModule.Line(geometry, material);
  33012. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  33013. mesh = new _threeModule.LineLoop(geometry, material);
  33014. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  33015. mesh = new _threeModule.Points(geometry, material);
  33016. } else {
  33017. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  33018. }
  33019. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  33020. updateMorphTargets(mesh, meshDef);
  33021. }
  33022. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  33023. if (geometries.length > 1) mesh.name += '_' + i;
  33024. assignExtrasToUserData(mesh, meshDef);
  33025. parser.assignFinalMaterial(mesh);
  33026. meshes.push(mesh);
  33027. }
  33028. if (meshes.length === 1) {
  33029. return meshes[0];
  33030. }
  33031. var group = new _threeModule.Group();
  33032. for (var i = 0, il = meshes.length; i < il; i++) {
  33033. group.add(meshes[i]);
  33034. }
  33035. return group;
  33036. });
  33037. };
  33038. /**
  33039. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  33040. * @param {number} cameraIndex
  33041. * @return {Promise<THREE.Camera>}
  33042. */
  33043. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  33044. var camera;
  33045. var cameraDef = this.json.cameras[cameraIndex];
  33046. var params = cameraDef[cameraDef.type];
  33047. if (!params) {
  33048. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  33049. return;
  33050. }
  33051. if (cameraDef.type === 'perspective') {
  33052. camera = new _threeModule.PerspectiveCamera(_threeModule.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  33053. } else if (cameraDef.type === 'orthographic') {
  33054. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  33055. }
  33056. if (cameraDef.name) camera.name = cameraDef.name;
  33057. assignExtrasToUserData(camera, cameraDef);
  33058. return Promise.resolve(camera);
  33059. };
  33060. /**
  33061. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  33062. * @param {number} skinIndex
  33063. * @return {Promise<Object>}
  33064. */
  33065. GLTFParser.prototype.loadSkin = function (skinIndex) {
  33066. var skinDef = this.json.skins[skinIndex];
  33067. var skinEntry = {
  33068. joints: skinDef.joints
  33069. };
  33070. if (skinDef.inverseBindMatrices === undefined) {
  33071. return Promise.resolve(skinEntry);
  33072. }
  33073. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  33074. skinEntry.inverseBindMatrices = accessor;
  33075. return skinEntry;
  33076. });
  33077. };
  33078. /**
  33079. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  33080. * @param {number} animationIndex
  33081. * @return {Promise<AnimationClip>}
  33082. */
  33083. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  33084. var json = this.json;
  33085. var animationDef = json.animations[animationIndex];
  33086. var pendingNodes = [];
  33087. var pendingInputAccessors = [];
  33088. var pendingOutputAccessors = [];
  33089. var pendingSamplers = [];
  33090. var pendingTargets = [];
  33091. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  33092. var channel = animationDef.channels[i];
  33093. var sampler = animationDef.samplers[channel.sampler];
  33094. var target = channel.target;
  33095. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  33096. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  33097. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  33098. pendingNodes.push(this.getDependency('node', name));
  33099. pendingInputAccessors.push(this.getDependency('accessor', input));
  33100. pendingOutputAccessors.push(this.getDependency('accessor', output));
  33101. pendingSamplers.push(sampler);
  33102. pendingTargets.push(target);
  33103. }
  33104. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  33105. var nodes = dependencies[0];
  33106. var inputAccessors = dependencies[1];
  33107. var outputAccessors = dependencies[2];
  33108. var samplers = dependencies[3];
  33109. var targets = dependencies[4];
  33110. var tracks = [];
  33111. for (var i = 0, il = nodes.length; i < il; i++) {
  33112. var node = nodes[i];
  33113. var inputAccessor = inputAccessors[i];
  33114. var outputAccessor = outputAccessors[i];
  33115. var sampler = samplers[i];
  33116. var target = targets[i];
  33117. if (node === undefined) continue;
  33118. node.updateMatrix();
  33119. node.matrixAutoUpdate = true;
  33120. var TypedKeyframeTrack;
  33121. switch (PATH_PROPERTIES[target.path]) {
  33122. case PATH_PROPERTIES.weights:
  33123. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  33124. break;
  33125. case PATH_PROPERTIES.rotation:
  33126. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  33127. break;
  33128. case PATH_PROPERTIES.position:
  33129. case PATH_PROPERTIES.scale:
  33130. default:
  33131. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  33132. break;
  33133. }
  33134. var targetName = node.name ? node.name : node.uuid;
  33135. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  33136. var targetNames = [];
  33137. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  33138. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  33139. node.traverse(function (object) {
  33140. if (object.isMesh === true && object.morphTargetInfluences) {
  33141. targetNames.push(object.name ? object.name : object.uuid);
  33142. }
  33143. });
  33144. } else {
  33145. targetNames.push(targetName);
  33146. }
  33147. var outputArray = outputAccessor.array;
  33148. if (outputAccessor.normalized) {
  33149. var scale;
  33150. if (outputArray.constructor === Int8Array) {
  33151. scale = 1 / 127;
  33152. } else if (outputArray.constructor === Uint8Array) {
  33153. scale = 1 / 255;
  33154. } else if (outputArray.constructor == Int16Array) {
  33155. scale = 1 / 32767;
  33156. } else if (outputArray.constructor === Uint16Array) {
  33157. scale = 1 / 65535;
  33158. } else {
  33159. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  33160. }
  33161. var scaled = new Float32Array(outputArray.length);
  33162. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  33163. scaled[j] = outputArray[j] * scale;
  33164. }
  33165. outputArray = scaled;
  33166. }
  33167. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  33168. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  33169. if (sampler.interpolation === 'CUBICSPLINE') {
  33170. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  33171. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  33172. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  33173. // must be divided by three to get the interpolant's sampleSize argument.
  33174. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  33175. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  33176. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  33177. }
  33178. tracks.push(track);
  33179. }
  33180. }
  33181. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  33182. return new _threeModule.AnimationClip(name, undefined, tracks);
  33183. });
  33184. };
  33185. /**
  33186. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  33187. * @param {number} nodeIndex
  33188. * @return {Promise<Object3D>}
  33189. */
  33190. GLTFParser.prototype.loadNode = function (nodeIndex) {
  33191. var json = this.json;
  33192. var extensions = this.extensions;
  33193. var parser = this;
  33194. var meshReferences = json.meshReferences;
  33195. var meshUses = json.meshUses;
  33196. var nodeDef = json.nodes[nodeIndex];
  33197. return function () {
  33198. var pending = [];
  33199. if (nodeDef.mesh !== undefined) {
  33200. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  33201. var node;
  33202. if (meshReferences[nodeDef.mesh] > 1) {
  33203. var instanceNum = meshUses[nodeDef.mesh]++;
  33204. node = mesh.clone();
  33205. node.name += '_instance_' + instanceNum;
  33206. } else {
  33207. node = mesh;
  33208. } // if weights are provided on the node, override weights on the mesh.
  33209. if (nodeDef.weights !== undefined) {
  33210. node.traverse(function (o) {
  33211. if (!o.isMesh) return;
  33212. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  33213. o.morphTargetInfluences[i] = nodeDef.weights[i];
  33214. }
  33215. });
  33216. }
  33217. return node;
  33218. }));
  33219. }
  33220. if (nodeDef.camera !== undefined) {
  33221. pending.push(parser.getDependency('camera', nodeDef.camera));
  33222. }
  33223. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  33224. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  33225. }
  33226. return Promise.all(pending);
  33227. }().then(function (objects) {
  33228. var node; // .isBone isn't in glTF spec. See .markDefs
  33229. if (nodeDef.isBone === true) {
  33230. node = new _threeModule.Bone();
  33231. } else if (objects.length > 1) {
  33232. node = new _threeModule.Group();
  33233. } else if (objects.length === 1) {
  33234. node = objects[0];
  33235. } else {
  33236. node = new _threeModule.Object3D();
  33237. }
  33238. if (node !== objects[0]) {
  33239. for (var i = 0, il = objects.length; i < il; i++) {
  33240. node.add(objects[i]);
  33241. }
  33242. }
  33243. if (nodeDef.name) {
  33244. node.userData.name = nodeDef.name;
  33245. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  33246. }
  33247. assignExtrasToUserData(node, nodeDef);
  33248. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  33249. if (nodeDef.matrix !== undefined) {
  33250. var matrix = new _threeModule.Matrix4();
  33251. matrix.fromArray(nodeDef.matrix);
  33252. node.applyMatrix4(matrix);
  33253. } else {
  33254. if (nodeDef.translation !== undefined) {
  33255. node.position.fromArray(nodeDef.translation);
  33256. }
  33257. if (nodeDef.rotation !== undefined) {
  33258. node.quaternion.fromArray(nodeDef.rotation);
  33259. }
  33260. if (nodeDef.scale !== undefined) {
  33261. node.scale.fromArray(nodeDef.scale);
  33262. }
  33263. }
  33264. return node;
  33265. });
  33266. };
  33267. /**
  33268. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  33269. * @param {number} sceneIndex
  33270. * @return {Promise<Group>}
  33271. */
  33272. GLTFParser.prototype.loadScene = function () {
  33273. // scene node hierachy builder
  33274. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  33275. var nodeDef = json.nodes[nodeId];
  33276. return parser.getDependency('node', nodeId).then(function (node) {
  33277. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  33278. var skinEntry;
  33279. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  33280. skinEntry = skin;
  33281. var pendingJoints = [];
  33282. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  33283. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  33284. }
  33285. return Promise.all(pendingJoints);
  33286. }).then(function (jointNodes) {
  33287. node.traverse(function (mesh) {
  33288. if (!mesh.isMesh) return;
  33289. var bones = [];
  33290. var boneInverses = [];
  33291. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  33292. var jointNode = jointNodes[j];
  33293. if (jointNode) {
  33294. bones.push(jointNode);
  33295. var mat = new _threeModule.Matrix4();
  33296. if (skinEntry.inverseBindMatrices !== undefined) {
  33297. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  33298. }
  33299. boneInverses.push(mat);
  33300. } else {
  33301. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  33302. }
  33303. }
  33304. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  33305. });
  33306. return node;
  33307. });
  33308. }).then(function (node) {
  33309. // build node hierachy
  33310. parentObject.add(node);
  33311. var pending = [];
  33312. if (nodeDef.children) {
  33313. var children = nodeDef.children;
  33314. for (var i = 0, il = children.length; i < il; i++) {
  33315. var child = children[i];
  33316. pending.push(buildNodeHierachy(child, node, json, parser));
  33317. }
  33318. }
  33319. return Promise.all(pending);
  33320. });
  33321. }
  33322. return function loadScene(sceneIndex) {
  33323. var json = this.json;
  33324. var extensions = this.extensions;
  33325. var sceneDef = this.json.scenes[sceneIndex];
  33326. var parser = this; // Loader returns Group, not Scene.
  33327. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  33328. var scene = new _threeModule.Group();
  33329. if (sceneDef.name) scene.name = sceneDef.name;
  33330. assignExtrasToUserData(scene, sceneDef);
  33331. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  33332. var nodeIds = sceneDef.nodes || [];
  33333. var pending = [];
  33334. for (var i = 0, il = nodeIds.length; i < il; i++) {
  33335. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  33336. }
  33337. return Promise.all(pending).then(function () {
  33338. return scene;
  33339. });
  33340. };
  33341. }();
  33342. return GLTFLoader;
  33343. }();
  33344. exports.GLTFLoader = GLTFLoader;
  33345. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  33346. "use strict";
  33347. Object.defineProperty(exports, "__esModule", {
  33348. value: true
  33349. });
  33350. exports.B3DMLoader = void 0;
  33351. var _B3DMLoaderBase = require("../base/B3DMLoaderBase.js");
  33352. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  33353. class B3DMLoader extends _B3DMLoaderBase.B3DMLoaderBase {
  33354. constructor(manager) {
  33355. super();
  33356. this.manager = manager;
  33357. }
  33358. parse(buffer) {
  33359. const b3dm = super.parse(buffer);
  33360. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  33361. return new Promise((resolve, reject) => {
  33362. const manager = this.manager;
  33363. new _GLTFLoader.GLTFLoader(manager).parse(gltfBuffer, null, model => {
  33364. model.batchTable = b3dm.batchTable;
  33365. model.featureTable = b3dm.featureTable;
  33366. resolve(model);
  33367. }, reject);
  33368. });
  33369. }
  33370. }
  33371. exports.B3DMLoader = B3DMLoader;
  33372. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  33373. "use strict";
  33374. Object.defineProperty(exports, "__esModule", {
  33375. value: true
  33376. });
  33377. exports.TilesGroup = void 0;
  33378. var _three = require("three");
  33379. // Specialization of "Group" that only updates world matrices of children if
  33380. // the transform has changed since the last update and ignores the "force"
  33381. // parameter under the assumption that the children tiles will not move.
  33382. const tempMat = new _three.Matrix4();
  33383. class TilesGroup extends _three.Group {
  33384. constructor(tilesRenderer) {
  33385. super();
  33386. this.tilesRenderer = tilesRenderer;
  33387. }
  33388. raycast(raycaster, intersects) {
  33389. this.tilesRenderer.raycast(raycaster, intersects);
  33390. }
  33391. updateMatrixWorld(force) {
  33392. if (this.matrixAutoUpdate) {
  33393. this.updateMatrix();
  33394. }
  33395. if (this.matrixWorldNeedsUpdate || force) {
  33396. if (this.parent === null) {
  33397. tempMat.copy(this.matrix);
  33398. } else {
  33399. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  33400. }
  33401. this.matrixWorldNeedsUpdate = false; // check if the matrix changed relative to what it was.
  33402. const elA = tempMat.elements;
  33403. const elB = this.matrixWorld.elements;
  33404. let isDifferent = false;
  33405. for (let i = 0; i < 16; i++) {
  33406. const itemA = elA[i];
  33407. const itemB = elB[i];
  33408. const diff = Math.abs(itemA - itemB);
  33409. if (diff > Number.EPSILON) {
  33410. isDifferent = true;
  33411. break;
  33412. }
  33413. }
  33414. if (isDifferent) {
  33415. this.matrixWorld.copy(tempMat); // update children
  33416. // the children will not have to change unless the parent group has updated
  33417. const children = this.children;
  33418. for (let i = 0, l = children.length; i < l; i++) {
  33419. children[i].updateMatrixWorld();
  33420. }
  33421. }
  33422. }
  33423. }
  33424. }
  33425. exports.TilesGroup = TilesGroup;
  33426. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  33427. "use strict";
  33428. Object.defineProperty(exports, "__esModule", {
  33429. value: true
  33430. });
  33431. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  33432. exports.raycastTraverse = raycastTraverse;
  33433. var _three = require("three");
  33434. const _sphere = new _three.Sphere();
  33435. const _mat = new _three.Matrix4();
  33436. const _vec = new _three.Vector3();
  33437. const _vec2 = new _three.Vector3();
  33438. const _ray = new _three.Ray();
  33439. const _hitArray = [];
  33440. function distanceSort(a, b) {
  33441. return a.distance - b.distance;
  33442. }
  33443. function intersectTileScene(scene, raycaster, intersects) {
  33444. // Don't intersect the box3 helpers because those are used for debugging
  33445. scene.traverse(c => {
  33446. // We set the default raycast function to empty so three.js doesn't automatically cast against it
  33447. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  33448. });
  33449. } // Returns the closest hit when traversing the tree
  33450. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  33451. // If the root is active make sure we've checked it
  33452. if (activeTiles.has(root)) {
  33453. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  33454. if (_hitArray.length > 0) {
  33455. if (_hitArray.length > 1) {
  33456. _hitArray.sort(distanceSort);
  33457. }
  33458. const res = _hitArray[0];
  33459. _hitArray.length = 0;
  33460. return res;
  33461. } else {
  33462. return null;
  33463. }
  33464. } // TODO: can we avoid creating a new array here every time to save on memory?
  33465. const array = [];
  33466. const children = root.children;
  33467. for (let i = 0, l = children.length; i < l; i++) {
  33468. const tile = children[i];
  33469. const cached = tile.cached;
  33470. const groupMatrixWorld = group.matrixWorld;
  33471. _mat.copy(groupMatrixWorld); // if we don't hit the sphere then early out
  33472. const sphere = cached.sphere;
  33473. if (sphere) {
  33474. _sphere.copy(sphere);
  33475. _sphere.applyMatrix4(_mat);
  33476. if (!raycaster.ray.intersectsSphere(_sphere)) {
  33477. continue;
  33478. }
  33479. } // TODO: check region?
  33480. const boundingBox = cached.box;
  33481. const obbMat = cached.boxTransform;
  33482. if (boundingBox) {
  33483. _mat.multiply(obbMat);
  33484. _mat.getInverse(_mat);
  33485. _ray.copy(raycaster.ray);
  33486. _ray.applyMatrix4(_mat);
  33487. if (_ray.intersectBox(boundingBox, _vec)) {
  33488. // account for tile scale
  33489. let invScale;
  33490. _vec2.setFromMatrixScale(_mat);
  33491. invScale = _vec2.x;
  33492. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  33493. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  33494. } // if we intersect the box save the distance to the tile bounds
  33495. let data = {
  33496. distance: Infinity,
  33497. tile: null
  33498. };
  33499. array.push(data);
  33500. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  33501. data.tile = tile;
  33502. } else {
  33503. continue;
  33504. }
  33505. }
  33506. } // sort them by ascending distance
  33507. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  33508. // couldn't possible include a best hit
  33509. let bestDistanceSquared = Infinity;
  33510. let bestHit = null;
  33511. for (let i = 0, l = array.length; i < l; i++) {
  33512. const data = array[i];
  33513. const distanceSquared = data.distance;
  33514. if (distanceSquared > bestDistanceSquared) {
  33515. break;
  33516. } else {
  33517. const tile = data.tile;
  33518. const scene = tile.cached.scene;
  33519. let hit = null;
  33520. if (activeTiles.has(tile)) {
  33521. // save the hit if it's closer
  33522. intersectTileScene(scene, raycaster, _hitArray);
  33523. if (_hitArray.length > 0) {
  33524. if (_hitArray.length > 1) {
  33525. _hitArray.sort(distanceSort);
  33526. }
  33527. hit = _hitArray[0];
  33528. }
  33529. } else {
  33530. hit = raycastTraverseFirstHit(tile, group, activeTiles, raycaster);
  33531. }
  33532. if (hit) {
  33533. const hitDistanceSquared = hit.distance * hit.distance;
  33534. if (hitDistanceSquared < bestDistanceSquared) {
  33535. bestDistanceSquared = hitDistanceSquared;
  33536. bestHit = hit;
  33537. }
  33538. _hitArray.length = 0;
  33539. }
  33540. }
  33541. }
  33542. return bestHit;
  33543. }
  33544. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  33545. const cached = tile.cached;
  33546. const groupMatrixWorld = group.matrixWorld;
  33547. _mat.copy(groupMatrixWorld); // Early out if we don't hit this tile sphere
  33548. const sphere = cached.sphere;
  33549. if (sphere) {
  33550. _sphere.copy(sphere);
  33551. _sphere.applyMatrix4(_mat);
  33552. if (!raycaster.ray.intersectsSphere(_sphere)) {
  33553. return;
  33554. }
  33555. } // Early out if we don't this this tile box
  33556. const boundingBox = cached.box;
  33557. const obbMat = cached.boxTransform;
  33558. if (boundingBox) {
  33559. _mat.multiply(obbMat);
  33560. _mat.getInverse(_mat);
  33561. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  33562. if (!_ray.intersectsBox(boundingBox)) {
  33563. return;
  33564. }
  33565. } // TODO: check region
  33566. const scene = cached.scene;
  33567. if (activeTiles.has(tile)) {
  33568. intersectTileScene(scene, raycaster, intersects);
  33569. return;
  33570. }
  33571. const children = tile.children;
  33572. for (let i = 0, l = children.length; i < l; i++) {
  33573. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  33574. }
  33575. }
  33576. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  33577. "use strict";
  33578. Object.defineProperty(exports, "__esModule", {
  33579. value: true
  33580. });
  33581. exports.TilesRenderer = void 0;
  33582. var _TilesRendererBase = require("../base/TilesRendererBase.js");
  33583. var _B3DMLoader = require("./B3DMLoader.js");
  33584. var _TilesGroup = require("./TilesGroup.js");
  33585. var _three = require("three");
  33586. var _raycastTraverse = require("./raycastTraverse.js");
  33587. const DEG2RAD = _three.Math.DEG2RAD;
  33588. const tempMat = new _three.Matrix4();
  33589. const tempMat2 = new _three.Matrix4();
  33590. const tempVector = new _three.Vector3();
  33591. const vecX = new _three.Vector3();
  33592. const vecY = new _three.Vector3();
  33593. const vecZ = new _three.Vector3();
  33594. const X_AXIS = new _three.Vector3(1, 0, 0);
  33595. const Y_AXIS = new _three.Vector3(0, 1, 0);
  33596. const useImageBitmap = typeof createImageBitmap !== 'undefined';
  33597. function emptyRaycast() {}
  33598. class TilesRenderer extends _TilesRendererBase.TilesRendererBase {
  33599. constructor(...args) {
  33600. super(...args);
  33601. this.group = new _TilesGroup.TilesGroup(this);
  33602. this.cameras = [];
  33603. this.cameraMap = new Map();
  33604. this.cameraInfo = [];
  33605. this.activeTiles = new Set();
  33606. this.visibleTiles = new Set();
  33607. this.onLoadModel = null;
  33608. }
  33609. /* Public API */
  33610. getBounds(box) {
  33611. if (!this.root) {
  33612. return false;
  33613. }
  33614. const cached = this.root.cached;
  33615. const boundingBox = cached.box;
  33616. const obbMat = cached.boxTransform;
  33617. if (boundingBox) {
  33618. box.copy(boundingBox);
  33619. box.applyMatrix4(obbMat);
  33620. return true;
  33621. } else {
  33622. return false;
  33623. }
  33624. }
  33625. forEachLoadedModel(callback) {
  33626. this.traverse(tile => {
  33627. const scene = tile.cached.scene;
  33628. if (scene) {
  33629. callback(scene, tile);
  33630. }
  33631. });
  33632. }
  33633. raycast(raycaster, intersects) {
  33634. if (!this.root) {
  33635. return;
  33636. }
  33637. if (raycaster.firstHitOnly) {
  33638. const hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  33639. if (hit) {
  33640. intersects.push(hit);
  33641. }
  33642. } else {
  33643. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  33644. }
  33645. }
  33646. hasCamera(camera) {
  33647. return this.cameraMap.has(camera);
  33648. }
  33649. setCamera(camera) {
  33650. const cameras = this.cameras;
  33651. const cameraMap = this.cameraMap;
  33652. if (!cameraMap.has(camera)) {
  33653. cameraMap.set(camera, new _three.Vector2());
  33654. cameras.push(camera);
  33655. return true;
  33656. }
  33657. return false;
  33658. }
  33659. setResolution(camera, xOrVec, y) {
  33660. const cameraMap = this.cameraMap;
  33661. if (!cameraMap.has(camera)) {
  33662. return false;
  33663. }
  33664. if (xOrVec instanceof _three.Vector2) {
  33665. cameraMap.get(camera).copy(xOrVec);
  33666. } else {
  33667. cameraMap.get(camera).set(xOrVec, y);
  33668. }
  33669. return true;
  33670. }
  33671. setResolutionFromRenderer(camera, renderer) {
  33672. const cameraMap = this.cameraMap;
  33673. if (!cameraMap.has(camera)) {
  33674. return false;
  33675. }
  33676. const resolution = cameraMap.get(camera);
  33677. renderer.getSize(resolution);
  33678. resolution.multiplyScalar(renderer.getPixelRatio());
  33679. return true;
  33680. }
  33681. deleteCamera(camera) {
  33682. const cameras = this.cameras;
  33683. const cameraMap = this.cameraMap;
  33684. if (cameraMap.has(camera)) {
  33685. const index = cameras.indexOf(camera);
  33686. cameras.splice(index, 1);
  33687. cameraMap.delete(camera);
  33688. return true;
  33689. }
  33690. return false;
  33691. }
  33692. /* Overriden */
  33693. update() {
  33694. const group = this.group;
  33695. const cameras = this.cameras;
  33696. const cameraMap = this.cameraMap;
  33697. const cameraInfo = this.cameraInfo;
  33698. if (cameras.length === 0) {
  33699. console.warn('TilesRenderer: no cameras defined. Cannot update 3d tiles.');
  33700. return;
  33701. } // automatically scale the array of cameraInfo to match the cameras
  33702. while (cameraInfo.length > cameras.length) {
  33703. cameraInfo.pop();
  33704. }
  33705. while (cameraInfo.length < cameras.length) {
  33706. cameraInfo.push({
  33707. frustum: new _three.Frustum(),
  33708. sseDenominator: -1,
  33709. position: new _three.Vector3(),
  33710. invScale: -1,
  33711. pixelSize: 0
  33712. });
  33713. } // extract scale of group container
  33714. tempMat2.getInverse(group.matrixWorld);
  33715. let invScale;
  33716. tempVector.setFromMatrixScale(tempMat2);
  33717. invScale = tempVector.x;
  33718. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  33719. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  33720. } // store the camera cameraInfo in the 3d tiles root frame
  33721. for (let i = 0, l = cameraInfo.length; i < l; i++) {
  33722. const camera = cameras[i];
  33723. const info = cameraInfo[i];
  33724. const frustum = info.frustum;
  33725. const position = info.position;
  33726. const resolution = cameraMap.get(camera);
  33727. if (resolution.width === 0 || resolution.height === 0) {
  33728. console.warn('TilesRenderer: resolution for camera error calculation is not set.');
  33729. }
  33730. if (camera.isPerspectiveCamera) {
  33731. info.sseDenominator = 2 * Math.tan(0.5 * camera.fov * DEG2RAD) / resolution.height;
  33732. }
  33733. if (camera.isOrthographicCamera) {
  33734. const w = camera.right - camera.left;
  33735. const h = camera.top - camera.bottom;
  33736. info.pixelSize = Math.max(h / resolution.height, w / resolution.width);
  33737. }
  33738. info.invScale = invScale; // get frustum in grop root frame
  33739. tempMat.copy(group.matrixWorld);
  33740. tempMat.premultiply(camera.matrixWorldInverse);
  33741. tempMat.premultiply(camera.projectionMatrix);
  33742. frustum.setFromProjectionMatrix(tempMat); // get transform position in group root frame
  33743. position.set(0, 0, 0);
  33744. position.applyMatrix4(camera.matrixWorld);
  33745. position.applyMatrix4(tempMat2);
  33746. }
  33747. super.update();
  33748. }
  33749. preprocessNode(tile, parentTile, tileSetDir) {
  33750. super.preprocessNode(tile, parentTile, tileSetDir);
  33751. const transform = new _three.Matrix4();
  33752. if (tile.transform) {
  33753. const transformArr = tile.transform;
  33754. for (let i = 0; i < 16; i++) {
  33755. transform.elements[i] = transformArr[i];
  33756. }
  33757. } else {
  33758. transform.identity();
  33759. }
  33760. if (parentTile) {
  33761. transform.multiply(parentTile.cached.transform);
  33762. }
  33763. let box = null;
  33764. let boxTransform = null;
  33765. let boxTransformInverse = null;
  33766. if ('box' in tile.boundingVolume) {
  33767. const data = tile.boundingVolume.box;
  33768. box = new _three.Box3();
  33769. boxTransform = new _three.Matrix4();
  33770. boxTransformInverse = new _three.Matrix4(); // get the extents of the bounds in each axis
  33771. vecX.set(data[3], data[4], data[5]);
  33772. vecY.set(data[6], data[7], data[8]);
  33773. vecZ.set(data[9], data[10], data[11]);
  33774. const scaleX = vecX.length();
  33775. const scaleY = vecY.length();
  33776. const scaleZ = vecZ.length();
  33777. vecX.normalize();
  33778. vecY.normalize();
  33779. vecZ.normalize(); // create the oriented frame that the box exists in
  33780. 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);
  33781. boxTransform.premultiply(transform);
  33782. boxTransformInverse.getInverse(boxTransform); // scale the box by the extents
  33783. box.min.set(-scaleX, -scaleY, -scaleZ);
  33784. box.max.set(scaleX, scaleY, scaleZ);
  33785. }
  33786. let sphere = null;
  33787. if ('sphere' in tile.boundingVolume) {
  33788. const data = tile.boundingVolume.sphere;
  33789. sphere = new _three.Sphere();
  33790. sphere.center.set(data[0], data[1], data[2]);
  33791. sphere.radius = data[3];
  33792. sphere.applyMatrix4(transform);
  33793. } else if ('box' in tile.boundingVolume) {
  33794. const data = tile.boundingVolume.box;
  33795. sphere = new _three.Sphere();
  33796. box.getBoundingSphere(sphere);
  33797. sphere.center.set(data[0], data[1], data[2]);
  33798. sphere.applyMatrix4(transform);
  33799. }
  33800. let region = null;
  33801. if ('region' in tile.boundingVolume) {
  33802. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  33803. }
  33804. tile.cached = {
  33805. loadIndex: 0,
  33806. transform,
  33807. active: false,
  33808. inFrustum: [],
  33809. box,
  33810. boxTransform,
  33811. boxTransformInverse,
  33812. sphere,
  33813. region,
  33814. scene: null,
  33815. geometry: null,
  33816. material: null,
  33817. distance: Infinity
  33818. };
  33819. }
  33820. parseTile(buffer, tile, extension) {
  33821. tile._loadIndex = tile._loadIndex || 0;
  33822. tile._loadIndex++;
  33823. const loadIndex = tile._loadIndex;
  33824. const manager = new _three.LoadingManager();
  33825. let promise = null;
  33826. if (useImageBitmap) {
  33827. // TODO: We should verify that `flipY` is false on the resulting texture after load because it can't be modified after
  33828. // the fact. Premultiply alpha default behavior is not well defined, either.
  33829. // TODO: Determine whether or not options are supported before using this so we can force flipY false and premultiply alpha
  33830. // behavior. Fall back to regular texture loading
  33831. manager.addHandler(/(^blob:)|(\.png$)|(\.jpg$)|(\.jpeg$)/g, {
  33832. load(url, onComplete) {
  33833. const loader = new _three.ImageBitmapLoader();
  33834. loader.load(url, res => {
  33835. onComplete(new _three.CanvasTexture(res));
  33836. });
  33837. }
  33838. });
  33839. }
  33840. switch (extension) {
  33841. case 'b3dm':
  33842. promise = new _B3DMLoader.B3DMLoader(manager).parse(buffer);
  33843. break;
  33844. case 'pnts':
  33845. case 'cmpt':
  33846. case 'i3dm':
  33847. default:
  33848. console.warn(`TilesRenderer: Content type "${extension}" not supported.`);
  33849. promise = Promise.resolve(null);
  33850. break;
  33851. }
  33852. return promise.then(res => {
  33853. if (tile._loadIndex !== loadIndex) {
  33854. return;
  33855. }
  33856. const upAxis = this.rootTileSet.asset && this.rootTileSet.asset.gltfUpAxis || 'y';
  33857. const cached = tile.cached;
  33858. const cachedTransform = cached.transform;
  33859. const scene = res ? res.scene : new _three.Group();
  33860. switch (upAxis.toLowerCase()) {
  33861. case 'x':
  33862. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  33863. break;
  33864. case 'y':
  33865. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  33866. break;
  33867. case 'z':
  33868. break;
  33869. }
  33870. scene.matrix.premultiply(cachedTransform);
  33871. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  33872. scene.traverse(c => c.frustumCulled = false);
  33873. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  33874. scene.traverse(c => {
  33875. c.raycast = emptyRaycast;
  33876. });
  33877. const materials = [];
  33878. const geometry = [];
  33879. const textures = [];
  33880. scene.traverse(c => {
  33881. if (c.geometry) {
  33882. geometry.push(c.geometry);
  33883. }
  33884. if (c.material) {
  33885. const material = c.material;
  33886. materials.push(c.material);
  33887. for (const key in material) {
  33888. const value = material[key];
  33889. if (value && value.isTexture) {
  33890. textures.push(value);
  33891. }
  33892. }
  33893. }
  33894. });
  33895. cached.materials = materials;
  33896. cached.geometry = geometry;
  33897. cached.textures = textures;
  33898. if (this.onLoadModel) {
  33899. this.onLoadModel(scene, tile);
  33900. }
  33901. });
  33902. }
  33903. disposeTile(tile) {
  33904. // This could get called before the tile has finished downloading
  33905. const cached = tile.cached;
  33906. if (cached.scene) {
  33907. const materials = cached.materials;
  33908. const geometry = cached.geometry;
  33909. const textures = cached.textures;
  33910. for (let i = 0, l = geometry.length; i < l; i++) {
  33911. geometry[i].dispose();
  33912. }
  33913. for (let i = 0, l = materials.length; i < l; i++) {
  33914. materials[i].dispose();
  33915. }
  33916. for (let i = 0, l = textures.length; i < l; i++) {
  33917. const texture = textures[i];
  33918. texture.dispose();
  33919. if (useImageBitmap && 'close' in texture.image) {
  33920. texture.image.close();
  33921. }
  33922. }
  33923. cached.scene = null;
  33924. cached.materials = null;
  33925. cached.textures = null;
  33926. cached.geometry = null;
  33927. }
  33928. tile._loadIndex++;
  33929. }
  33930. setTileVisible(tile, visible) {
  33931. const scene = tile.cached.scene;
  33932. const visibleTiles = this.visibleTiles;
  33933. const group = this.group;
  33934. if (visible) {
  33935. group.add(scene);
  33936. visibleTiles.add(tile);
  33937. scene.updateMatrixWorld(true);
  33938. } else {
  33939. group.remove(scene);
  33940. visibleTiles.delete(tile);
  33941. }
  33942. }
  33943. setTileActive(tile, active) {
  33944. const activeTiles = this.activeTiles;
  33945. if (active) {
  33946. activeTiles.add(tile);
  33947. } else {
  33948. activeTiles.delete(tile);
  33949. }
  33950. }
  33951. calculateError(tile) {
  33952. if (tile.geometricError === 0.0) {
  33953. return 0.0;
  33954. }
  33955. const cached = tile.cached;
  33956. const inFrustum = cached.inFrustum;
  33957. const cameras = this.cameras;
  33958. const cameraInfo = this.cameraInfo; // TODO: Use the content bounding volume here?
  33959. const boundingVolume = tile.boundingVolume;
  33960. if ('box' in boundingVolume) {
  33961. const boundingBox = cached.box;
  33962. const boxTransformInverse = cached.boxTransformInverse;
  33963. let maxError = -Infinity;
  33964. let minDistance = Infinity;
  33965. for (let i = 0, l = cameras.length; i < l; i++) {
  33966. if (!inFrustum[i]) {
  33967. continue;
  33968. } // transform camera position into local frame of the tile bounding box
  33969. const camera = cameras[i];
  33970. const info = cameraInfo[i];
  33971. const invScale = info.invScale;
  33972. tempVector.copy(info.position);
  33973. tempVector.applyMatrix4(boxTransformInverse);
  33974. let error;
  33975. if (camera.isOrthographicCamera) {
  33976. const pixelSize = info.pixelSize;
  33977. error = tile.geometricError / (pixelSize * invScale);
  33978. } else {
  33979. const distance = boundingBox.distanceToPoint(tempVector);
  33980. const scaledDistance = distance * invScale;
  33981. const sseDenominator = info.sseDenominator;
  33982. error = tile.geometricError / (scaledDistance * sseDenominator);
  33983. minDistance = Math.min(minDistance, scaledDistance);
  33984. }
  33985. maxError = Math.max(maxError, error);
  33986. }
  33987. tile.cached.distance = minDistance;
  33988. return maxError;
  33989. } else if ('sphere' in boundingVolume) {
  33990. // const sphere = cached.sphere;
  33991. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  33992. } else if ('region' in boundingVolume) {
  33993. // unsupported
  33994. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  33995. }
  33996. return Infinity;
  33997. }
  33998. tileInView(tile) {
  33999. // TODO: we should use the more precise bounding volumes here if possible
  34000. // cache the root-space planes
  34001. // Use separating axis theorem for frustum and obb
  34002. const cached = tile.cached;
  34003. const sphere = cached.sphere;
  34004. const inFrustum = cached.inFrustum;
  34005. if (sphere) {
  34006. const cameraInfo = this.cameraInfo;
  34007. let inView = false;
  34008. for (let i = 0, l = cameraInfo.length; i < l; i++) {
  34009. // Track which camera frustums this tile is in so we can use it
  34010. // to ignore the error calculations for cameras that can't see it
  34011. const frustum = cameraInfo[i].frustum;
  34012. if (frustum.intersectsSphere(sphere)) {
  34013. inView = true;
  34014. inFrustum[i] = true;
  34015. } else {
  34016. inFrustum[i] = false;
  34017. }
  34018. }
  34019. return inView;
  34020. }
  34021. return true;
  34022. }
  34023. }
  34024. exports.TilesRenderer = TilesRenderer;
  34025. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.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) {
  34026. "use strict";
  34027. Object.defineProperty(exports, "__esModule", {
  34028. value: true
  34029. });
  34030. exports.SphereHelper = void 0;
  34031. var _three = require("three");
  34032. const _vector = new _three.Vector3();
  34033. const axes = ['x', 'y', 'z'];
  34034. class SphereHelper extends _three.LineSegments {
  34035. constructor(sphere, color = 0xffff00, angleSteps = 40) {
  34036. const geometry = new _three.BufferGeometry();
  34037. const positions = [];
  34038. for (let i = 0; i < 3; i++) {
  34039. const axis1 = axes[i];
  34040. const axis2 = axes[(i + 1) % 3];
  34041. _vector.set(0, 0, 0);
  34042. for (let a = 0; a < angleSteps; a++) {
  34043. let angle;
  34044. angle = 2 * Math.PI * a / (angleSteps - 1);
  34045. _vector[axis1] = Math.sin(angle);
  34046. _vector[axis2] = Math.cos(angle);
  34047. positions.push(_vector.x, _vector.y, _vector.z);
  34048. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  34049. _vector[axis1] = Math.sin(angle);
  34050. _vector[axis2] = Math.cos(angle);
  34051. positions.push(_vector.x, _vector.y, _vector.z);
  34052. }
  34053. }
  34054. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  34055. geometry.computeBoundingSphere();
  34056. super(geometry, new _three.LineBasicMaterial({
  34057. color: color,
  34058. toneMapped: false
  34059. }));
  34060. this.sphere = sphere;
  34061. this.type = 'SphereHelper';
  34062. }
  34063. updateMatrixWorld(force) {
  34064. const sphere = this.sphere;
  34065. this.position.copy(sphere.center);
  34066. this.scale.setScalar(sphere.radius);
  34067. super.updateMatrixWorld(force);
  34068. }
  34069. }
  34070. exports.SphereHelper = SphereHelper;
  34071. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  34072. "use strict";
  34073. Object.defineProperty(exports, "__esModule", {
  34074. value: true
  34075. });
  34076. 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;
  34077. var _three = require("three");
  34078. var _TilesRenderer = require("./TilesRenderer.js");
  34079. var _SphereHelper = require("./SphereHelper.js");
  34080. const ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  34081. const HAS_RANDOM_COLOR = Symbol('HAS_RANDOM_COLOR');
  34082. function emptyRaycast() {}
  34083. const NONE = 0;
  34084. exports.NONE = NONE;
  34085. const SCREEN_ERROR = 1;
  34086. exports.SCREEN_ERROR = SCREEN_ERROR;
  34087. const GEOMETRIC_ERROR = 2;
  34088. exports.GEOMETRIC_ERROR = GEOMETRIC_ERROR;
  34089. const DISTANCE = 3;
  34090. exports.DISTANCE = DISTANCE;
  34091. const DEPTH = 4;
  34092. exports.DEPTH = DEPTH;
  34093. const RELATIVE_DEPTH = 5;
  34094. exports.RELATIVE_DEPTH = RELATIVE_DEPTH;
  34095. const IS_LEAF = 6;
  34096. exports.IS_LEAF = IS_LEAF;
  34097. const RANDOM_COLOR = 7;
  34098. exports.RANDOM_COLOR = RANDOM_COLOR;
  34099. class DebugTilesRenderer extends _TilesRenderer.TilesRenderer {
  34100. constructor(...args) {
  34101. super(...args);
  34102. const tilesGroup = this.group;
  34103. const boxGroup = new _three.Group();
  34104. tilesGroup.add(boxGroup);
  34105. const sphereGroup = new _three.Group();
  34106. tilesGroup.add(sphereGroup);
  34107. this.displayBoxBounds = false;
  34108. this.displaySphereBounds = false;
  34109. this.colorMode = NONE;
  34110. this.boxGroup = boxGroup;
  34111. this.sphereGroup = sphereGroup;
  34112. this.maxDebugDepth = -1;
  34113. this.maxDebugDistance = -1;
  34114. this.maxDebugError = -1;
  34115. this.extremeDebugDepth = -1;
  34116. this.extremeDebugError = -1;
  34117. }
  34118. initExtremes() {
  34119. // initialize the extreme values of the hierarchy
  34120. let maxDepth = -1;
  34121. this.traverse(tile => {
  34122. maxDepth = Math.max(maxDepth, tile.__depth);
  34123. });
  34124. let maxError = -1;
  34125. this.traverse(tile => {
  34126. maxError = Math.max(maxError, tile.geometricError);
  34127. });
  34128. this.extremeDebugDepth = maxDepth;
  34129. this.extremeDebugError = maxError;
  34130. }
  34131. loadTileSet(...args) {
  34132. const pr = super.loadTileSet(...args);
  34133. pr.then(() => this.initExtremes());
  34134. return pr;
  34135. }
  34136. getTileInformationFromActiveObject(object) {
  34137. // Find which tile this scene is associated with. This is slow and
  34138. // intended for debug purposes only.
  34139. let targetTile = null;
  34140. const activeTiles = this.activeTiles;
  34141. activeTiles.forEach(tile => {
  34142. if (targetTile) {
  34143. return true;
  34144. }
  34145. const scene = tile.cached.scene;
  34146. if (scene) {
  34147. scene.traverse(c => {
  34148. if (c === object) {
  34149. targetTile = tile;
  34150. }
  34151. });
  34152. }
  34153. });
  34154. if (targetTile) {
  34155. return {
  34156. distanceToCamera: targetTile.cached.distance,
  34157. geometricError: targetTile.geometricError,
  34158. screenSpaceError: targetTile.__error,
  34159. depth: targetTile.__depth,
  34160. isLeaf: targetTile.__isLeaf
  34161. };
  34162. } else {
  34163. return null;
  34164. }
  34165. }
  34166. update() {
  34167. super.update();
  34168. if (!this.root) {
  34169. return;
  34170. } // set box or sphere visibility
  34171. this.boxGroup.visible = this.displayBoxBounds;
  34172. this.sphereGroup.visible = this.displaySphereBounds; // get max values to use for materials
  34173. let maxDepth = -1;
  34174. if (this.maxDebugDepth === -1) {
  34175. maxDepth = this.extremeDebugDepth;
  34176. } else {
  34177. maxDepth = this.maxDebugDepth;
  34178. }
  34179. let maxError = -1;
  34180. if (this.maxDebugError === -1) {
  34181. maxError = this.extremeDebugError;
  34182. } else {
  34183. maxError = this.maxDebugError;
  34184. }
  34185. let maxDistance = -1;
  34186. if (this.maxDebugDistance === -1) {
  34187. maxDistance = this.root.cached.sphere.radius;
  34188. } else {
  34189. maxDistance = this.maxDebugDistance;
  34190. }
  34191. const errorTarget = this.errorTarget;
  34192. const colorMode = this.colorMode;
  34193. const visibleTiles = this.visibleTiles;
  34194. visibleTiles.forEach(tile => {
  34195. const scene = tile.cached.scene;
  34196. scene.traverse(c => {
  34197. const currMaterial = c.material;
  34198. if (currMaterial) {
  34199. // Reset the material if needed
  34200. const originalMaterial = c[ORIGINAL_MATERIAL];
  34201. if (colorMode === NONE && currMaterial !== originalMaterial) {
  34202. c.material.dispose();
  34203. c.material = c[ORIGINAL_MATERIAL];
  34204. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  34205. c.material = new _three.MeshBasicMaterial();
  34206. }
  34207. if (colorMode !== RANDOM_COLOR) {
  34208. delete c.material[HAS_RANDOM_COLOR];
  34209. } // Set the color on the basic material
  34210. switch (colorMode) {
  34211. case DEPTH:
  34212. {
  34213. const val = tile.__depth / maxDepth;
  34214. c.material.color.setRGB(val, val, val);
  34215. break;
  34216. }
  34217. case RELATIVE_DEPTH:
  34218. {
  34219. const val = tile.__depthFromRenderedParent / maxDepth;
  34220. c.material.color.setRGB(val, val, val);
  34221. break;
  34222. }
  34223. case SCREEN_ERROR:
  34224. {
  34225. const val = tile.__error / errorTarget;
  34226. if (val > 1.0) {
  34227. c.material.color.setRGB(1.0, 0.0, 0.0);
  34228. } else {
  34229. c.material.color.setRGB(val, val, val);
  34230. }
  34231. break;
  34232. }
  34233. case GEOMETRIC_ERROR:
  34234. {
  34235. const val = Math.min(tile.geometricError / maxError, 1);
  34236. c.material.color.setRGB(val, val, val);
  34237. break;
  34238. }
  34239. case DISTANCE:
  34240. {
  34241. // We don't update the distance if the geometric error is 0.0 so
  34242. // it will always be black.
  34243. const val = Math.min(tile.cached.distance / maxDistance, 1);
  34244. c.material.color.setRGB(val, val, val);
  34245. break;
  34246. }
  34247. case IS_LEAF:
  34248. {
  34249. if (!tile.children || tile.children.length === 0) {
  34250. c.material.color.set(0xffffff);
  34251. } else {
  34252. c.material.color.set(0);
  34253. }
  34254. break;
  34255. }
  34256. case RANDOM_COLOR:
  34257. {
  34258. if (!c.material[HAS_RANDOM_COLOR]) {
  34259. const h = Math.random();
  34260. const s = 0.5 + Math.random() * 0.5;
  34261. const l = 0.375 + Math.random() * 0.25;
  34262. c.material.color.setHSL(h, s, l);
  34263. c.material[HAS_RANDOM_COLOR] = true;
  34264. }
  34265. break;
  34266. }
  34267. }
  34268. }
  34269. });
  34270. });
  34271. }
  34272. setTileVisible(tile, visible) {
  34273. super.setTileVisible(tile, visible);
  34274. const cached = tile.cached;
  34275. const sphereGroup = this.sphereGroup;
  34276. const boxGroup = this.boxGroup;
  34277. const boxHelperGroup = cached.boxHelperGroup;
  34278. const sphereHelper = cached.sphereHelper;
  34279. if (!visible) {
  34280. boxGroup.remove(boxHelperGroup);
  34281. sphereGroup.remove(sphereHelper);
  34282. } else {
  34283. boxGroup.add(boxHelperGroup);
  34284. boxHelperGroup.updateMatrixWorld(true);
  34285. sphereGroup.add(sphereHelper);
  34286. sphereHelper.updateMatrixWorld(true);
  34287. }
  34288. }
  34289. parseTile(buffer, tile, extension) {
  34290. return super.parseTile(buffer, tile, extension).then(() => {
  34291. const cached = tile.cached;
  34292. const scene = cached.scene;
  34293. if (scene) {
  34294. const cachedBox = cached.box;
  34295. const cachedBoxMat = cached.boxTransform; // Create debug bounding box
  34296. const boxHelperGroup = new _three.Group();
  34297. boxHelperGroup.matrix.copy(cachedBoxMat);
  34298. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  34299. const boxHelper = new _three.Box3Helper(cachedBox);
  34300. boxHelper.raycast = emptyRaycast;
  34301. boxHelperGroup.add(boxHelper);
  34302. cached.boxHelperGroup = boxHelperGroup;
  34303. if (this.visibleTiles.has(tile) && this.displayBoxBounds) {
  34304. this.boxGroup.add(boxHelperGroup);
  34305. boxHelperGroup.updateMatrixWorld(true);
  34306. } // Create debugbounding sphere
  34307. const cachedSphere = cached.sphere;
  34308. const sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  34309. sphereHelper.raycast = emptyRaycast;
  34310. cached.sphereHelper = sphereHelper;
  34311. if (this.visibleTiles.has(tile) && this.displaySphereBounds) {
  34312. this.sphereGroup.add(sphereHelper);
  34313. sphereHelper.updateMatrixWorld(true);
  34314. } // Cache the original materials
  34315. scene.traverse(c => {
  34316. const material = c.material;
  34317. if (material) {
  34318. c[ORIGINAL_MATERIAL] = material;
  34319. }
  34320. });
  34321. }
  34322. });
  34323. }
  34324. disposeTile(tile) {
  34325. super.disposeTile(tile);
  34326. const cached = tile.cached;
  34327. if (cached.boxHelperGroup) {
  34328. cached.boxHelperGroup.children[0].geometry.dispose();
  34329. cached.sphereHelper.geometry.dispose();
  34330. delete cached.boxHelperGroup;
  34331. delete cached.sphereHelper;
  34332. }
  34333. }
  34334. }
  34335. exports.DebugTilesRenderer = DebugTilesRenderer;
  34336. },{"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) {
  34337. "use strict";
  34338. Object.defineProperty(exports, "__esModule", {
  34339. value: true
  34340. });
  34341. Object.defineProperty(exports, "DebugTilesRenderer", {
  34342. enumerable: true,
  34343. get: function () {
  34344. return _DebugTilesRenderer.DebugTilesRenderer;
  34345. }
  34346. });
  34347. Object.defineProperty(exports, "NONE", {
  34348. enumerable: true,
  34349. get: function () {
  34350. return _DebugTilesRenderer.NONE;
  34351. }
  34352. });
  34353. Object.defineProperty(exports, "SCREEN_ERROR", {
  34354. enumerable: true,
  34355. get: function () {
  34356. return _DebugTilesRenderer.SCREEN_ERROR;
  34357. }
  34358. });
  34359. Object.defineProperty(exports, "GEOMETRIC_ERROR", {
  34360. enumerable: true,
  34361. get: function () {
  34362. return _DebugTilesRenderer.GEOMETRIC_ERROR;
  34363. }
  34364. });
  34365. Object.defineProperty(exports, "DISTANCE", {
  34366. enumerable: true,
  34367. get: function () {
  34368. return _DebugTilesRenderer.DISTANCE;
  34369. }
  34370. });
  34371. Object.defineProperty(exports, "DEPTH", {
  34372. enumerable: true,
  34373. get: function () {
  34374. return _DebugTilesRenderer.DEPTH;
  34375. }
  34376. });
  34377. Object.defineProperty(exports, "RELATIVE_DEPTH", {
  34378. enumerable: true,
  34379. get: function () {
  34380. return _DebugTilesRenderer.RELATIVE_DEPTH;
  34381. }
  34382. });
  34383. Object.defineProperty(exports, "IS_LEAF", {
  34384. enumerable: true,
  34385. get: function () {
  34386. return _DebugTilesRenderer.IS_LEAF;
  34387. }
  34388. });
  34389. Object.defineProperty(exports, "RANDOM_COLOR", {
  34390. enumerable: true,
  34391. get: function () {
  34392. return _DebugTilesRenderer.RANDOM_COLOR;
  34393. }
  34394. });
  34395. Object.defineProperty(exports, "TilesRenderer", {
  34396. enumerable: true,
  34397. get: function () {
  34398. return _TilesRenderer.TilesRenderer;
  34399. }
  34400. });
  34401. Object.defineProperty(exports, "B3DMLoader", {
  34402. enumerable: true,
  34403. get: function () {
  34404. return _B3DMLoader.B3DMLoader;
  34405. }
  34406. });
  34407. Object.defineProperty(exports, "TilesRendererBase", {
  34408. enumerable: true,
  34409. get: function () {
  34410. return _TilesRendererBase.TilesRendererBase;
  34411. }
  34412. });
  34413. Object.defineProperty(exports, "B3DMLoaderBase", {
  34414. enumerable: true,
  34415. get: function () {
  34416. return _B3DMLoaderBase.B3DMLoaderBase;
  34417. }
  34418. });
  34419. Object.defineProperty(exports, "LRUCache", {
  34420. enumerable: true,
  34421. get: function () {
  34422. return _LRUCache.LRUCache;
  34423. }
  34424. });
  34425. Object.defineProperty(exports, "PriorityQueue", {
  34426. enumerable: true,
  34427. get: function () {
  34428. return _PriorityQueue.PriorityQueue;
  34429. }
  34430. });
  34431. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  34432. var _TilesRenderer = require("./three/TilesRenderer.js");
  34433. var _B3DMLoader = require("./three/B3DMLoader.js");
  34434. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  34435. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  34436. var _LRUCache = require("./utilities/LRUCache.js");
  34437. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  34438. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.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) {
  34439. "use strict";
  34440. Object.defineProperty(exports, "__esModule", {
  34441. value: true
  34442. });
  34443. exports.MapControls = exports.OrbitControls = void 0;
  34444. var _threeModule = require("../../../build/three.module.js");
  34445. /**
  34446. * @author qiao / https://github.com/qiao
  34447. * @author mrdoob / http://mrdoob.com
  34448. * @author alteredq / http://alteredqualia.com/
  34449. * @author WestLangley / http://github.com/WestLangley
  34450. * @author erich666 / http://erichaines.com
  34451. * @author ScieCode / http://github.com/sciecode
  34452. */
  34453. // This set of controls performs orbiting, dollying (zooming), and panning.
  34454. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  34455. //
  34456. // Orbit - left mouse / touch: one-finger move
  34457. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  34458. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  34459. var OrbitControls = function (object, domElement) {
  34460. if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
  34461. if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
  34462. this.object = object;
  34463. this.domElement = domElement; // Set to false to disable this control
  34464. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  34465. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  34466. this.minDistance = 0;
  34467. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  34468. this.minZoom = 0;
  34469. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  34470. // Range is 0 to Math.PI radians.
  34471. this.minPolarAngle = 0; // radians
  34472. this.maxPolarAngle = Math.PI; // radians
  34473. // How far you can orbit horizontally, upper and lower limits.
  34474. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  34475. this.minAzimuthAngle = -Infinity; // radians
  34476. this.maxAzimuthAngle = Infinity; // radians
  34477. // Set to true to enable damping (inertia)
  34478. // If damping is enabled, you must call controls.update() in your animation loop
  34479. this.enableDamping = false;
  34480. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  34481. // Set to false to disable zooming
  34482. this.enableZoom = true;
  34483. this.zoomSpeed = 1.0; // Set to false to disable rotating
  34484. this.enableRotate = true;
  34485. this.rotateSpeed = 1.0; // Set to false to disable panning
  34486. this.enablePan = true;
  34487. this.panSpeed = 1.0;
  34488. this.screenSpacePanning = false; // if true, pan in screen-space
  34489. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  34490. // Set to true to automatically rotate around the target
  34491. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  34492. this.autoRotate = false;
  34493. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  34494. // Set to false to disable use of the keys
  34495. this.enableKeys = true; // The four arrow keys
  34496. this.keys = {
  34497. LEFT: 37,
  34498. UP: 38,
  34499. RIGHT: 39,
  34500. BOTTOM: 40
  34501. }; // Mouse buttons
  34502. this.mouseButtons = {
  34503. LEFT: _threeModule.MOUSE.ROTATE,
  34504. MIDDLE: _threeModule.MOUSE.DOLLY,
  34505. RIGHT: _threeModule.MOUSE.PAN
  34506. }; // Touch fingers
  34507. this.touches = {
  34508. ONE: _threeModule.TOUCH.ROTATE,
  34509. TWO: _threeModule.TOUCH.DOLLY_PAN
  34510. }; // for reset
  34511. this.target0 = this.target.clone();
  34512. this.position0 = this.object.position.clone();
  34513. this.zoom0 = this.object.zoom; //
  34514. // public methods
  34515. //
  34516. this.getPolarAngle = function () {
  34517. return spherical.phi;
  34518. };
  34519. this.getAzimuthalAngle = function () {
  34520. return spherical.theta;
  34521. };
  34522. this.saveState = function () {
  34523. scope.target0.copy(scope.target);
  34524. scope.position0.copy(scope.object.position);
  34525. scope.zoom0 = scope.object.zoom;
  34526. };
  34527. this.reset = function () {
  34528. scope.target.copy(scope.target0);
  34529. scope.object.position.copy(scope.position0);
  34530. scope.object.zoom = scope.zoom0;
  34531. scope.object.updateProjectionMatrix();
  34532. scope.dispatchEvent(changeEvent);
  34533. scope.update();
  34534. state = STATE.NONE;
  34535. }; // this method is exposed, but perhaps it would be better if we can make it private...
  34536. this.update = function () {
  34537. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  34538. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  34539. var quatInverse = quat.clone().inverse();
  34540. var lastPosition = new _threeModule.Vector3();
  34541. var lastQuaternion = new _threeModule.Quaternion();
  34542. return function update() {
  34543. var position = scope.object.position;
  34544. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  34545. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  34546. spherical.setFromVector3(offset);
  34547. if (scope.autoRotate && state === STATE.NONE) {
  34548. rotateLeft(getAutoRotationAngle());
  34549. }
  34550. if (scope.enableDamping) {
  34551. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  34552. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  34553. } else {
  34554. spherical.theta += sphericalDelta.theta;
  34555. spherical.phi += sphericalDelta.phi;
  34556. } // restrict theta to be between desired limits
  34557. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  34558. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  34559. spherical.makeSafe();
  34560. spherical.radius *= scale; // restrict radius to be between desired limits
  34561. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  34562. if (scope.enableDamping === true) {
  34563. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  34564. } else {
  34565. scope.target.add(panOffset);
  34566. }
  34567. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  34568. offset.applyQuaternion(quatInverse);
  34569. position.copy(scope.target).add(offset);
  34570. scope.object.lookAt(scope.target);
  34571. if (scope.enableDamping === true) {
  34572. sphericalDelta.theta *= 1 - scope.dampingFactor;
  34573. sphericalDelta.phi *= 1 - scope.dampingFactor;
  34574. panOffset.multiplyScalar(1 - scope.dampingFactor);
  34575. } else {
  34576. sphericalDelta.set(0, 0, 0);
  34577. panOffset.set(0, 0, 0);
  34578. }
  34579. scale = 1; // update condition is:
  34580. // min(camera displacement, camera rotation in radians)^2 > EPS
  34581. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  34582. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  34583. scope.dispatchEvent(changeEvent);
  34584. lastPosition.copy(scope.object.position);
  34585. lastQuaternion.copy(scope.object.quaternion);
  34586. zoomChanged = false;
  34587. return true;
  34588. }
  34589. return false;
  34590. };
  34591. }();
  34592. this.dispose = function () {
  34593. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  34594. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  34595. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  34596. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  34597. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  34598. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  34599. document.removeEventListener('mousemove', onMouseMove, false);
  34600. document.removeEventListener('mouseup', onMouseUp, false);
  34601. scope.domElement.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  34602. }; //
  34603. // internals
  34604. //
  34605. var scope = this;
  34606. var changeEvent = {
  34607. type: 'change'
  34608. };
  34609. var startEvent = {
  34610. type: 'start'
  34611. };
  34612. var endEvent = {
  34613. type: 'end'
  34614. };
  34615. var STATE = {
  34616. NONE: -1,
  34617. ROTATE: 0,
  34618. DOLLY: 1,
  34619. PAN: 2,
  34620. TOUCH_ROTATE: 3,
  34621. TOUCH_PAN: 4,
  34622. TOUCH_DOLLY_PAN: 5,
  34623. TOUCH_DOLLY_ROTATE: 6
  34624. };
  34625. var state = STATE.NONE;
  34626. var EPS = 0.000001; // current position in spherical coordinates
  34627. var spherical = new _threeModule.Spherical();
  34628. var sphericalDelta = new _threeModule.Spherical();
  34629. var scale = 1;
  34630. var panOffset = new _threeModule.Vector3();
  34631. var zoomChanged = false;
  34632. var rotateStart = new _threeModule.Vector2();
  34633. var rotateEnd = new _threeModule.Vector2();
  34634. var rotateDelta = new _threeModule.Vector2();
  34635. var panStart = new _threeModule.Vector2();
  34636. var panEnd = new _threeModule.Vector2();
  34637. var panDelta = new _threeModule.Vector2();
  34638. var dollyStart = new _threeModule.Vector2();
  34639. var dollyEnd = new _threeModule.Vector2();
  34640. var dollyDelta = new _threeModule.Vector2();
  34641. function getAutoRotationAngle() {
  34642. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  34643. }
  34644. function getZoomScale() {
  34645. return Math.pow(0.95, scope.zoomSpeed);
  34646. }
  34647. function rotateLeft(angle) {
  34648. sphericalDelta.theta -= angle;
  34649. }
  34650. function rotateUp(angle) {
  34651. sphericalDelta.phi -= angle;
  34652. }
  34653. var panLeft = function () {
  34654. var v = new _threeModule.Vector3();
  34655. return function panLeft(distance, objectMatrix) {
  34656. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  34657. v.multiplyScalar(-distance);
  34658. panOffset.add(v);
  34659. };
  34660. }();
  34661. var panUp = function () {
  34662. var v = new _threeModule.Vector3();
  34663. return function panUp(distance, objectMatrix) {
  34664. if (scope.screenSpacePanning === true) {
  34665. v.setFromMatrixColumn(objectMatrix, 1);
  34666. } else {
  34667. v.setFromMatrixColumn(objectMatrix, 0);
  34668. v.crossVectors(scope.object.up, v);
  34669. }
  34670. v.multiplyScalar(distance);
  34671. panOffset.add(v);
  34672. };
  34673. }(); // deltaX and deltaY are in pixels; right and down are positive
  34674. var pan = function () {
  34675. var offset = new _threeModule.Vector3();
  34676. return function pan(deltaX, deltaY) {
  34677. var element = scope.domElement;
  34678. if (scope.object.isPerspectiveCamera) {
  34679. // perspective
  34680. var position = scope.object.position;
  34681. offset.copy(position).sub(scope.target);
  34682. var targetDistance = offset.length(); // half of the fov is center to top of screen
  34683. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  34684. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  34685. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  34686. } else if (scope.object.isOrthographicCamera) {
  34687. // orthographic
  34688. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  34689. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  34690. } else {
  34691. // camera neither orthographic nor perspective
  34692. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  34693. scope.enablePan = false;
  34694. }
  34695. };
  34696. }();
  34697. function dollyOut(dollyScale) {
  34698. if (scope.object.isPerspectiveCamera) {
  34699. scale /= dollyScale;
  34700. } else if (scope.object.isOrthographicCamera) {
  34701. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  34702. scope.object.updateProjectionMatrix();
  34703. zoomChanged = true;
  34704. } else {
  34705. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  34706. scope.enableZoom = false;
  34707. }
  34708. }
  34709. function dollyIn(dollyScale) {
  34710. if (scope.object.isPerspectiveCamera) {
  34711. scale *= dollyScale;
  34712. } else if (scope.object.isOrthographicCamera) {
  34713. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  34714. scope.object.updateProjectionMatrix();
  34715. zoomChanged = true;
  34716. } else {
  34717. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  34718. scope.enableZoom = false;
  34719. }
  34720. } //
  34721. // event callbacks - update the object state
  34722. //
  34723. function handleMouseDownRotate(event) {
  34724. rotateStart.set(event.clientX, event.clientY);
  34725. }
  34726. function handleMouseDownDolly(event) {
  34727. dollyStart.set(event.clientX, event.clientY);
  34728. }
  34729. function handleMouseDownPan(event) {
  34730. panStart.set(event.clientX, event.clientY);
  34731. }
  34732. function handleMouseMoveRotate(event) {
  34733. rotateEnd.set(event.clientX, event.clientY);
  34734. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  34735. var element = scope.domElement;
  34736. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  34737. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  34738. rotateStart.copy(rotateEnd);
  34739. scope.update();
  34740. }
  34741. function handleMouseMoveDolly(event) {
  34742. dollyEnd.set(event.clientX, event.clientY);
  34743. dollyDelta.subVectors(dollyEnd, dollyStart);
  34744. if (dollyDelta.y > 0) {
  34745. dollyOut(getZoomScale());
  34746. } else if (dollyDelta.y < 0) {
  34747. dollyIn(getZoomScale());
  34748. }
  34749. dollyStart.copy(dollyEnd);
  34750. scope.update();
  34751. }
  34752. function handleMouseMovePan(event) {
  34753. panEnd.set(event.clientX, event.clientY);
  34754. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  34755. pan(panDelta.x, panDelta.y);
  34756. panStart.copy(panEnd);
  34757. scope.update();
  34758. }
  34759. function handleMouseUp()
  34760. /*event*/
  34761. {// no-op
  34762. }
  34763. function handleMouseWheel(event) {
  34764. if (event.deltaY < 0) {
  34765. dollyIn(getZoomScale());
  34766. } else if (event.deltaY > 0) {
  34767. dollyOut(getZoomScale());
  34768. }
  34769. scope.update();
  34770. }
  34771. function handleKeyDown(event) {
  34772. var needsUpdate = false;
  34773. switch (event.keyCode) {
  34774. case scope.keys.UP:
  34775. pan(0, scope.keyPanSpeed);
  34776. needsUpdate = true;
  34777. break;
  34778. case scope.keys.BOTTOM:
  34779. pan(0, -scope.keyPanSpeed);
  34780. needsUpdate = true;
  34781. break;
  34782. case scope.keys.LEFT:
  34783. pan(scope.keyPanSpeed, 0);
  34784. needsUpdate = true;
  34785. break;
  34786. case scope.keys.RIGHT:
  34787. pan(-scope.keyPanSpeed, 0);
  34788. needsUpdate = true;
  34789. break;
  34790. }
  34791. if (needsUpdate) {
  34792. // prevent the browser from scrolling on cursor keys
  34793. event.preventDefault();
  34794. scope.update();
  34795. }
  34796. }
  34797. function handleTouchStartRotate(event) {
  34798. if (event.touches.length == 1) {
  34799. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  34800. } else {
  34801. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34802. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34803. rotateStart.set(x, y);
  34804. }
  34805. }
  34806. function handleTouchStartPan(event) {
  34807. if (event.touches.length == 1) {
  34808. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  34809. } else {
  34810. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34811. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34812. panStart.set(x, y);
  34813. }
  34814. }
  34815. function handleTouchStartDolly(event) {
  34816. var dx = event.touches[0].pageX - event.touches[1].pageX;
  34817. var dy = event.touches[0].pageY - event.touches[1].pageY;
  34818. var distance = Math.sqrt(dx * dx + dy * dy);
  34819. dollyStart.set(0, distance);
  34820. }
  34821. function handleTouchStartDollyPan(event) {
  34822. if (scope.enableZoom) handleTouchStartDolly(event);
  34823. if (scope.enablePan) handleTouchStartPan(event);
  34824. }
  34825. function handleTouchStartDollyRotate(event) {
  34826. if (scope.enableZoom) handleTouchStartDolly(event);
  34827. if (scope.enableRotate) handleTouchStartRotate(event);
  34828. }
  34829. function handleTouchMoveRotate(event) {
  34830. if (event.touches.length == 1) {
  34831. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  34832. } else {
  34833. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34834. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34835. rotateEnd.set(x, y);
  34836. }
  34837. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  34838. var element = scope.domElement;
  34839. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  34840. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  34841. rotateStart.copy(rotateEnd);
  34842. }
  34843. function handleTouchMovePan(event) {
  34844. if (event.touches.length == 1) {
  34845. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  34846. } else {
  34847. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34848. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34849. panEnd.set(x, y);
  34850. }
  34851. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  34852. pan(panDelta.x, panDelta.y);
  34853. panStart.copy(panEnd);
  34854. }
  34855. function handleTouchMoveDolly(event) {
  34856. var dx = event.touches[0].pageX - event.touches[1].pageX;
  34857. var dy = event.touches[0].pageY - event.touches[1].pageY;
  34858. var distance = Math.sqrt(dx * dx + dy * dy);
  34859. dollyEnd.set(0, distance);
  34860. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  34861. dollyOut(dollyDelta.y);
  34862. dollyStart.copy(dollyEnd);
  34863. }
  34864. function handleTouchMoveDollyPan(event) {
  34865. if (scope.enableZoom) handleTouchMoveDolly(event);
  34866. if (scope.enablePan) handleTouchMovePan(event);
  34867. }
  34868. function handleTouchMoveDollyRotate(event) {
  34869. if (scope.enableZoom) handleTouchMoveDolly(event);
  34870. if (scope.enableRotate) handleTouchMoveRotate(event);
  34871. }
  34872. function handleTouchEnd()
  34873. /*event*/
  34874. {} // no-op
  34875. //
  34876. // event handlers - FSM: listen for events and reset state
  34877. //
  34878. function onMouseDown(event) {
  34879. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  34880. event.preventDefault(); // Manually set the focus since calling preventDefault above
  34881. // prevents the browser from setting it automatically.
  34882. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  34883. var mouseAction;
  34884. switch (event.button) {
  34885. case 0:
  34886. mouseAction = scope.mouseButtons.LEFT;
  34887. break;
  34888. case 1:
  34889. mouseAction = scope.mouseButtons.MIDDLE;
  34890. break;
  34891. case 2:
  34892. mouseAction = scope.mouseButtons.RIGHT;
  34893. break;
  34894. default:
  34895. mouseAction = -1;
  34896. }
  34897. switch (mouseAction) {
  34898. case _threeModule.MOUSE.DOLLY:
  34899. if (scope.enableZoom === false) return;
  34900. handleMouseDownDolly(event);
  34901. state = STATE.DOLLY;
  34902. break;
  34903. case _threeModule.MOUSE.ROTATE:
  34904. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  34905. if (scope.enablePan === false) return;
  34906. handleMouseDownPan(event);
  34907. state = STATE.PAN;
  34908. } else {
  34909. if (scope.enableRotate === false) return;
  34910. handleMouseDownRotate(event);
  34911. state = STATE.ROTATE;
  34912. }
  34913. break;
  34914. case _threeModule.MOUSE.PAN:
  34915. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  34916. if (scope.enableRotate === false) return;
  34917. handleMouseDownRotate(event);
  34918. state = STATE.ROTATE;
  34919. } else {
  34920. if (scope.enablePan === false) return;
  34921. handleMouseDownPan(event);
  34922. state = STATE.PAN;
  34923. }
  34924. break;
  34925. default:
  34926. state = STATE.NONE;
  34927. }
  34928. if (state !== STATE.NONE) {
  34929. document.addEventListener('mousemove', onMouseMove, false);
  34930. document.addEventListener('mouseup', onMouseUp, false);
  34931. scope.dispatchEvent(startEvent);
  34932. }
  34933. }
  34934. function onMouseMove(event) {
  34935. if (scope.enabled === false) return;
  34936. event.preventDefault();
  34937. switch (state) {
  34938. case STATE.ROTATE:
  34939. if (scope.enableRotate === false) return;
  34940. handleMouseMoveRotate(event);
  34941. break;
  34942. case STATE.DOLLY:
  34943. if (scope.enableZoom === false) return;
  34944. handleMouseMoveDolly(event);
  34945. break;
  34946. case STATE.PAN:
  34947. if (scope.enablePan === false) return;
  34948. handleMouseMovePan(event);
  34949. break;
  34950. }
  34951. }
  34952. function onMouseUp(event) {
  34953. if (scope.enabled === false) return;
  34954. handleMouseUp(event);
  34955. document.removeEventListener('mousemove', onMouseMove, false);
  34956. document.removeEventListener('mouseup', onMouseUp, false);
  34957. scope.dispatchEvent(endEvent);
  34958. state = STATE.NONE;
  34959. }
  34960. function onMouseWheel(event) {
  34961. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  34962. event.preventDefault();
  34963. event.stopPropagation();
  34964. scope.dispatchEvent(startEvent);
  34965. handleMouseWheel(event);
  34966. scope.dispatchEvent(endEvent);
  34967. }
  34968. function onKeyDown(event) {
  34969. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  34970. handleKeyDown(event);
  34971. }
  34972. function onTouchStart(event) {
  34973. if (scope.enabled === false) return;
  34974. event.preventDefault(); // prevent scrolling
  34975. switch (event.touches.length) {
  34976. case 1:
  34977. switch (scope.touches.ONE) {
  34978. case _threeModule.TOUCH.ROTATE:
  34979. if (scope.enableRotate === false) return;
  34980. handleTouchStartRotate(event);
  34981. state = STATE.TOUCH_ROTATE;
  34982. break;
  34983. case _threeModule.TOUCH.PAN:
  34984. if (scope.enablePan === false) return;
  34985. handleTouchStartPan(event);
  34986. state = STATE.TOUCH_PAN;
  34987. break;
  34988. default:
  34989. state = STATE.NONE;
  34990. }
  34991. break;
  34992. case 2:
  34993. switch (scope.touches.TWO) {
  34994. case _threeModule.TOUCH.DOLLY_PAN:
  34995. if (scope.enableZoom === false && scope.enablePan === false) return;
  34996. handleTouchStartDollyPan(event);
  34997. state = STATE.TOUCH_DOLLY_PAN;
  34998. break;
  34999. case _threeModule.TOUCH.DOLLY_ROTATE:
  35000. if (scope.enableZoom === false && scope.enableRotate === false) return;
  35001. handleTouchStartDollyRotate(event);
  35002. state = STATE.TOUCH_DOLLY_ROTATE;
  35003. break;
  35004. default:
  35005. state = STATE.NONE;
  35006. }
  35007. break;
  35008. default:
  35009. state = STATE.NONE;
  35010. }
  35011. if (state !== STATE.NONE) {
  35012. scope.dispatchEvent(startEvent);
  35013. }
  35014. }
  35015. function onTouchMove(event) {
  35016. if (scope.enabled === false) return;
  35017. event.preventDefault(); // prevent scrolling
  35018. event.stopPropagation();
  35019. switch (state) {
  35020. case STATE.TOUCH_ROTATE:
  35021. if (scope.enableRotate === false) return;
  35022. handleTouchMoveRotate(event);
  35023. scope.update();
  35024. break;
  35025. case STATE.TOUCH_PAN:
  35026. if (scope.enablePan === false) return;
  35027. handleTouchMovePan(event);
  35028. scope.update();
  35029. break;
  35030. case STATE.TOUCH_DOLLY_PAN:
  35031. if (scope.enableZoom === false && scope.enablePan === false) return;
  35032. handleTouchMoveDollyPan(event);
  35033. scope.update();
  35034. break;
  35035. case STATE.TOUCH_DOLLY_ROTATE:
  35036. if (scope.enableZoom === false && scope.enableRotate === false) return;
  35037. handleTouchMoveDollyRotate(event);
  35038. scope.update();
  35039. break;
  35040. default:
  35041. state = STATE.NONE;
  35042. }
  35043. }
  35044. function onTouchEnd(event) {
  35045. if (scope.enabled === false) return;
  35046. handleTouchEnd(event);
  35047. scope.dispatchEvent(endEvent);
  35048. state = STATE.NONE;
  35049. }
  35050. function onContextMenu(event) {
  35051. if (scope.enabled === false) return;
  35052. event.preventDefault();
  35053. } //
  35054. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  35055. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  35056. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  35057. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  35058. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  35059. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  35060. scope.domElement.addEventListener('keydown', onKeyDown, false); // make sure element can receive keys.
  35061. if (scope.domElement.tabIndex === -1) {
  35062. scope.domElement.tabIndex = 0;
  35063. } // force an update at start
  35064. this.update();
  35065. };
  35066. exports.OrbitControls = OrbitControls;
  35067. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  35068. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  35069. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  35070. // This is very similar to OrbitControls, another set of touch behavior
  35071. //
  35072. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  35073. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  35074. // Pan - left mouse, or arrow keys / touch: one-finger move
  35075. var MapControls = function (object, domElement) {
  35076. OrbitControls.call(this, object, domElement);
  35077. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  35078. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  35079. this.touches.ONE = _threeModule.TOUCH.PAN;
  35080. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  35081. };
  35082. exports.MapControls = MapControls;
  35083. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  35084. MapControls.prototype.constructor = MapControls;
  35085. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js":[function(require,module,exports) {
  35086. "use strict";
  35087. Object.defineProperty(exports, "__esModule", {
  35088. value: true
  35089. });
  35090. exports.BufferGeometryUtils = void 0;
  35091. var _threeModule = require("../../../build/three.module.js");
  35092. /**
  35093. * @author mrdoob / http://mrdoob.com/
  35094. */
  35095. var BufferGeometryUtils = {
  35096. computeTangents: function (geometry) {
  35097. var index = geometry.index;
  35098. var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html
  35099. // (per vertex tangents)
  35100. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  35101. console.warn('THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()');
  35102. return;
  35103. }
  35104. var indices = index.array;
  35105. var positions = attributes.position.array;
  35106. var normals = attributes.normal.array;
  35107. var uvs = attributes.uv.array;
  35108. var nVertices = positions.length / 3;
  35109. if (attributes.tangent === undefined) {
  35110. geometry.setAttribute('tangent', new _threeModule.BufferAttribute(new Float32Array(4 * nVertices), 4));
  35111. }
  35112. var tangents = attributes.tangent.array;
  35113. var tan1 = [],
  35114. tan2 = [];
  35115. for (var i = 0; i < nVertices; i++) {
  35116. tan1[i] = new _threeModule.Vector3();
  35117. tan2[i] = new _threeModule.Vector3();
  35118. }
  35119. var vA = new _threeModule.Vector3(),
  35120. vB = new _threeModule.Vector3(),
  35121. vC = new _threeModule.Vector3(),
  35122. uvA = new _threeModule.Vector2(),
  35123. uvB = new _threeModule.Vector2(),
  35124. uvC = new _threeModule.Vector2(),
  35125. sdir = new _threeModule.Vector3(),
  35126. tdir = new _threeModule.Vector3();
  35127. function handleTriangle(a, b, c) {
  35128. vA.fromArray(positions, a * 3);
  35129. vB.fromArray(positions, b * 3);
  35130. vC.fromArray(positions, c * 3);
  35131. uvA.fromArray(uvs, a * 2);
  35132. uvB.fromArray(uvs, b * 2);
  35133. uvC.fromArray(uvs, c * 2);
  35134. vB.sub(vA);
  35135. vC.sub(vA);
  35136. uvB.sub(uvA);
  35137. uvC.sub(uvA);
  35138. var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  35139. if (!isFinite(r)) return;
  35140. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  35141. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  35142. tan1[a].add(sdir);
  35143. tan1[b].add(sdir);
  35144. tan1[c].add(sdir);
  35145. tan2[a].add(tdir);
  35146. tan2[b].add(tdir);
  35147. tan2[c].add(tdir);
  35148. }
  35149. var groups = geometry.groups;
  35150. if (groups.length === 0) {
  35151. groups = [{
  35152. start: 0,
  35153. count: indices.length
  35154. }];
  35155. }
  35156. for (var i = 0, il = groups.length; i < il; ++i) {
  35157. var group = groups[i];
  35158. var start = group.start;
  35159. var count = group.count;
  35160. for (var j = start, jl = start + count; j < jl; j += 3) {
  35161. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  35162. }
  35163. }
  35164. var tmp = new _threeModule.Vector3(),
  35165. tmp2 = new _threeModule.Vector3();
  35166. var n = new _threeModule.Vector3(),
  35167. n2 = new _threeModule.Vector3();
  35168. var w, t, test;
  35169. function handleVertex(v) {
  35170. n.fromArray(normals, v * 3);
  35171. n2.copy(n);
  35172. t = tan1[v]; // Gram-Schmidt orthogonalize
  35173. tmp.copy(t);
  35174. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  35175. tmp2.crossVectors(n2, t);
  35176. test = tmp2.dot(tan2[v]);
  35177. w = test < 0.0 ? -1.0 : 1.0;
  35178. tangents[v * 4] = tmp.x;
  35179. tangents[v * 4 + 1] = tmp.y;
  35180. tangents[v * 4 + 2] = tmp.z;
  35181. tangents[v * 4 + 3] = w;
  35182. }
  35183. for (var i = 0, il = groups.length; i < il; ++i) {
  35184. var group = groups[i];
  35185. var start = group.start;
  35186. var count = group.count;
  35187. for (var j = start, jl = start + count; j < jl; j += 3) {
  35188. handleVertex(indices[j + 0]);
  35189. handleVertex(indices[j + 1]);
  35190. handleVertex(indices[j + 2]);
  35191. }
  35192. }
  35193. },
  35194. /**
  35195. * @param {Array<BufferGeometry>} geometries
  35196. * @param {Boolean} useGroups
  35197. * @return {BufferGeometry}
  35198. */
  35199. mergeBufferGeometries: function (geometries, useGroups) {
  35200. var isIndexed = geometries[0].index !== null;
  35201. var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  35202. var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  35203. var attributes = {};
  35204. var morphAttributes = {};
  35205. var morphTargetsRelative = geometries[0].morphTargetsRelative;
  35206. var mergedGeometry = new _threeModule.BufferGeometry();
  35207. var offset = 0;
  35208. for (var i = 0; i < geometries.length; ++i) {
  35209. var geometry = geometries[i]; // ensure that all geometries are indexed, or none
  35210. if (isIndexed !== (geometry.index !== null)) return null; // gather attributes, exit early if they're different
  35211. for (var name in geometry.attributes) {
  35212. if (!attributesUsed.has(name)) return null;
  35213. if (attributes[name] === undefined) attributes[name] = [];
  35214. attributes[name].push(geometry.attributes[name]);
  35215. } // gather morph attributes, exit early if they're different
  35216. if (morphTargetsRelative !== geometry.morphTargetsRelative) return null;
  35217. for (var name in geometry.morphAttributes) {
  35218. if (!morphAttributesUsed.has(name)) return null;
  35219. if (morphAttributes[name] === undefined) morphAttributes[name] = [];
  35220. morphAttributes[name].push(geometry.morphAttributes[name]);
  35221. } // gather .userData
  35222. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  35223. mergedGeometry.userData.mergedUserData.push(geometry.userData);
  35224. if (useGroups) {
  35225. var count;
  35226. if (isIndexed) {
  35227. count = geometry.index.count;
  35228. } else if (geometry.attributes.position !== undefined) {
  35229. count = geometry.attributes.position.count;
  35230. } else {
  35231. return null;
  35232. }
  35233. mergedGeometry.addGroup(offset, count, i);
  35234. offset += count;
  35235. }
  35236. } // merge indices
  35237. if (isIndexed) {
  35238. var indexOffset = 0;
  35239. var mergedIndex = [];
  35240. for (var i = 0; i < geometries.length; ++i) {
  35241. var index = geometries[i].index;
  35242. for (var j = 0; j < index.count; ++j) {
  35243. mergedIndex.push(index.getX(j) + indexOffset);
  35244. }
  35245. indexOffset += geometries[i].attributes.position.count;
  35246. }
  35247. mergedGeometry.setIndex(mergedIndex);
  35248. } // merge attributes
  35249. for (var name in attributes) {
  35250. var mergedAttribute = this.mergeBufferAttributes(attributes[name]);
  35251. if (!mergedAttribute) return null;
  35252. mergedGeometry.setAttribute(name, mergedAttribute);
  35253. } // merge morph attributes
  35254. for (var name in morphAttributes) {
  35255. var numMorphTargets = morphAttributes[name][0].length;
  35256. if (numMorphTargets === 0) break;
  35257. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  35258. mergedGeometry.morphAttributes[name] = [];
  35259. for (var i = 0; i < numMorphTargets; ++i) {
  35260. var morphAttributesToMerge = [];
  35261. for (var j = 0; j < morphAttributes[name].length; ++j) {
  35262. morphAttributesToMerge.push(morphAttributes[name][j][i]);
  35263. }
  35264. var mergedMorphAttribute = this.mergeBufferAttributes(morphAttributesToMerge);
  35265. if (!mergedMorphAttribute) return null;
  35266. mergedGeometry.morphAttributes[name].push(mergedMorphAttribute);
  35267. }
  35268. }
  35269. return mergedGeometry;
  35270. },
  35271. /**
  35272. * @param {Array<BufferAttribute>} attributes
  35273. * @return {BufferAttribute}
  35274. */
  35275. mergeBufferAttributes: function (attributes) {
  35276. var TypedArray;
  35277. var itemSize;
  35278. var normalized;
  35279. var arrayLength = 0;
  35280. for (var i = 0; i < attributes.length; ++i) {
  35281. var attribute = attributes[i];
  35282. if (attribute.isInterleavedBufferAttribute) return null;
  35283. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  35284. if (TypedArray !== attribute.array.constructor) return null;
  35285. if (itemSize === undefined) itemSize = attribute.itemSize;
  35286. if (itemSize !== attribute.itemSize) return null;
  35287. if (normalized === undefined) normalized = attribute.normalized;
  35288. if (normalized !== attribute.normalized) return null;
  35289. arrayLength += attribute.array.length;
  35290. }
  35291. var array = new TypedArray(arrayLength);
  35292. var offset = 0;
  35293. for (var i = 0; i < attributes.length; ++i) {
  35294. array.set(attributes[i].array, offset);
  35295. offset += attributes[i].array.length;
  35296. }
  35297. return new _threeModule.BufferAttribute(array, itemSize, normalized);
  35298. },
  35299. /**
  35300. * @param {Array<BufferAttribute>} attributes
  35301. * @return {Array<InterleavedBufferAttribute>}
  35302. */
  35303. interleaveAttributes: function (attributes) {
  35304. // Interleaves the provided attributes into an InterleavedBuffer and returns
  35305. // a set of InterleavedBufferAttributes for each attribute
  35306. var TypedArray;
  35307. var arrayLength = 0;
  35308. var stride = 0; // calculate the the length and type of the interleavedBuffer
  35309. for (var i = 0, l = attributes.length; i < l; ++i) {
  35310. var attribute = attributes[i];
  35311. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  35312. if (TypedArray !== attribute.array.constructor) {
  35313. console.warn('AttributeBuffers of different types cannot be interleaved');
  35314. return null;
  35315. }
  35316. arrayLength += attribute.array.length;
  35317. stride += attribute.itemSize;
  35318. } // Create the set of buffer attributes
  35319. var interleavedBuffer = new _threeModule.InterleavedBuffer(new TypedArray(arrayLength), stride);
  35320. var offset = 0;
  35321. var res = [];
  35322. var getters = ['getX', 'getY', 'getZ', 'getW'];
  35323. var setters = ['setX', 'setY', 'setZ', 'setW'];
  35324. for (var j = 0, l = attributes.length; j < l; j++) {
  35325. var attribute = attributes[j];
  35326. var itemSize = attribute.itemSize;
  35327. var count = attribute.count;
  35328. var iba = new _threeModule.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
  35329. res.push(iba);
  35330. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  35331. // at the appropriate offset
  35332. for (var c = 0; c < count; c++) {
  35333. for (var k = 0; k < itemSize; k++) {
  35334. iba[setters[k]](c, attribute[getters[k]](c));
  35335. }
  35336. }
  35337. }
  35338. return res;
  35339. },
  35340. /**
  35341. * @param {Array<BufferGeometry>} geometry
  35342. * @return {number}
  35343. */
  35344. estimateBytesUsed: function (geometry) {
  35345. // Return the estimated memory used by this geometry in bytes
  35346. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  35347. // for InterleavedBufferAttributes.
  35348. var mem = 0;
  35349. for (var name in geometry.attributes) {
  35350. var attr = geometry.getAttribute(name);
  35351. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  35352. }
  35353. var indices = geometry.getIndex();
  35354. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  35355. return mem;
  35356. },
  35357. /**
  35358. * @param {BufferGeometry} geometry
  35359. * @param {number} tolerance
  35360. * @return {BufferGeometry>}
  35361. */
  35362. mergeVertices: function (geometry, tolerance = 1e-4) {
  35363. tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it
  35364. // if it's already available.
  35365. var hashToIndex = {};
  35366. var indices = geometry.getIndex();
  35367. var positions = geometry.getAttribute('position');
  35368. var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  35369. var nextIndex = 0; // attributes and new attribute arrays
  35370. var attributeNames = Object.keys(geometry.attributes);
  35371. var attrArrays = {};
  35372. var morphAttrsArrays = {};
  35373. var newIndices = [];
  35374. var getters = ['getX', 'getY', 'getZ', 'getW']; // initialize the arrays
  35375. for (var i = 0, l = attributeNames.length; i < l; i++) {
  35376. var name = attributeNames[i];
  35377. attrArrays[name] = [];
  35378. var morphAttr = geometry.morphAttributes[name];
  35379. if (morphAttr) {
  35380. morphAttrsArrays[name] = new Array(morphAttr.length).fill().map(() => []);
  35381. }
  35382. } // convert the error tolerance to an amount of decimal places to truncate to
  35383. var decimalShift = Math.log10(1 / tolerance);
  35384. var shiftMultiplier = Math.pow(10, decimalShift);
  35385. for (var i = 0; i < vertexCount; i++) {
  35386. var index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'
  35387. var hash = '';
  35388. for (var j = 0, l = attributeNames.length; j < l; j++) {
  35389. var name = attributeNames[j];
  35390. var attribute = geometry.getAttribute(name);
  35391. var itemSize = attribute.itemSize;
  35392. for (var k = 0; k < itemSize; k++) {
  35393. // double tilde truncates the decimal value
  35394. hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`;
  35395. }
  35396. } // Add another reference to the vertex if it's already
  35397. // used by another index
  35398. if (hash in hashToIndex) {
  35399. newIndices.push(hashToIndex[hash]);
  35400. } else {
  35401. // copy data to the new index in the attribute arrays
  35402. for (var j = 0, l = attributeNames.length; j < l; j++) {
  35403. var name = attributeNames[j];
  35404. var attribute = geometry.getAttribute(name);
  35405. var morphAttr = geometry.morphAttributes[name];
  35406. var itemSize = attribute.itemSize;
  35407. var newarray = attrArrays[name];
  35408. var newMorphArrays = morphAttrsArrays[name];
  35409. for (var k = 0; k < itemSize; k++) {
  35410. var getterFunc = getters[k];
  35411. newarray.push(attribute[getterFunc](index));
  35412. if (morphAttr) {
  35413. for (var m = 0, ml = morphAttr.length; m < ml; m++) {
  35414. newMorphArrays[m].push(morphAttr[m][getterFunc](index));
  35415. }
  35416. }
  35417. }
  35418. }
  35419. hashToIndex[hash] = nextIndex;
  35420. newIndices.push(nextIndex);
  35421. nextIndex++;
  35422. }
  35423. } // Generate typed arrays from new attribute arrays and update
  35424. // the attributeBuffers
  35425. const result = geometry.clone();
  35426. for (var i = 0, l = attributeNames.length; i < l; i++) {
  35427. var name = attributeNames[i];
  35428. var oldAttribute = geometry.getAttribute(name);
  35429. var buffer = new oldAttribute.array.constructor(attrArrays[name]);
  35430. var attribute = new _threeModule.BufferAttribute(buffer, oldAttribute.itemSize, oldAttribute.normalized);
  35431. result.setAttribute(name, attribute); // Update the attribute arrays
  35432. if (name in morphAttrsArrays) {
  35433. for (var j = 0; j < morphAttrsArrays[name].length; j++) {
  35434. var oldMorphAttribute = geometry.morphAttributes[name][j];
  35435. var buffer = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]);
  35436. var morphAttribute = new _threeModule.BufferAttribute(buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized);
  35437. result.morphAttributes[name][j] = morphAttribute;
  35438. }
  35439. }
  35440. } // indices
  35441. result.setIndex(newIndices);
  35442. return result;
  35443. },
  35444. /**
  35445. * @param {BufferGeometry} geometry
  35446. * @param {number} drawMode
  35447. * @return {BufferGeometry>}
  35448. */
  35449. toTrianglesDrawMode: function (geometry, drawMode) {
  35450. if (drawMode === _threeModule.TrianglesDrawMode) {
  35451. console.warn('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.');
  35452. return geometry;
  35453. }
  35454. if (drawMode === _threeModule.TriangleFanDrawMode || drawMode === _threeModule.TriangleStripDrawMode) {
  35455. var index = geometry.getIndex(); // generate index if not present
  35456. if (index === null) {
  35457. var indices = [];
  35458. var position = geometry.getAttribute('position');
  35459. if (position !== undefined) {
  35460. for (var i = 0; i < position.count; i++) {
  35461. indices.push(i);
  35462. }
  35463. geometry.setIndex(indices);
  35464. index = geometry.getIndex();
  35465. } else {
  35466. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  35467. return geometry;
  35468. }
  35469. } //
  35470. var numberOfTriangles = index.count - 2;
  35471. var newIndices = [];
  35472. if (drawMode === _threeModule.TriangleFanDrawMode) {
  35473. // gl.TRIANGLE_FAN
  35474. for (var i = 1; i <= numberOfTriangles; i++) {
  35475. newIndices.push(index.getX(0));
  35476. newIndices.push(index.getX(i));
  35477. newIndices.push(index.getX(i + 1));
  35478. }
  35479. } else {
  35480. // gl.TRIANGLE_STRIP
  35481. for (var i = 0; i < numberOfTriangles; i++) {
  35482. if (i % 2 === 0) {
  35483. newIndices.push(index.getX(i));
  35484. newIndices.push(index.getX(i + 1));
  35485. newIndices.push(index.getX(i + 2));
  35486. } else {
  35487. newIndices.push(index.getX(i + 2));
  35488. newIndices.push(index.getX(i + 1));
  35489. newIndices.push(index.getX(i));
  35490. }
  35491. }
  35492. }
  35493. if (newIndices.length / 3 !== numberOfTriangles) {
  35494. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  35495. } // build final geometry
  35496. var newGeometry = geometry.clone();
  35497. newGeometry.setIndex(newIndices);
  35498. newGeometry.clearGroups();
  35499. return newGeometry;
  35500. } else {
  35501. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode);
  35502. return geometry;
  35503. }
  35504. }
  35505. };
  35506. exports.BufferGeometryUtils = BufferGeometryUtils;
  35507. },{"../../../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) {
  35508. "use strict";
  35509. Object.defineProperty(exports, "__esModule", {
  35510. value: true
  35511. });
  35512. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  35513. /**
  35514. * dat-gui JavaScript Controller Library
  35515. * http://code.google.com/p/dat-gui
  35516. *
  35517. * Copyright 2011 Data Arts Team, Google Creative Lab
  35518. *
  35519. * Licensed under the Apache License, Version 2.0 (the "License");
  35520. * you may not use this file except in compliance with the License.
  35521. * You may obtain a copy of the License at
  35522. *
  35523. * http://www.apache.org/licenses/LICENSE-2.0
  35524. */
  35525. function ___$insertStyle(css) {
  35526. if (!css) {
  35527. return;
  35528. }
  35529. if (typeof window === 'undefined') {
  35530. return;
  35531. }
  35532. var style = document.createElement('style');
  35533. style.setAttribute('type', 'text/css');
  35534. style.innerHTML = css;
  35535. document.head.appendChild(style);
  35536. return css;
  35537. }
  35538. function colorToString(color, forceCSSHex) {
  35539. var colorFormat = color.__state.conversionName.toString();
  35540. var r = Math.round(color.r);
  35541. var g = Math.round(color.g);
  35542. var b = Math.round(color.b);
  35543. var a = color.a;
  35544. var h = Math.round(color.h);
  35545. var s = color.s.toFixed(1);
  35546. var v = color.v.toFixed(1);
  35547. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  35548. var str = color.hex.toString(16);
  35549. while (str.length < 6) {
  35550. str = '0' + str;
  35551. }
  35552. return '#' + str;
  35553. } else if (colorFormat === 'CSS_RGB') {
  35554. return 'rgb(' + r + ',' + g + ',' + b + ')';
  35555. } else if (colorFormat === 'CSS_RGBA') {
  35556. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  35557. } else if (colorFormat === 'HEX') {
  35558. return '0x' + color.hex.toString(16);
  35559. } else if (colorFormat === 'RGB_ARRAY') {
  35560. return '[' + r + ',' + g + ',' + b + ']';
  35561. } else if (colorFormat === 'RGBA_ARRAY') {
  35562. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  35563. } else if (colorFormat === 'RGB_OBJ') {
  35564. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  35565. } else if (colorFormat === 'RGBA_OBJ') {
  35566. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  35567. } else if (colorFormat === 'HSV_OBJ') {
  35568. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  35569. } else if (colorFormat === 'HSVA_OBJ') {
  35570. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  35571. }
  35572. return 'unknown format';
  35573. }
  35574. var ARR_EACH = Array.prototype.forEach;
  35575. var ARR_SLICE = Array.prototype.slice;
  35576. var Common = {
  35577. BREAK: {},
  35578. extend: function extend(target) {
  35579. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  35580. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  35581. keys.forEach(function (key) {
  35582. if (!this.isUndefined(obj[key])) {
  35583. target[key] = obj[key];
  35584. }
  35585. }.bind(this));
  35586. }, this);
  35587. return target;
  35588. },
  35589. defaults: function defaults(target) {
  35590. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  35591. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  35592. keys.forEach(function (key) {
  35593. if (this.isUndefined(target[key])) {
  35594. target[key] = obj[key];
  35595. }
  35596. }.bind(this));
  35597. }, this);
  35598. return target;
  35599. },
  35600. compose: function compose() {
  35601. var toCall = ARR_SLICE.call(arguments);
  35602. return function () {
  35603. var args = ARR_SLICE.call(arguments);
  35604. for (var i = toCall.length - 1; i >= 0; i--) {
  35605. args = [toCall[i].apply(this, args)];
  35606. }
  35607. return args[0];
  35608. };
  35609. },
  35610. each: function each(obj, itr, scope) {
  35611. if (!obj) {
  35612. return;
  35613. }
  35614. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  35615. obj.forEach(itr, scope);
  35616. } else if (obj.length === obj.length + 0) {
  35617. var key = void 0;
  35618. var l = void 0;
  35619. for (key = 0, l = obj.length; key < l; key++) {
  35620. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  35621. return;
  35622. }
  35623. }
  35624. } else {
  35625. for (var _key in obj) {
  35626. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  35627. return;
  35628. }
  35629. }
  35630. }
  35631. },
  35632. defer: function defer(fnc) {
  35633. setTimeout(fnc, 0);
  35634. },
  35635. debounce: function debounce(func, threshold, callImmediately) {
  35636. var timeout = void 0;
  35637. return function () {
  35638. var obj = this;
  35639. var args = arguments;
  35640. function delayed() {
  35641. timeout = null;
  35642. if (!callImmediately) func.apply(obj, args);
  35643. }
  35644. var callNow = callImmediately || !timeout;
  35645. clearTimeout(timeout);
  35646. timeout = setTimeout(delayed, threshold);
  35647. if (callNow) {
  35648. func.apply(obj, args);
  35649. }
  35650. };
  35651. },
  35652. toArray: function toArray(obj) {
  35653. if (obj.toArray) return obj.toArray();
  35654. return ARR_SLICE.call(obj);
  35655. },
  35656. isUndefined: function isUndefined(obj) {
  35657. return obj === undefined;
  35658. },
  35659. isNull: function isNull(obj) {
  35660. return obj === null;
  35661. },
  35662. isNaN: function (_isNaN) {
  35663. function isNaN() {
  35664. return _isNaN.apply(this, arguments);
  35665. }
  35666. isNaN.toString = function () {
  35667. return _isNaN.toString();
  35668. };
  35669. return isNaN;
  35670. }(function (obj) {
  35671. return isNaN(obj);
  35672. }),
  35673. isArray: Array.isArray || function (obj) {
  35674. return obj.constructor === Array;
  35675. },
  35676. isObject: function isObject(obj) {
  35677. return obj === Object(obj);
  35678. },
  35679. isNumber: function isNumber(obj) {
  35680. return obj === obj + 0;
  35681. },
  35682. isString: function isString(obj) {
  35683. return obj === obj + '';
  35684. },
  35685. isBoolean: function isBoolean(obj) {
  35686. return obj === false || obj === true;
  35687. },
  35688. isFunction: function isFunction(obj) {
  35689. return Object.prototype.toString.call(obj) === '[object Function]';
  35690. }
  35691. };
  35692. var INTERPRETATIONS = [{
  35693. litmus: Common.isString,
  35694. conversions: {
  35695. THREE_CHAR_HEX: {
  35696. read: function read(original) {
  35697. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  35698. if (test === null) {
  35699. return false;
  35700. }
  35701. return {
  35702. space: 'HEX',
  35703. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  35704. };
  35705. },
  35706. write: colorToString
  35707. },
  35708. SIX_CHAR_HEX: {
  35709. read: function read(original) {
  35710. var test = original.match(/^#([A-F0-9]{6})$/i);
  35711. if (test === null) {
  35712. return false;
  35713. }
  35714. return {
  35715. space: 'HEX',
  35716. hex: parseInt('0x' + test[1].toString(), 0)
  35717. };
  35718. },
  35719. write: colorToString
  35720. },
  35721. CSS_RGB: {
  35722. read: function read(original) {
  35723. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  35724. if (test === null) {
  35725. return false;
  35726. }
  35727. return {
  35728. space: 'RGB',
  35729. r: parseFloat(test[1]),
  35730. g: parseFloat(test[2]),
  35731. b: parseFloat(test[3])
  35732. };
  35733. },
  35734. write: colorToString
  35735. },
  35736. CSS_RGBA: {
  35737. read: function read(original) {
  35738. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  35739. if (test === null) {
  35740. return false;
  35741. }
  35742. return {
  35743. space: 'RGB',
  35744. r: parseFloat(test[1]),
  35745. g: parseFloat(test[2]),
  35746. b: parseFloat(test[3]),
  35747. a: parseFloat(test[4])
  35748. };
  35749. },
  35750. write: colorToString
  35751. }
  35752. }
  35753. }, {
  35754. litmus: Common.isNumber,
  35755. conversions: {
  35756. HEX: {
  35757. read: function read(original) {
  35758. return {
  35759. space: 'HEX',
  35760. hex: original,
  35761. conversionName: 'HEX'
  35762. };
  35763. },
  35764. write: function write(color) {
  35765. return color.hex;
  35766. }
  35767. }
  35768. }
  35769. }, {
  35770. litmus: Common.isArray,
  35771. conversions: {
  35772. RGB_ARRAY: {
  35773. read: function read(original) {
  35774. if (original.length !== 3) {
  35775. return false;
  35776. }
  35777. return {
  35778. space: 'RGB',
  35779. r: original[0],
  35780. g: original[1],
  35781. b: original[2]
  35782. };
  35783. },
  35784. write: function write(color) {
  35785. return [color.r, color.g, color.b];
  35786. }
  35787. },
  35788. RGBA_ARRAY: {
  35789. read: function read(original) {
  35790. if (original.length !== 4) return false;
  35791. return {
  35792. space: 'RGB',
  35793. r: original[0],
  35794. g: original[1],
  35795. b: original[2],
  35796. a: original[3]
  35797. };
  35798. },
  35799. write: function write(color) {
  35800. return [color.r, color.g, color.b, color.a];
  35801. }
  35802. }
  35803. }
  35804. }, {
  35805. litmus: Common.isObject,
  35806. conversions: {
  35807. RGBA_OBJ: {
  35808. read: function read(original) {
  35809. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  35810. return {
  35811. space: 'RGB',
  35812. r: original.r,
  35813. g: original.g,
  35814. b: original.b,
  35815. a: original.a
  35816. };
  35817. }
  35818. return false;
  35819. },
  35820. write: function write(color) {
  35821. return {
  35822. r: color.r,
  35823. g: color.g,
  35824. b: color.b,
  35825. a: color.a
  35826. };
  35827. }
  35828. },
  35829. RGB_OBJ: {
  35830. read: function read(original) {
  35831. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  35832. return {
  35833. space: 'RGB',
  35834. r: original.r,
  35835. g: original.g,
  35836. b: original.b
  35837. };
  35838. }
  35839. return false;
  35840. },
  35841. write: function write(color) {
  35842. return {
  35843. r: color.r,
  35844. g: color.g,
  35845. b: color.b
  35846. };
  35847. }
  35848. },
  35849. HSVA_OBJ: {
  35850. read: function read(original) {
  35851. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  35852. return {
  35853. space: 'HSV',
  35854. h: original.h,
  35855. s: original.s,
  35856. v: original.v,
  35857. a: original.a
  35858. };
  35859. }
  35860. return false;
  35861. },
  35862. write: function write(color) {
  35863. return {
  35864. h: color.h,
  35865. s: color.s,
  35866. v: color.v,
  35867. a: color.a
  35868. };
  35869. }
  35870. },
  35871. HSV_OBJ: {
  35872. read: function read(original) {
  35873. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  35874. return {
  35875. space: 'HSV',
  35876. h: original.h,
  35877. s: original.s,
  35878. v: original.v
  35879. };
  35880. }
  35881. return false;
  35882. },
  35883. write: function write(color) {
  35884. return {
  35885. h: color.h,
  35886. s: color.s,
  35887. v: color.v
  35888. };
  35889. }
  35890. }
  35891. }
  35892. }];
  35893. var result = void 0;
  35894. var toReturn = void 0;
  35895. var interpret = function interpret() {
  35896. toReturn = false;
  35897. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  35898. Common.each(INTERPRETATIONS, function (family) {
  35899. if (family.litmus(original)) {
  35900. Common.each(family.conversions, function (conversion, conversionName) {
  35901. result = conversion.read(original);
  35902. if (toReturn === false && result !== false) {
  35903. toReturn = result;
  35904. result.conversionName = conversionName;
  35905. result.conversion = conversion;
  35906. return Common.BREAK;
  35907. }
  35908. });
  35909. return Common.BREAK;
  35910. }
  35911. });
  35912. return toReturn;
  35913. };
  35914. var tmpComponent = void 0;
  35915. var ColorMath = {
  35916. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  35917. var hi = Math.floor(h / 60) % 6;
  35918. var f = h / 60 - Math.floor(h / 60);
  35919. var p = v * (1.0 - s);
  35920. var q = v * (1.0 - f * s);
  35921. var t = v * (1.0 - (1.0 - f) * s);
  35922. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  35923. return {
  35924. r: c[0] * 255,
  35925. g: c[1] * 255,
  35926. b: c[2] * 255
  35927. };
  35928. },
  35929. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  35930. var min = Math.min(r, g, b);
  35931. var max = Math.max(r, g, b);
  35932. var delta = max - min;
  35933. var h = void 0;
  35934. var s = void 0;
  35935. if (max !== 0) {
  35936. s = delta / max;
  35937. } else {
  35938. return {
  35939. h: NaN,
  35940. s: 0,
  35941. v: 0
  35942. };
  35943. }
  35944. if (r === max) {
  35945. h = (g - b) / delta;
  35946. } else if (g === max) {
  35947. h = 2 + (b - r) / delta;
  35948. } else {
  35949. h = 4 + (r - g) / delta;
  35950. }
  35951. h /= 6;
  35952. if (h < 0) {
  35953. h += 1;
  35954. }
  35955. return {
  35956. h: h * 360,
  35957. s: s,
  35958. v: max / 255
  35959. };
  35960. },
  35961. rgb_to_hex: function rgb_to_hex(r, g, b) {
  35962. var hex = this.hex_with_component(0, 2, r);
  35963. hex = this.hex_with_component(hex, 1, g);
  35964. hex = this.hex_with_component(hex, 0, b);
  35965. return hex;
  35966. },
  35967. component_from_hex: function component_from_hex(hex, componentIndex) {
  35968. return hex >> componentIndex * 8 & 0xFF;
  35969. },
  35970. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  35971. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  35972. }
  35973. };
  35974. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  35975. return typeof obj;
  35976. } : function (obj) {
  35977. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  35978. };
  35979. var classCallCheck = function (instance, Constructor) {
  35980. if (!(instance instanceof Constructor)) {
  35981. throw new TypeError("Cannot call a class as a function");
  35982. }
  35983. };
  35984. var createClass = function () {
  35985. function defineProperties(target, props) {
  35986. for (var i = 0; i < props.length; i++) {
  35987. var descriptor = props[i];
  35988. descriptor.enumerable = descriptor.enumerable || false;
  35989. descriptor.configurable = true;
  35990. if ("value" in descriptor) descriptor.writable = true;
  35991. Object.defineProperty(target, descriptor.key, descriptor);
  35992. }
  35993. }
  35994. return function (Constructor, protoProps, staticProps) {
  35995. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  35996. if (staticProps) defineProperties(Constructor, staticProps);
  35997. return Constructor;
  35998. };
  35999. }();
  36000. var get = function get(object, property, receiver) {
  36001. if (object === null) object = Function.prototype;
  36002. var desc = Object.getOwnPropertyDescriptor(object, property);
  36003. if (desc === undefined) {
  36004. var parent = Object.getPrototypeOf(object);
  36005. if (parent === null) {
  36006. return undefined;
  36007. } else {
  36008. return get(parent, property, receiver);
  36009. }
  36010. } else if ("value" in desc) {
  36011. return desc.value;
  36012. } else {
  36013. var getter = desc.get;
  36014. if (getter === undefined) {
  36015. return undefined;
  36016. }
  36017. return getter.call(receiver);
  36018. }
  36019. };
  36020. var inherits = function (subClass, superClass) {
  36021. if (typeof superClass !== "function" && superClass !== null) {
  36022. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  36023. }
  36024. subClass.prototype = Object.create(superClass && superClass.prototype, {
  36025. constructor: {
  36026. value: subClass,
  36027. enumerable: false,
  36028. writable: true,
  36029. configurable: true
  36030. }
  36031. });
  36032. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  36033. };
  36034. var possibleConstructorReturn = function (self, call) {
  36035. if (!self) {
  36036. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  36037. }
  36038. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  36039. };
  36040. var Color = function () {
  36041. function Color() {
  36042. classCallCheck(this, Color);
  36043. this.__state = interpret.apply(this, arguments);
  36044. if (this.__state === false) {
  36045. throw new Error('Failed to interpret color arguments');
  36046. }
  36047. this.__state.a = this.__state.a || 1;
  36048. }
  36049. createClass(Color, [{
  36050. key: 'toString',
  36051. value: function toString() {
  36052. return colorToString(this);
  36053. }
  36054. }, {
  36055. key: 'toHexString',
  36056. value: function toHexString() {
  36057. return colorToString(this, true);
  36058. }
  36059. }, {
  36060. key: 'toOriginal',
  36061. value: function toOriginal() {
  36062. return this.__state.conversion.write(this);
  36063. }
  36064. }]);
  36065. return Color;
  36066. }();
  36067. function defineRGBComponent(target, component, componentHexIndex) {
  36068. Object.defineProperty(target, component, {
  36069. get: function get$$1() {
  36070. if (this.__state.space === 'RGB') {
  36071. return this.__state[component];
  36072. }
  36073. Color.recalculateRGB(this, component, componentHexIndex);
  36074. return this.__state[component];
  36075. },
  36076. set: function set$$1(v) {
  36077. if (this.__state.space !== 'RGB') {
  36078. Color.recalculateRGB(this, component, componentHexIndex);
  36079. this.__state.space = 'RGB';
  36080. }
  36081. this.__state[component] = v;
  36082. }
  36083. });
  36084. }
  36085. function defineHSVComponent(target, component) {
  36086. Object.defineProperty(target, component, {
  36087. get: function get$$1() {
  36088. if (this.__state.space === 'HSV') {
  36089. return this.__state[component];
  36090. }
  36091. Color.recalculateHSV(this);
  36092. return this.__state[component];
  36093. },
  36094. set: function set$$1(v) {
  36095. if (this.__state.space !== 'HSV') {
  36096. Color.recalculateHSV(this);
  36097. this.__state.space = 'HSV';
  36098. }
  36099. this.__state[component] = v;
  36100. }
  36101. });
  36102. }
  36103. Color.recalculateRGB = function (color, component, componentHexIndex) {
  36104. if (color.__state.space === 'HEX') {
  36105. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  36106. } else if (color.__state.space === 'HSV') {
  36107. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  36108. } else {
  36109. throw new Error('Corrupted color state');
  36110. }
  36111. };
  36112. Color.recalculateHSV = function (color) {
  36113. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  36114. Common.extend(color.__state, {
  36115. s: result.s,
  36116. v: result.v
  36117. });
  36118. if (!Common.isNaN(result.h)) {
  36119. color.__state.h = result.h;
  36120. } else if (Common.isUndefined(color.__state.h)) {
  36121. color.__state.h = 0;
  36122. }
  36123. };
  36124. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  36125. defineRGBComponent(Color.prototype, 'r', 2);
  36126. defineRGBComponent(Color.prototype, 'g', 1);
  36127. defineRGBComponent(Color.prototype, 'b', 0);
  36128. defineHSVComponent(Color.prototype, 'h');
  36129. defineHSVComponent(Color.prototype, 's');
  36130. defineHSVComponent(Color.prototype, 'v');
  36131. Object.defineProperty(Color.prototype, 'a', {
  36132. get: function get$$1() {
  36133. return this.__state.a;
  36134. },
  36135. set: function set$$1(v) {
  36136. this.__state.a = v;
  36137. }
  36138. });
  36139. Object.defineProperty(Color.prototype, 'hex', {
  36140. get: function get$$1() {
  36141. if (!this.__state.space !== 'HEX') {
  36142. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  36143. }
  36144. return this.__state.hex;
  36145. },
  36146. set: function set$$1(v) {
  36147. this.__state.space = 'HEX';
  36148. this.__state.hex = v;
  36149. }
  36150. });
  36151. var Controller = function () {
  36152. function Controller(object, property) {
  36153. classCallCheck(this, Controller);
  36154. this.initialValue = object[property];
  36155. this.domElement = document.createElement('div');
  36156. this.object = object;
  36157. this.property = property;
  36158. this.__onChange = undefined;
  36159. this.__onFinishChange = undefined;
  36160. }
  36161. createClass(Controller, [{
  36162. key: 'onChange',
  36163. value: function onChange(fnc) {
  36164. this.__onChange = fnc;
  36165. return this;
  36166. }
  36167. }, {
  36168. key: 'onFinishChange',
  36169. value: function onFinishChange(fnc) {
  36170. this.__onFinishChange = fnc;
  36171. return this;
  36172. }
  36173. }, {
  36174. key: 'setValue',
  36175. value: function setValue(newValue) {
  36176. this.object[this.property] = newValue;
  36177. if (this.__onChange) {
  36178. this.__onChange.call(this, newValue);
  36179. }
  36180. this.updateDisplay();
  36181. return this;
  36182. }
  36183. }, {
  36184. key: 'getValue',
  36185. value: function getValue() {
  36186. return this.object[this.property];
  36187. }
  36188. }, {
  36189. key: 'updateDisplay',
  36190. value: function updateDisplay() {
  36191. return this;
  36192. }
  36193. }, {
  36194. key: 'isModified',
  36195. value: function isModified() {
  36196. return this.initialValue !== this.getValue();
  36197. }
  36198. }]);
  36199. return Controller;
  36200. }();
  36201. var EVENT_MAP = {
  36202. HTMLEvents: ['change'],
  36203. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  36204. KeyboardEvents: ['keydown']
  36205. };
  36206. var EVENT_MAP_INV = {};
  36207. Common.each(EVENT_MAP, function (v, k) {
  36208. Common.each(v, function (e) {
  36209. EVENT_MAP_INV[e] = k;
  36210. });
  36211. });
  36212. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  36213. function cssValueToPixels(val) {
  36214. if (val === '0' || Common.isUndefined(val)) {
  36215. return 0;
  36216. }
  36217. var match = val.match(CSS_VALUE_PIXELS);
  36218. if (!Common.isNull(match)) {
  36219. return parseFloat(match[1]);
  36220. }
  36221. return 0;
  36222. }
  36223. var dom = {
  36224. makeSelectable: function makeSelectable(elem, selectable) {
  36225. if (elem === undefined || elem.style === undefined) return;
  36226. elem.onselectstart = selectable ? function () {
  36227. return false;
  36228. } : function () {};
  36229. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  36230. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  36231. elem.unselectable = selectable ? 'on' : 'off';
  36232. },
  36233. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  36234. var vertical = vert;
  36235. var horizontal = hor;
  36236. if (Common.isUndefined(horizontal)) {
  36237. horizontal = true;
  36238. }
  36239. if (Common.isUndefined(vertical)) {
  36240. vertical = true;
  36241. }
  36242. elem.style.position = 'absolute';
  36243. if (horizontal) {
  36244. elem.style.left = 0;
  36245. elem.style.right = 0;
  36246. }
  36247. if (vertical) {
  36248. elem.style.top = 0;
  36249. elem.style.bottom = 0;
  36250. }
  36251. },
  36252. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  36253. var params = pars || {};
  36254. var className = EVENT_MAP_INV[eventType];
  36255. if (!className) {
  36256. throw new Error('Event type ' + eventType + ' not supported.');
  36257. }
  36258. var evt = document.createEvent(className);
  36259. switch (className) {
  36260. case 'MouseEvents':
  36261. {
  36262. var clientX = params.x || params.clientX || 0;
  36263. var clientY = params.y || params.clientY || 0;
  36264. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  36265. break;
  36266. }
  36267. case 'KeyboardEvents':
  36268. {
  36269. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  36270. Common.defaults(params, {
  36271. cancelable: true,
  36272. ctrlKey: false,
  36273. altKey: false,
  36274. shiftKey: false,
  36275. metaKey: false,
  36276. keyCode: undefined,
  36277. charCode: undefined
  36278. });
  36279. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  36280. break;
  36281. }
  36282. default:
  36283. {
  36284. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  36285. break;
  36286. }
  36287. }
  36288. Common.defaults(evt, aux);
  36289. elem.dispatchEvent(evt);
  36290. },
  36291. bind: function bind(elem, event, func, newBool) {
  36292. var bool = newBool || false;
  36293. if (elem.addEventListener) {
  36294. elem.addEventListener(event, func, bool);
  36295. } else if (elem.attachEvent) {
  36296. elem.attachEvent('on' + event, func);
  36297. }
  36298. return dom;
  36299. },
  36300. unbind: function unbind(elem, event, func, newBool) {
  36301. var bool = newBool || false;
  36302. if (elem.removeEventListener) {
  36303. elem.removeEventListener(event, func, bool);
  36304. } else if (elem.detachEvent) {
  36305. elem.detachEvent('on' + event, func);
  36306. }
  36307. return dom;
  36308. },
  36309. addClass: function addClass(elem, className) {
  36310. if (elem.className === undefined) {
  36311. elem.className = className;
  36312. } else if (elem.className !== className) {
  36313. var classes = elem.className.split(/ +/);
  36314. if (classes.indexOf(className) === -1) {
  36315. classes.push(className);
  36316. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  36317. }
  36318. }
  36319. return dom;
  36320. },
  36321. removeClass: function removeClass(elem, className) {
  36322. if (className) {
  36323. if (elem.className === className) {
  36324. elem.removeAttribute('class');
  36325. } else {
  36326. var classes = elem.className.split(/ +/);
  36327. var index = classes.indexOf(className);
  36328. if (index !== -1) {
  36329. classes.splice(index, 1);
  36330. elem.className = classes.join(' ');
  36331. }
  36332. }
  36333. } else {
  36334. elem.className = undefined;
  36335. }
  36336. return dom;
  36337. },
  36338. hasClass: function hasClass(elem, className) {
  36339. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  36340. },
  36341. getWidth: function getWidth(elem) {
  36342. var style = getComputedStyle(elem);
  36343. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  36344. },
  36345. getHeight: function getHeight(elem) {
  36346. var style = getComputedStyle(elem);
  36347. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  36348. },
  36349. getOffset: function getOffset(el) {
  36350. var elem = el;
  36351. var offset = {
  36352. left: 0,
  36353. top: 0
  36354. };
  36355. if (elem.offsetParent) {
  36356. do {
  36357. offset.left += elem.offsetLeft;
  36358. offset.top += elem.offsetTop;
  36359. elem = elem.offsetParent;
  36360. } while (elem);
  36361. }
  36362. return offset;
  36363. },
  36364. isActive: function isActive(elem) {
  36365. return elem === document.activeElement && (elem.type || elem.href);
  36366. }
  36367. };
  36368. var BooleanController = function (_Controller) {
  36369. inherits(BooleanController, _Controller);
  36370. function BooleanController(object, property) {
  36371. classCallCheck(this, BooleanController);
  36372. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  36373. var _this = _this2;
  36374. _this2.__prev = _this2.getValue();
  36375. _this2.__checkbox = document.createElement('input');
  36376. _this2.__checkbox.setAttribute('type', 'checkbox');
  36377. function onChange() {
  36378. _this.setValue(!_this.__prev);
  36379. }
  36380. dom.bind(_this2.__checkbox, 'change', onChange, false);
  36381. _this2.domElement.appendChild(_this2.__checkbox);
  36382. _this2.updateDisplay();
  36383. return _this2;
  36384. }
  36385. createClass(BooleanController, [{
  36386. key: 'setValue',
  36387. value: function setValue(v) {
  36388. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  36389. if (this.__onFinishChange) {
  36390. this.__onFinishChange.call(this, this.getValue());
  36391. }
  36392. this.__prev = this.getValue();
  36393. return toReturn;
  36394. }
  36395. }, {
  36396. key: 'updateDisplay',
  36397. value: function updateDisplay() {
  36398. if (this.getValue() === true) {
  36399. this.__checkbox.setAttribute('checked', 'checked');
  36400. this.__checkbox.checked = true;
  36401. this.__prev = true;
  36402. } else {
  36403. this.__checkbox.checked = false;
  36404. this.__prev = false;
  36405. }
  36406. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  36407. }
  36408. }]);
  36409. return BooleanController;
  36410. }(Controller);
  36411. var OptionController = function (_Controller) {
  36412. inherits(OptionController, _Controller);
  36413. function OptionController(object, property, opts) {
  36414. classCallCheck(this, OptionController);
  36415. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  36416. var options = opts;
  36417. var _this = _this2;
  36418. _this2.__select = document.createElement('select');
  36419. if (Common.isArray(options)) {
  36420. var map = {};
  36421. Common.each(options, function (element) {
  36422. map[element] = element;
  36423. });
  36424. options = map;
  36425. }
  36426. Common.each(options, function (value, key) {
  36427. var opt = document.createElement('option');
  36428. opt.innerHTML = key;
  36429. opt.setAttribute('value', value);
  36430. _this.__select.appendChild(opt);
  36431. });
  36432. _this2.updateDisplay();
  36433. dom.bind(_this2.__select, 'change', function () {
  36434. var desiredValue = this.options[this.selectedIndex].value;
  36435. _this.setValue(desiredValue);
  36436. });
  36437. _this2.domElement.appendChild(_this2.__select);
  36438. return _this2;
  36439. }
  36440. createClass(OptionController, [{
  36441. key: 'setValue',
  36442. value: function setValue(v) {
  36443. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  36444. if (this.__onFinishChange) {
  36445. this.__onFinishChange.call(this, this.getValue());
  36446. }
  36447. return toReturn;
  36448. }
  36449. }, {
  36450. key: 'updateDisplay',
  36451. value: function updateDisplay() {
  36452. if (dom.isActive(this.__select)) return this;
  36453. this.__select.value = this.getValue();
  36454. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  36455. }
  36456. }]);
  36457. return OptionController;
  36458. }(Controller);
  36459. var StringController = function (_Controller) {
  36460. inherits(StringController, _Controller);
  36461. function StringController(object, property) {
  36462. classCallCheck(this, StringController);
  36463. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  36464. var _this = _this2;
  36465. function onChange() {
  36466. _this.setValue(_this.__input.value);
  36467. }
  36468. function onBlur() {
  36469. if (_this.__onFinishChange) {
  36470. _this.__onFinishChange.call(_this, _this.getValue());
  36471. }
  36472. }
  36473. _this2.__input = document.createElement('input');
  36474. _this2.__input.setAttribute('type', 'text');
  36475. dom.bind(_this2.__input, 'keyup', onChange);
  36476. dom.bind(_this2.__input, 'change', onChange);
  36477. dom.bind(_this2.__input, 'blur', onBlur);
  36478. dom.bind(_this2.__input, 'keydown', function (e) {
  36479. if (e.keyCode === 13) {
  36480. this.blur();
  36481. }
  36482. });
  36483. _this2.updateDisplay();
  36484. _this2.domElement.appendChild(_this2.__input);
  36485. return _this2;
  36486. }
  36487. createClass(StringController, [{
  36488. key: 'updateDisplay',
  36489. value: function updateDisplay() {
  36490. if (!dom.isActive(this.__input)) {
  36491. this.__input.value = this.getValue();
  36492. }
  36493. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  36494. }
  36495. }]);
  36496. return StringController;
  36497. }(Controller);
  36498. function numDecimals(x) {
  36499. var _x = x.toString();
  36500. if (_x.indexOf('.') > -1) {
  36501. return _x.length - _x.indexOf('.') - 1;
  36502. }
  36503. return 0;
  36504. }
  36505. var NumberController = function (_Controller) {
  36506. inherits(NumberController, _Controller);
  36507. function NumberController(object, property, params) {
  36508. classCallCheck(this, NumberController);
  36509. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  36510. var _params = params || {};
  36511. _this.__min = _params.min;
  36512. _this.__max = _params.max;
  36513. _this.__step = _params.step;
  36514. if (Common.isUndefined(_this.__step)) {
  36515. if (_this.initialValue === 0) {
  36516. _this.__impliedStep = 1;
  36517. } else {
  36518. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  36519. }
  36520. } else {
  36521. _this.__impliedStep = _this.__step;
  36522. }
  36523. _this.__precision = numDecimals(_this.__impliedStep);
  36524. return _this;
  36525. }
  36526. createClass(NumberController, [{
  36527. key: 'setValue',
  36528. value: function setValue(v) {
  36529. var _v = v;
  36530. if (this.__min !== undefined && _v < this.__min) {
  36531. _v = this.__min;
  36532. } else if (this.__max !== undefined && _v > this.__max) {
  36533. _v = this.__max;
  36534. }
  36535. if (this.__step !== undefined && _v % this.__step !== 0) {
  36536. _v = Math.round(_v / this.__step) * this.__step;
  36537. }
  36538. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  36539. }
  36540. }, {
  36541. key: 'min',
  36542. value: function min(minValue) {
  36543. this.__min = minValue;
  36544. return this;
  36545. }
  36546. }, {
  36547. key: 'max',
  36548. value: function max(maxValue) {
  36549. this.__max = maxValue;
  36550. return this;
  36551. }
  36552. }, {
  36553. key: 'step',
  36554. value: function step(stepValue) {
  36555. this.__step = stepValue;
  36556. this.__impliedStep = stepValue;
  36557. this.__precision = numDecimals(stepValue);
  36558. return this;
  36559. }
  36560. }]);
  36561. return NumberController;
  36562. }(Controller);
  36563. function roundToDecimal(value, decimals) {
  36564. var tenTo = Math.pow(10, decimals);
  36565. return Math.round(value * tenTo) / tenTo;
  36566. }
  36567. var NumberControllerBox = function (_NumberController) {
  36568. inherits(NumberControllerBox, _NumberController);
  36569. function NumberControllerBox(object, property, params) {
  36570. classCallCheck(this, NumberControllerBox);
  36571. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  36572. _this2.__truncationSuspended = false;
  36573. var _this = _this2;
  36574. var prevY = void 0;
  36575. function onChange() {
  36576. var attempted = parseFloat(_this.__input.value);
  36577. if (!Common.isNaN(attempted)) {
  36578. _this.setValue(attempted);
  36579. }
  36580. }
  36581. function onFinish() {
  36582. if (_this.__onFinishChange) {
  36583. _this.__onFinishChange.call(_this, _this.getValue());
  36584. }
  36585. }
  36586. function onBlur() {
  36587. onFinish();
  36588. }
  36589. function onMouseDrag(e) {
  36590. var diff = prevY - e.clientY;
  36591. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  36592. prevY = e.clientY;
  36593. }
  36594. function onMouseUp() {
  36595. dom.unbind(window, 'mousemove', onMouseDrag);
  36596. dom.unbind(window, 'mouseup', onMouseUp);
  36597. onFinish();
  36598. }
  36599. function onMouseDown(e) {
  36600. dom.bind(window, 'mousemove', onMouseDrag);
  36601. dom.bind(window, 'mouseup', onMouseUp);
  36602. prevY = e.clientY;
  36603. }
  36604. _this2.__input = document.createElement('input');
  36605. _this2.__input.setAttribute('type', 'text');
  36606. dom.bind(_this2.__input, 'change', onChange);
  36607. dom.bind(_this2.__input, 'blur', onBlur);
  36608. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  36609. dom.bind(_this2.__input, 'keydown', function (e) {
  36610. if (e.keyCode === 13) {
  36611. _this.__truncationSuspended = true;
  36612. this.blur();
  36613. _this.__truncationSuspended = false;
  36614. onFinish();
  36615. }
  36616. });
  36617. _this2.updateDisplay();
  36618. _this2.domElement.appendChild(_this2.__input);
  36619. return _this2;
  36620. }
  36621. createClass(NumberControllerBox, [{
  36622. key: 'updateDisplay',
  36623. value: function updateDisplay() {
  36624. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  36625. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  36626. }
  36627. }]);
  36628. return NumberControllerBox;
  36629. }(NumberController);
  36630. function map(v, i1, i2, o1, o2) {
  36631. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  36632. }
  36633. var NumberControllerSlider = function (_NumberController) {
  36634. inherits(NumberControllerSlider, _NumberController);
  36635. function NumberControllerSlider(object, property, min, max, step) {
  36636. classCallCheck(this, NumberControllerSlider);
  36637. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  36638. min: min,
  36639. max: max,
  36640. step: step
  36641. }));
  36642. var _this = _this2;
  36643. _this2.__background = document.createElement('div');
  36644. _this2.__foreground = document.createElement('div');
  36645. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  36646. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  36647. dom.addClass(_this2.__background, 'slider');
  36648. dom.addClass(_this2.__foreground, 'slider-fg');
  36649. function onMouseDown(e) {
  36650. document.activeElement.blur();
  36651. dom.bind(window, 'mousemove', onMouseDrag);
  36652. dom.bind(window, 'mouseup', onMouseUp);
  36653. onMouseDrag(e);
  36654. }
  36655. function onMouseDrag(e) {
  36656. e.preventDefault();
  36657. var bgRect = _this.__background.getBoundingClientRect();
  36658. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  36659. return false;
  36660. }
  36661. function onMouseUp() {
  36662. dom.unbind(window, 'mousemove', onMouseDrag);
  36663. dom.unbind(window, 'mouseup', onMouseUp);
  36664. if (_this.__onFinishChange) {
  36665. _this.__onFinishChange.call(_this, _this.getValue());
  36666. }
  36667. }
  36668. function onTouchStart(e) {
  36669. if (e.touches.length !== 1) {
  36670. return;
  36671. }
  36672. dom.bind(window, 'touchmove', onTouchMove);
  36673. dom.bind(window, 'touchend', onTouchEnd);
  36674. onTouchMove(e);
  36675. }
  36676. function onTouchMove(e) {
  36677. var clientX = e.touches[0].clientX;
  36678. var bgRect = _this.__background.getBoundingClientRect();
  36679. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  36680. }
  36681. function onTouchEnd() {
  36682. dom.unbind(window, 'touchmove', onTouchMove);
  36683. dom.unbind(window, 'touchend', onTouchEnd);
  36684. if (_this.__onFinishChange) {
  36685. _this.__onFinishChange.call(_this, _this.getValue());
  36686. }
  36687. }
  36688. _this2.updateDisplay();
  36689. _this2.__background.appendChild(_this2.__foreground);
  36690. _this2.domElement.appendChild(_this2.__background);
  36691. return _this2;
  36692. }
  36693. createClass(NumberControllerSlider, [{
  36694. key: 'updateDisplay',
  36695. value: function updateDisplay() {
  36696. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  36697. this.__foreground.style.width = pct * 100 + '%';
  36698. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  36699. }
  36700. }]);
  36701. return NumberControllerSlider;
  36702. }(NumberController);
  36703. var FunctionController = function (_Controller) {
  36704. inherits(FunctionController, _Controller);
  36705. function FunctionController(object, property, text) {
  36706. classCallCheck(this, FunctionController);
  36707. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  36708. var _this = _this2;
  36709. _this2.__button = document.createElement('div');
  36710. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  36711. dom.bind(_this2.__button, 'click', function (e) {
  36712. e.preventDefault();
  36713. _this.fire();
  36714. return false;
  36715. });
  36716. dom.addClass(_this2.__button, 'button');
  36717. _this2.domElement.appendChild(_this2.__button);
  36718. return _this2;
  36719. }
  36720. createClass(FunctionController, [{
  36721. key: 'fire',
  36722. value: function fire() {
  36723. if (this.__onChange) {
  36724. this.__onChange.call(this);
  36725. }
  36726. this.getValue().call(this.object);
  36727. if (this.__onFinishChange) {
  36728. this.__onFinishChange.call(this, this.getValue());
  36729. }
  36730. }
  36731. }]);
  36732. return FunctionController;
  36733. }(Controller);
  36734. var ColorController = function (_Controller) {
  36735. inherits(ColorController, _Controller);
  36736. function ColorController(object, property) {
  36737. classCallCheck(this, ColorController);
  36738. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  36739. _this2.__color = new Color(_this2.getValue());
  36740. _this2.__temp = new Color(0);
  36741. var _this = _this2;
  36742. _this2.domElement = document.createElement('div');
  36743. dom.makeSelectable(_this2.domElement, false);
  36744. _this2.__selector = document.createElement('div');
  36745. _this2.__selector.className = 'selector';
  36746. _this2.__saturation_field = document.createElement('div');
  36747. _this2.__saturation_field.className = 'saturation-field';
  36748. _this2.__field_knob = document.createElement('div');
  36749. _this2.__field_knob.className = 'field-knob';
  36750. _this2.__field_knob_border = '2px solid ';
  36751. _this2.__hue_knob = document.createElement('div');
  36752. _this2.__hue_knob.className = 'hue-knob';
  36753. _this2.__hue_field = document.createElement('div');
  36754. _this2.__hue_field.className = 'hue-field';
  36755. _this2.__input = document.createElement('input');
  36756. _this2.__input.type = 'text';
  36757. _this2.__input_textShadow = '0 1px 1px ';
  36758. dom.bind(_this2.__input, 'keydown', function (e) {
  36759. if (e.keyCode === 13) {
  36760. onBlur.call(this);
  36761. }
  36762. });
  36763. dom.bind(_this2.__input, 'blur', onBlur);
  36764. dom.bind(_this2.__selector, 'mousedown', function () {
  36765. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  36766. dom.removeClass(_this.__selector, 'drag');
  36767. });
  36768. });
  36769. dom.bind(_this2.__selector, 'touchstart', function () {
  36770. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  36771. dom.removeClass(_this.__selector, 'drag');
  36772. });
  36773. });
  36774. var valueField = document.createElement('div');
  36775. Common.extend(_this2.__selector.style, {
  36776. width: '122px',
  36777. height: '102px',
  36778. padding: '3px',
  36779. backgroundColor: '#222',
  36780. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  36781. });
  36782. Common.extend(_this2.__field_knob.style, {
  36783. position: 'absolute',
  36784. width: '12px',
  36785. height: '12px',
  36786. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  36787. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  36788. borderRadius: '12px',
  36789. zIndex: 1
  36790. });
  36791. Common.extend(_this2.__hue_knob.style, {
  36792. position: 'absolute',
  36793. width: '15px',
  36794. height: '2px',
  36795. borderRight: '4px solid #fff',
  36796. zIndex: 1
  36797. });
  36798. Common.extend(_this2.__saturation_field.style, {
  36799. width: '100px',
  36800. height: '100px',
  36801. border: '1px solid #555',
  36802. marginRight: '3px',
  36803. display: 'inline-block',
  36804. cursor: 'pointer'
  36805. });
  36806. Common.extend(valueField.style, {
  36807. width: '100%',
  36808. height: '100%',
  36809. background: 'none'
  36810. });
  36811. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  36812. Common.extend(_this2.__hue_field.style, {
  36813. width: '15px',
  36814. height: '100px',
  36815. border: '1px solid #555',
  36816. cursor: 'ns-resize',
  36817. position: 'absolute',
  36818. top: '3px',
  36819. right: '3px'
  36820. });
  36821. hueGradient(_this2.__hue_field);
  36822. Common.extend(_this2.__input.style, {
  36823. outline: 'none',
  36824. textAlign: 'center',
  36825. color: '#fff',
  36826. border: 0,
  36827. fontWeight: 'bold',
  36828. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  36829. });
  36830. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  36831. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  36832. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  36833. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  36834. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  36835. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  36836. function fieldDown(e) {
  36837. setSV(e);
  36838. dom.bind(window, 'mousemove', setSV);
  36839. dom.bind(window, 'touchmove', setSV);
  36840. dom.bind(window, 'mouseup', fieldUpSV);
  36841. dom.bind(window, 'touchend', fieldUpSV);
  36842. }
  36843. function fieldDownH(e) {
  36844. setH(e);
  36845. dom.bind(window, 'mousemove', setH);
  36846. dom.bind(window, 'touchmove', setH);
  36847. dom.bind(window, 'mouseup', fieldUpH);
  36848. dom.bind(window, 'touchend', fieldUpH);
  36849. }
  36850. function fieldUpSV() {
  36851. dom.unbind(window, 'mousemove', setSV);
  36852. dom.unbind(window, 'touchmove', setSV);
  36853. dom.unbind(window, 'mouseup', fieldUpSV);
  36854. dom.unbind(window, 'touchend', fieldUpSV);
  36855. onFinish();
  36856. }
  36857. function fieldUpH() {
  36858. dom.unbind(window, 'mousemove', setH);
  36859. dom.unbind(window, 'touchmove', setH);
  36860. dom.unbind(window, 'mouseup', fieldUpH);
  36861. dom.unbind(window, 'touchend', fieldUpH);
  36862. onFinish();
  36863. }
  36864. function onBlur() {
  36865. var i = interpret(this.value);
  36866. if (i !== false) {
  36867. _this.__color.__state = i;
  36868. _this.setValue(_this.__color.toOriginal());
  36869. } else {
  36870. this.value = _this.__color.toString();
  36871. }
  36872. }
  36873. function onFinish() {
  36874. if (_this.__onFinishChange) {
  36875. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  36876. }
  36877. }
  36878. _this2.__saturation_field.appendChild(valueField);
  36879. _this2.__selector.appendChild(_this2.__field_knob);
  36880. _this2.__selector.appendChild(_this2.__saturation_field);
  36881. _this2.__selector.appendChild(_this2.__hue_field);
  36882. _this2.__hue_field.appendChild(_this2.__hue_knob);
  36883. _this2.domElement.appendChild(_this2.__input);
  36884. _this2.domElement.appendChild(_this2.__selector);
  36885. _this2.updateDisplay();
  36886. function setSV(e) {
  36887. if (e.type.indexOf('touch') === -1) {
  36888. e.preventDefault();
  36889. }
  36890. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  36891. var _ref = e.touches && e.touches[0] || e,
  36892. clientX = _ref.clientX,
  36893. clientY = _ref.clientY;
  36894. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  36895. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  36896. if (v > 1) {
  36897. v = 1;
  36898. } else if (v < 0) {
  36899. v = 0;
  36900. }
  36901. if (s > 1) {
  36902. s = 1;
  36903. } else if (s < 0) {
  36904. s = 0;
  36905. }
  36906. _this.__color.v = v;
  36907. _this.__color.s = s;
  36908. _this.setValue(_this.__color.toOriginal());
  36909. return false;
  36910. }
  36911. function setH(e) {
  36912. if (e.type.indexOf('touch') === -1) {
  36913. e.preventDefault();
  36914. }
  36915. var fieldRect = _this.__hue_field.getBoundingClientRect();
  36916. var _ref2 = e.touches && e.touches[0] || e,
  36917. clientY = _ref2.clientY;
  36918. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  36919. if (h > 1) {
  36920. h = 1;
  36921. } else if (h < 0) {
  36922. h = 0;
  36923. }
  36924. _this.__color.h = h * 360;
  36925. _this.setValue(_this.__color.toOriginal());
  36926. return false;
  36927. }
  36928. return _this2;
  36929. }
  36930. createClass(ColorController, [{
  36931. key: 'updateDisplay',
  36932. value: function updateDisplay() {
  36933. var i = interpret(this.getValue());
  36934. if (i !== false) {
  36935. var mismatch = false;
  36936. Common.each(Color.COMPONENTS, function (component) {
  36937. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  36938. mismatch = true;
  36939. return {};
  36940. }
  36941. }, this);
  36942. if (mismatch) {
  36943. Common.extend(this.__color.__state, i);
  36944. }
  36945. }
  36946. Common.extend(this.__temp.__state, this.__color.__state);
  36947. this.__temp.a = 1;
  36948. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  36949. var _flip = 255 - flip;
  36950. Common.extend(this.__field_knob.style, {
  36951. marginLeft: 100 * this.__color.s - 7 + 'px',
  36952. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  36953. backgroundColor: this.__temp.toHexString(),
  36954. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  36955. });
  36956. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  36957. this.__temp.s = 1;
  36958. this.__temp.v = 1;
  36959. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  36960. this.__input.value = this.__color.toString();
  36961. Common.extend(this.__input.style, {
  36962. backgroundColor: this.__color.toHexString(),
  36963. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  36964. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  36965. });
  36966. }
  36967. }]);
  36968. return ColorController;
  36969. }(Controller);
  36970. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  36971. function linearGradient(elem, x, a, b) {
  36972. elem.style.background = '';
  36973. Common.each(vendors, function (vendor) {
  36974. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  36975. });
  36976. }
  36977. function hueGradient(elem) {
  36978. elem.style.background = '';
  36979. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  36980. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36981. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36982. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36983. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36984. }
  36985. var css = {
  36986. load: function load(url, indoc) {
  36987. var doc = indoc || document;
  36988. var link = doc.createElement('link');
  36989. link.type = 'text/css';
  36990. link.rel = 'stylesheet';
  36991. link.href = url;
  36992. doc.getElementsByTagName('head')[0].appendChild(link);
  36993. },
  36994. inject: function inject(cssContent, indoc) {
  36995. var doc = indoc || document;
  36996. var injected = document.createElement('style');
  36997. injected.type = 'text/css';
  36998. injected.innerHTML = cssContent;
  36999. var head = doc.getElementsByTagName('head')[0];
  37000. try {
  37001. head.appendChild(injected);
  37002. } catch (e) {}
  37003. }
  37004. };
  37005. 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>";
  37006. var ControllerFactory = function ControllerFactory(object, property) {
  37007. var initialValue = object[property];
  37008. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  37009. return new OptionController(object, property, arguments[2]);
  37010. }
  37011. if (Common.isNumber(initialValue)) {
  37012. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  37013. if (Common.isNumber(arguments[4])) {
  37014. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  37015. }
  37016. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  37017. }
  37018. if (Common.isNumber(arguments[4])) {
  37019. return new NumberControllerBox(object, property, {
  37020. min: arguments[2],
  37021. max: arguments[3],
  37022. step: arguments[4]
  37023. });
  37024. }
  37025. return new NumberControllerBox(object, property, {
  37026. min: arguments[2],
  37027. max: arguments[3]
  37028. });
  37029. }
  37030. if (Common.isString(initialValue)) {
  37031. return new StringController(object, property);
  37032. }
  37033. if (Common.isFunction(initialValue)) {
  37034. return new FunctionController(object, property, '');
  37035. }
  37036. if (Common.isBoolean(initialValue)) {
  37037. return new BooleanController(object, property);
  37038. }
  37039. return null;
  37040. };
  37041. function requestAnimationFrame(callback) {
  37042. setTimeout(callback, 1000 / 60);
  37043. }
  37044. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  37045. var CenteredDiv = function () {
  37046. function CenteredDiv() {
  37047. classCallCheck(this, CenteredDiv);
  37048. this.backgroundElement = document.createElement('div');
  37049. Common.extend(this.backgroundElement.style, {
  37050. backgroundColor: 'rgba(0,0,0,0.8)',
  37051. top: 0,
  37052. left: 0,
  37053. display: 'none',
  37054. zIndex: '1000',
  37055. opacity: 0,
  37056. WebkitTransition: 'opacity 0.2s linear',
  37057. transition: 'opacity 0.2s linear'
  37058. });
  37059. dom.makeFullscreen(this.backgroundElement);
  37060. this.backgroundElement.style.position = 'fixed';
  37061. this.domElement = document.createElement('div');
  37062. Common.extend(this.domElement.style, {
  37063. position: 'fixed',
  37064. display: 'none',
  37065. zIndex: '1001',
  37066. opacity: 0,
  37067. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  37068. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  37069. });
  37070. document.body.appendChild(this.backgroundElement);
  37071. document.body.appendChild(this.domElement);
  37072. var _this = this;
  37073. dom.bind(this.backgroundElement, 'click', function () {
  37074. _this.hide();
  37075. });
  37076. }
  37077. createClass(CenteredDiv, [{
  37078. key: 'show',
  37079. value: function show() {
  37080. var _this = this;
  37081. this.backgroundElement.style.display = 'block';
  37082. this.domElement.style.display = 'block';
  37083. this.domElement.style.opacity = 0;
  37084. this.domElement.style.webkitTransform = 'scale(1.1)';
  37085. this.layout();
  37086. Common.defer(function () {
  37087. _this.backgroundElement.style.opacity = 1;
  37088. _this.domElement.style.opacity = 1;
  37089. _this.domElement.style.webkitTransform = 'scale(1)';
  37090. });
  37091. }
  37092. }, {
  37093. key: 'hide',
  37094. value: function hide() {
  37095. var _this = this;
  37096. var hide = function hide() {
  37097. _this.domElement.style.display = 'none';
  37098. _this.backgroundElement.style.display = 'none';
  37099. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  37100. dom.unbind(_this.domElement, 'transitionend', hide);
  37101. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  37102. };
  37103. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  37104. dom.bind(this.domElement, 'transitionend', hide);
  37105. dom.bind(this.domElement, 'oTransitionEnd', hide);
  37106. this.backgroundElement.style.opacity = 0;
  37107. this.domElement.style.opacity = 0;
  37108. this.domElement.style.webkitTransform = 'scale(1.1)';
  37109. }
  37110. }, {
  37111. key: 'layout',
  37112. value: function layout() {
  37113. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  37114. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  37115. }
  37116. }]);
  37117. return CenteredDiv;
  37118. }();
  37119. 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");
  37120. css.inject(styleSheet);
  37121. var CSS_NAMESPACE = 'dg';
  37122. var HIDE_KEY_CODE = 72;
  37123. var CLOSE_BUTTON_HEIGHT = 20;
  37124. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  37125. var SUPPORTS_LOCAL_STORAGE = function () {
  37126. try {
  37127. return !!window.localStorage;
  37128. } catch (e) {
  37129. return false;
  37130. }
  37131. }();
  37132. var SAVE_DIALOGUE = void 0;
  37133. var autoPlaceVirgin = true;
  37134. var autoPlaceContainer = void 0;
  37135. var hide = false;
  37136. var hideableGuis = [];
  37137. var GUI = function GUI(pars) {
  37138. var _this = this;
  37139. var params = pars || {};
  37140. this.domElement = document.createElement('div');
  37141. this.__ul = document.createElement('ul');
  37142. this.domElement.appendChild(this.__ul);
  37143. dom.addClass(this.domElement, CSS_NAMESPACE);
  37144. this.__folders = {};
  37145. this.__controllers = [];
  37146. this.__rememberedObjects = [];
  37147. this.__rememberedObjectIndecesToControllers = [];
  37148. this.__listening = [];
  37149. params = Common.defaults(params, {
  37150. closeOnTop: false,
  37151. autoPlace: true,
  37152. width: GUI.DEFAULT_WIDTH
  37153. });
  37154. params = Common.defaults(params, {
  37155. resizable: params.autoPlace,
  37156. hideable: params.autoPlace
  37157. });
  37158. if (!Common.isUndefined(params.load)) {
  37159. if (params.preset) {
  37160. params.load.preset = params.preset;
  37161. }
  37162. } else {
  37163. params.load = {
  37164. preset: DEFAULT_DEFAULT_PRESET_NAME
  37165. };
  37166. }
  37167. if (Common.isUndefined(params.parent) && params.hideable) {
  37168. hideableGuis.push(this);
  37169. }
  37170. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  37171. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  37172. params.scrollable = true;
  37173. }
  37174. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  37175. var saveToLocalStorage = void 0;
  37176. var titleRow = void 0;
  37177. Object.defineProperties(this, {
  37178. parent: {
  37179. get: function get$$1() {
  37180. return params.parent;
  37181. }
  37182. },
  37183. scrollable: {
  37184. get: function get$$1() {
  37185. return params.scrollable;
  37186. }
  37187. },
  37188. autoPlace: {
  37189. get: function get$$1() {
  37190. return params.autoPlace;
  37191. }
  37192. },
  37193. closeOnTop: {
  37194. get: function get$$1() {
  37195. return params.closeOnTop;
  37196. }
  37197. },
  37198. preset: {
  37199. get: function get$$1() {
  37200. if (_this.parent) {
  37201. return _this.getRoot().preset;
  37202. }
  37203. return params.load.preset;
  37204. },
  37205. set: function set$$1(v) {
  37206. if (_this.parent) {
  37207. _this.getRoot().preset = v;
  37208. } else {
  37209. params.load.preset = v;
  37210. }
  37211. setPresetSelectIndex(this);
  37212. _this.revert();
  37213. }
  37214. },
  37215. width: {
  37216. get: function get$$1() {
  37217. return params.width;
  37218. },
  37219. set: function set$$1(v) {
  37220. params.width = v;
  37221. setWidth(_this, v);
  37222. }
  37223. },
  37224. name: {
  37225. get: function get$$1() {
  37226. return params.name;
  37227. },
  37228. set: function set$$1(v) {
  37229. params.name = v;
  37230. if (titleRow) {
  37231. titleRow.innerHTML = params.name;
  37232. }
  37233. }
  37234. },
  37235. closed: {
  37236. get: function get$$1() {
  37237. return params.closed;
  37238. },
  37239. set: function set$$1(v) {
  37240. params.closed = v;
  37241. if (params.closed) {
  37242. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  37243. } else {
  37244. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  37245. }
  37246. this.onResize();
  37247. if (_this.__closeButton) {
  37248. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  37249. }
  37250. }
  37251. },
  37252. load: {
  37253. get: function get$$1() {
  37254. return params.load;
  37255. }
  37256. },
  37257. useLocalStorage: {
  37258. get: function get$$1() {
  37259. return useLocalStorage;
  37260. },
  37261. set: function set$$1(bool) {
  37262. if (SUPPORTS_LOCAL_STORAGE) {
  37263. useLocalStorage = bool;
  37264. if (bool) {
  37265. dom.bind(window, 'unload', saveToLocalStorage);
  37266. } else {
  37267. dom.unbind(window, 'unload', saveToLocalStorage);
  37268. }
  37269. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  37270. }
  37271. }
  37272. }
  37273. });
  37274. if (Common.isUndefined(params.parent)) {
  37275. this.closed = params.closed || false;
  37276. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  37277. dom.makeSelectable(this.domElement, false);
  37278. if (SUPPORTS_LOCAL_STORAGE) {
  37279. if (useLocalStorage) {
  37280. _this.useLocalStorage = true;
  37281. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  37282. if (savedGui) {
  37283. params.load = JSON.parse(savedGui);
  37284. }
  37285. }
  37286. }
  37287. this.__closeButton = document.createElement('div');
  37288. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  37289. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  37290. if (params.closeOnTop) {
  37291. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  37292. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  37293. } else {
  37294. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  37295. this.domElement.appendChild(this.__closeButton);
  37296. }
  37297. dom.bind(this.__closeButton, 'click', function () {
  37298. _this.closed = !_this.closed;
  37299. });
  37300. } else {
  37301. if (params.closed === undefined) {
  37302. params.closed = true;
  37303. }
  37304. var titleRowName = document.createTextNode(params.name);
  37305. dom.addClass(titleRowName, 'controller-name');
  37306. titleRow = addRow(_this, titleRowName);
  37307. var onClickTitle = function onClickTitle(e) {
  37308. e.preventDefault();
  37309. _this.closed = !_this.closed;
  37310. return false;
  37311. };
  37312. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  37313. dom.addClass(titleRow, 'title');
  37314. dom.bind(titleRow, 'click', onClickTitle);
  37315. if (!params.closed) {
  37316. this.closed = false;
  37317. }
  37318. }
  37319. if (params.autoPlace) {
  37320. if (Common.isUndefined(params.parent)) {
  37321. if (autoPlaceVirgin) {
  37322. autoPlaceContainer = document.createElement('div');
  37323. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  37324. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  37325. document.body.appendChild(autoPlaceContainer);
  37326. autoPlaceVirgin = false;
  37327. }
  37328. autoPlaceContainer.appendChild(this.domElement);
  37329. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  37330. }
  37331. if (!this.parent) {
  37332. setWidth(_this, params.width);
  37333. }
  37334. }
  37335. this.__resizeHandler = function () {
  37336. _this.onResizeDebounced();
  37337. };
  37338. dom.bind(window, 'resize', this.__resizeHandler);
  37339. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  37340. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  37341. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  37342. this.onResize();
  37343. if (params.resizable) {
  37344. addResizeHandle(this);
  37345. }
  37346. saveToLocalStorage = function saveToLocalStorage() {
  37347. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  37348. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  37349. }
  37350. };
  37351. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  37352. function resetWidth() {
  37353. var root = _this.getRoot();
  37354. root.width += 1;
  37355. Common.defer(function () {
  37356. root.width -= 1;
  37357. });
  37358. }
  37359. if (!params.parent) {
  37360. resetWidth();
  37361. }
  37362. };
  37363. GUI.toggleHide = function () {
  37364. hide = !hide;
  37365. Common.each(hideableGuis, function (gui) {
  37366. gui.domElement.style.display = hide ? 'none' : '';
  37367. });
  37368. };
  37369. GUI.CLASS_AUTO_PLACE = 'a';
  37370. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  37371. GUI.CLASS_MAIN = 'main';
  37372. GUI.CLASS_CONTROLLER_ROW = 'cr';
  37373. GUI.CLASS_TOO_TALL = 'taller-than-window';
  37374. GUI.CLASS_CLOSED = 'closed';
  37375. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  37376. GUI.CLASS_CLOSE_TOP = 'close-top';
  37377. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  37378. GUI.CLASS_DRAG = 'drag';
  37379. GUI.DEFAULT_WIDTH = 245;
  37380. GUI.TEXT_CLOSED = 'Close Controls';
  37381. GUI.TEXT_OPEN = 'Open Controls';
  37382. GUI._keydownHandler = function (e) {
  37383. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  37384. GUI.toggleHide();
  37385. }
  37386. };
  37387. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  37388. Common.extend(GUI.prototype, {
  37389. add: function add(object, property) {
  37390. return _add(this, object, property, {
  37391. factoryArgs: Array.prototype.slice.call(arguments, 2)
  37392. });
  37393. },
  37394. addColor: function addColor(object, property) {
  37395. return _add(this, object, property, {
  37396. color: true
  37397. });
  37398. },
  37399. remove: function remove(controller) {
  37400. this.__ul.removeChild(controller.__li);
  37401. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  37402. var _this = this;
  37403. Common.defer(function () {
  37404. _this.onResize();
  37405. });
  37406. },
  37407. destroy: function destroy() {
  37408. if (this.parent) {
  37409. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  37410. }
  37411. if (this.autoPlace) {
  37412. autoPlaceContainer.removeChild(this.domElement);
  37413. }
  37414. var _this = this;
  37415. Common.each(this.__folders, function (subfolder) {
  37416. _this.removeFolder(subfolder);
  37417. });
  37418. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  37419. removeListeners(this);
  37420. },
  37421. addFolder: function addFolder(name) {
  37422. if (this.__folders[name] !== undefined) {
  37423. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  37424. }
  37425. var newGuiParams = {
  37426. name: name,
  37427. parent: this
  37428. };
  37429. newGuiParams.autoPlace = this.autoPlace;
  37430. if (this.load && this.load.folders && this.load.folders[name]) {
  37431. newGuiParams.closed = this.load.folders[name].closed;
  37432. newGuiParams.load = this.load.folders[name];
  37433. }
  37434. var gui = new GUI(newGuiParams);
  37435. this.__folders[name] = gui;
  37436. var li = addRow(this, gui.domElement);
  37437. dom.addClass(li, 'folder');
  37438. return gui;
  37439. },
  37440. removeFolder: function removeFolder(folder) {
  37441. this.__ul.removeChild(folder.domElement.parentElement);
  37442. delete this.__folders[folder.name];
  37443. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  37444. delete this.load.folders[folder.name];
  37445. }
  37446. removeListeners(folder);
  37447. var _this = this;
  37448. Common.each(folder.__folders, function (subfolder) {
  37449. folder.removeFolder(subfolder);
  37450. });
  37451. Common.defer(function () {
  37452. _this.onResize();
  37453. });
  37454. },
  37455. open: function open() {
  37456. this.closed = false;
  37457. },
  37458. close: function close() {
  37459. this.closed = true;
  37460. },
  37461. hide: function hide() {
  37462. this.domElement.style.display = 'none';
  37463. },
  37464. show: function show() {
  37465. this.domElement.style.display = '';
  37466. },
  37467. onResize: function onResize() {
  37468. var root = this.getRoot();
  37469. if (root.scrollable) {
  37470. var top = dom.getOffset(root.__ul).top;
  37471. var h = 0;
  37472. Common.each(root.__ul.childNodes, function (node) {
  37473. if (!(root.autoPlace && node === root.__save_row)) {
  37474. h += dom.getHeight(node);
  37475. }
  37476. });
  37477. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  37478. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  37479. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  37480. } else {
  37481. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  37482. root.__ul.style.height = 'auto';
  37483. }
  37484. }
  37485. if (root.__resize_handle) {
  37486. Common.defer(function () {
  37487. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  37488. });
  37489. }
  37490. if (root.__closeButton) {
  37491. root.__closeButton.style.width = root.width + 'px';
  37492. }
  37493. },
  37494. onResizeDebounced: Common.debounce(function () {
  37495. this.onResize();
  37496. }, 50),
  37497. remember: function remember() {
  37498. if (Common.isUndefined(SAVE_DIALOGUE)) {
  37499. SAVE_DIALOGUE = new CenteredDiv();
  37500. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  37501. }
  37502. if (this.parent) {
  37503. throw new Error('You can only call remember on a top level GUI.');
  37504. }
  37505. var _this = this;
  37506. Common.each(Array.prototype.slice.call(arguments), function (object) {
  37507. if (_this.__rememberedObjects.length === 0) {
  37508. addSaveMenu(_this);
  37509. }
  37510. if (_this.__rememberedObjects.indexOf(object) === -1) {
  37511. _this.__rememberedObjects.push(object);
  37512. }
  37513. });
  37514. if (this.autoPlace) {
  37515. setWidth(this, this.width);
  37516. }
  37517. },
  37518. getRoot: function getRoot() {
  37519. var gui = this;
  37520. while (gui.parent) {
  37521. gui = gui.parent;
  37522. }
  37523. return gui;
  37524. },
  37525. getSaveObject: function getSaveObject() {
  37526. var toReturn = this.load;
  37527. toReturn.closed = this.closed;
  37528. if (this.__rememberedObjects.length > 0) {
  37529. toReturn.preset = this.preset;
  37530. if (!toReturn.remembered) {
  37531. toReturn.remembered = {};
  37532. }
  37533. toReturn.remembered[this.preset] = getCurrentPreset(this);
  37534. }
  37535. toReturn.folders = {};
  37536. Common.each(this.__folders, function (element, key) {
  37537. toReturn.folders[key] = element.getSaveObject();
  37538. });
  37539. return toReturn;
  37540. },
  37541. save: function save() {
  37542. if (!this.load.remembered) {
  37543. this.load.remembered = {};
  37544. }
  37545. this.load.remembered[this.preset] = getCurrentPreset(this);
  37546. markPresetModified(this, false);
  37547. this.saveToLocalStorageIfPossible();
  37548. },
  37549. saveAs: function saveAs(presetName) {
  37550. if (!this.load.remembered) {
  37551. this.load.remembered = {};
  37552. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  37553. }
  37554. this.load.remembered[presetName] = getCurrentPreset(this);
  37555. this.preset = presetName;
  37556. addPresetOption(this, presetName, true);
  37557. this.saveToLocalStorageIfPossible();
  37558. },
  37559. revert: function revert(gui) {
  37560. Common.each(this.__controllers, function (controller) {
  37561. if (!this.getRoot().load.remembered) {
  37562. controller.setValue(controller.initialValue);
  37563. } else {
  37564. recallSavedValue(gui || this.getRoot(), controller);
  37565. }
  37566. if (controller.__onFinishChange) {
  37567. controller.__onFinishChange.call(controller, controller.getValue());
  37568. }
  37569. }, this);
  37570. Common.each(this.__folders, function (folder) {
  37571. folder.revert(folder);
  37572. });
  37573. if (!gui) {
  37574. markPresetModified(this.getRoot(), false);
  37575. }
  37576. },
  37577. listen: function listen(controller) {
  37578. var init = this.__listening.length === 0;
  37579. this.__listening.push(controller);
  37580. if (init) {
  37581. updateDisplays(this.__listening);
  37582. }
  37583. },
  37584. updateDisplay: function updateDisplay() {
  37585. Common.each(this.__controllers, function (controller) {
  37586. controller.updateDisplay();
  37587. });
  37588. Common.each(this.__folders, function (folder) {
  37589. folder.updateDisplay();
  37590. });
  37591. }
  37592. });
  37593. function addRow(gui, newDom, liBefore) {
  37594. var li = document.createElement('li');
  37595. if (newDom) {
  37596. li.appendChild(newDom);
  37597. }
  37598. if (liBefore) {
  37599. gui.__ul.insertBefore(li, liBefore);
  37600. } else {
  37601. gui.__ul.appendChild(li);
  37602. }
  37603. gui.onResize();
  37604. return li;
  37605. }
  37606. function removeListeners(gui) {
  37607. dom.unbind(window, 'resize', gui.__resizeHandler);
  37608. if (gui.saveToLocalStorageIfPossible) {
  37609. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  37610. }
  37611. }
  37612. function markPresetModified(gui, modified) {
  37613. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  37614. if (modified) {
  37615. opt.innerHTML = opt.value + '*';
  37616. } else {
  37617. opt.innerHTML = opt.value;
  37618. }
  37619. }
  37620. function augmentController(gui, li, controller) {
  37621. controller.__li = li;
  37622. controller.__gui = gui;
  37623. Common.extend(controller, {
  37624. options: function options(_options) {
  37625. if (arguments.length > 1) {
  37626. var nextSibling = controller.__li.nextElementSibling;
  37627. controller.remove();
  37628. return _add(gui, controller.object, controller.property, {
  37629. before: nextSibling,
  37630. factoryArgs: [Common.toArray(arguments)]
  37631. });
  37632. }
  37633. if (Common.isArray(_options) || Common.isObject(_options)) {
  37634. var _nextSibling = controller.__li.nextElementSibling;
  37635. controller.remove();
  37636. return _add(gui, controller.object, controller.property, {
  37637. before: _nextSibling,
  37638. factoryArgs: [_options]
  37639. });
  37640. }
  37641. },
  37642. name: function name(_name) {
  37643. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  37644. return controller;
  37645. },
  37646. listen: function listen() {
  37647. controller.__gui.listen(controller);
  37648. return controller;
  37649. },
  37650. remove: function remove() {
  37651. controller.__gui.remove(controller);
  37652. return controller;
  37653. }
  37654. });
  37655. if (controller instanceof NumberControllerSlider) {
  37656. var box = new NumberControllerBox(controller.object, controller.property, {
  37657. min: controller.__min,
  37658. max: controller.__max,
  37659. step: controller.__step
  37660. });
  37661. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  37662. var pc = controller[method];
  37663. var pb = box[method];
  37664. controller[method] = box[method] = function () {
  37665. var args = Array.prototype.slice.call(arguments);
  37666. pb.apply(box, args);
  37667. return pc.apply(controller, args);
  37668. };
  37669. });
  37670. dom.addClass(li, 'has-slider');
  37671. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  37672. } else if (controller instanceof NumberControllerBox) {
  37673. var r = function r(returned) {
  37674. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  37675. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  37676. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  37677. controller.remove();
  37678. var newController = _add(gui, controller.object, controller.property, {
  37679. before: controller.__li.nextElementSibling,
  37680. factoryArgs: [controller.__min, controller.__max, controller.__step]
  37681. });
  37682. newController.name(oldName);
  37683. if (wasListening) newController.listen();
  37684. return newController;
  37685. }
  37686. return returned;
  37687. };
  37688. controller.min = Common.compose(r, controller.min);
  37689. controller.max = Common.compose(r, controller.max);
  37690. } else if (controller instanceof BooleanController) {
  37691. dom.bind(li, 'click', function () {
  37692. dom.fakeEvent(controller.__checkbox, 'click');
  37693. });
  37694. dom.bind(controller.__checkbox, 'click', function (e) {
  37695. e.stopPropagation();
  37696. });
  37697. } else if (controller instanceof FunctionController) {
  37698. dom.bind(li, 'click', function () {
  37699. dom.fakeEvent(controller.__button, 'click');
  37700. });
  37701. dom.bind(li, 'mouseover', function () {
  37702. dom.addClass(controller.__button, 'hover');
  37703. });
  37704. dom.bind(li, 'mouseout', function () {
  37705. dom.removeClass(controller.__button, 'hover');
  37706. });
  37707. } else if (controller instanceof ColorController) {
  37708. dom.addClass(li, 'color');
  37709. controller.updateDisplay = Common.compose(function (val) {
  37710. li.style.borderLeftColor = controller.__color.toString();
  37711. return val;
  37712. }, controller.updateDisplay);
  37713. controller.updateDisplay();
  37714. }
  37715. controller.setValue = Common.compose(function (val) {
  37716. if (gui.getRoot().__preset_select && controller.isModified()) {
  37717. markPresetModified(gui.getRoot(), true);
  37718. }
  37719. return val;
  37720. }, controller.setValue);
  37721. }
  37722. function recallSavedValue(gui, controller) {
  37723. var root = gui.getRoot();
  37724. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  37725. if (matchedIndex !== -1) {
  37726. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  37727. if (controllerMap === undefined) {
  37728. controllerMap = {};
  37729. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  37730. }
  37731. controllerMap[controller.property] = controller;
  37732. if (root.load && root.load.remembered) {
  37733. var presetMap = root.load.remembered;
  37734. var preset = void 0;
  37735. if (presetMap[gui.preset]) {
  37736. preset = presetMap[gui.preset];
  37737. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  37738. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  37739. } else {
  37740. return;
  37741. }
  37742. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  37743. var value = preset[matchedIndex][controller.property];
  37744. controller.initialValue = value;
  37745. controller.setValue(value);
  37746. }
  37747. }
  37748. }
  37749. }
  37750. function _add(gui, object, property, params) {
  37751. if (object[property] === undefined) {
  37752. throw new Error('Object "' + object + '" has no property "' + property + '"');
  37753. }
  37754. var controller = void 0;
  37755. if (params.color) {
  37756. controller = new ColorController(object, property);
  37757. } else {
  37758. var factoryArgs = [object, property].concat(params.factoryArgs);
  37759. controller = ControllerFactory.apply(gui, factoryArgs);
  37760. }
  37761. if (params.before instanceof Controller) {
  37762. params.before = params.before.__li;
  37763. }
  37764. recallSavedValue(gui, controller);
  37765. dom.addClass(controller.domElement, 'c');
  37766. var name = document.createElement('span');
  37767. dom.addClass(name, 'property-name');
  37768. name.innerHTML = controller.property;
  37769. var container = document.createElement('div');
  37770. container.appendChild(name);
  37771. container.appendChild(controller.domElement);
  37772. var li = addRow(gui, container, params.before);
  37773. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  37774. if (controller instanceof ColorController) {
  37775. dom.addClass(li, 'color');
  37776. } else {
  37777. dom.addClass(li, _typeof(controller.getValue()));
  37778. }
  37779. augmentController(gui, li, controller);
  37780. gui.__controllers.push(controller);
  37781. return controller;
  37782. }
  37783. function getLocalStorageHash(gui, key) {
  37784. return document.location.href + '.' + key;
  37785. }
  37786. function addPresetOption(gui, name, setSelected) {
  37787. var opt = document.createElement('option');
  37788. opt.innerHTML = name;
  37789. opt.value = name;
  37790. gui.__preset_select.appendChild(opt);
  37791. if (setSelected) {
  37792. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  37793. }
  37794. }
  37795. function showHideExplain(gui, explain) {
  37796. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  37797. }
  37798. function addSaveMenu(gui) {
  37799. var div = gui.__save_row = document.createElement('li');
  37800. dom.addClass(gui.domElement, 'has-save');
  37801. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  37802. dom.addClass(div, 'save-row');
  37803. var gears = document.createElement('span');
  37804. gears.innerHTML = '&nbsp;';
  37805. dom.addClass(gears, 'button gears');
  37806. var button = document.createElement('span');
  37807. button.innerHTML = 'Save';
  37808. dom.addClass(button, 'button');
  37809. dom.addClass(button, 'save');
  37810. var button2 = document.createElement('span');
  37811. button2.innerHTML = 'New';
  37812. dom.addClass(button2, 'button');
  37813. dom.addClass(button2, 'save-as');
  37814. var button3 = document.createElement('span');
  37815. button3.innerHTML = 'Revert';
  37816. dom.addClass(button3, 'button');
  37817. dom.addClass(button3, 'revert');
  37818. var select = gui.__preset_select = document.createElement('select');
  37819. if (gui.load && gui.load.remembered) {
  37820. Common.each(gui.load.remembered, function (value, key) {
  37821. addPresetOption(gui, key, key === gui.preset);
  37822. });
  37823. } else {
  37824. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  37825. }
  37826. dom.bind(select, 'change', function () {
  37827. for (var index = 0; index < gui.__preset_select.length; index++) {
  37828. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  37829. }
  37830. gui.preset = this.value;
  37831. });
  37832. div.appendChild(select);
  37833. div.appendChild(gears);
  37834. div.appendChild(button);
  37835. div.appendChild(button2);
  37836. div.appendChild(button3);
  37837. if (SUPPORTS_LOCAL_STORAGE) {
  37838. var explain = document.getElementById('dg-local-explain');
  37839. var localStorageCheckBox = document.getElementById('dg-local-storage');
  37840. var saveLocally = document.getElementById('dg-save-locally');
  37841. saveLocally.style.display = 'block';
  37842. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  37843. localStorageCheckBox.setAttribute('checked', 'checked');
  37844. }
  37845. showHideExplain(gui, explain);
  37846. dom.bind(localStorageCheckBox, 'change', function () {
  37847. gui.useLocalStorage = !gui.useLocalStorage;
  37848. showHideExplain(gui, explain);
  37849. });
  37850. }
  37851. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  37852. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  37853. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  37854. SAVE_DIALOGUE.hide();
  37855. }
  37856. });
  37857. dom.bind(gears, 'click', function () {
  37858. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  37859. SAVE_DIALOGUE.show();
  37860. newConstructorTextArea.focus();
  37861. newConstructorTextArea.select();
  37862. });
  37863. dom.bind(button, 'click', function () {
  37864. gui.save();
  37865. });
  37866. dom.bind(button2, 'click', function () {
  37867. var presetName = prompt('Enter a new preset name.');
  37868. if (presetName) {
  37869. gui.saveAs(presetName);
  37870. }
  37871. });
  37872. dom.bind(button3, 'click', function () {
  37873. gui.revert();
  37874. });
  37875. }
  37876. function addResizeHandle(gui) {
  37877. var pmouseX = void 0;
  37878. gui.__resize_handle = document.createElement('div');
  37879. Common.extend(gui.__resize_handle.style, {
  37880. width: '6px',
  37881. marginLeft: '-3px',
  37882. height: '200px',
  37883. cursor: 'ew-resize',
  37884. position: 'absolute'
  37885. });
  37886. function drag(e) {
  37887. e.preventDefault();
  37888. gui.width += pmouseX - e.clientX;
  37889. gui.onResize();
  37890. pmouseX = e.clientX;
  37891. return false;
  37892. }
  37893. function dragStop() {
  37894. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  37895. dom.unbind(window, 'mousemove', drag);
  37896. dom.unbind(window, 'mouseup', dragStop);
  37897. }
  37898. function dragStart(e) {
  37899. e.preventDefault();
  37900. pmouseX = e.clientX;
  37901. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  37902. dom.bind(window, 'mousemove', drag);
  37903. dom.bind(window, 'mouseup', dragStop);
  37904. return false;
  37905. }
  37906. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  37907. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  37908. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  37909. }
  37910. function setWidth(gui, w) {
  37911. gui.domElement.style.width = w + 'px';
  37912. if (gui.__save_row && gui.autoPlace) {
  37913. gui.__save_row.style.width = w + 'px';
  37914. }
  37915. if (gui.__closeButton) {
  37916. gui.__closeButton.style.width = w + 'px';
  37917. }
  37918. }
  37919. function getCurrentPreset(gui, useInitialValues) {
  37920. var toReturn = {};
  37921. Common.each(gui.__rememberedObjects, function (val, index) {
  37922. var savedValues = {};
  37923. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  37924. Common.each(controllerMap, function (controller, property) {
  37925. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  37926. });
  37927. toReturn[index] = savedValues;
  37928. });
  37929. return toReturn;
  37930. }
  37931. function setPresetSelectIndex(gui) {
  37932. for (var index = 0; index < gui.__preset_select.length; index++) {
  37933. if (gui.__preset_select[index].value === gui.preset) {
  37934. gui.__preset_select.selectedIndex = index;
  37935. }
  37936. }
  37937. }
  37938. function updateDisplays(controllerArray) {
  37939. if (controllerArray.length !== 0) {
  37940. requestAnimationFrame$1.call(window, function () {
  37941. updateDisplays(controllerArray);
  37942. });
  37943. }
  37944. Common.each(controllerArray, function (c) {
  37945. c.updateDisplay();
  37946. });
  37947. }
  37948. var color = {
  37949. Color: Color,
  37950. math: ColorMath,
  37951. interpret: interpret
  37952. };
  37953. exports.color = color;
  37954. var controllers = {
  37955. Controller: Controller,
  37956. BooleanController: BooleanController,
  37957. OptionController: OptionController,
  37958. StringController: StringController,
  37959. NumberController: NumberController,
  37960. NumberControllerBox: NumberControllerBox,
  37961. NumberControllerSlider: NumberControllerSlider,
  37962. FunctionController: FunctionController,
  37963. ColorController: ColorController
  37964. };
  37965. exports.controllers = controllers;
  37966. var dom$1 = {
  37967. dom: dom
  37968. };
  37969. exports.dom = dom$1;
  37970. var gui = {
  37971. GUI: GUI
  37972. };
  37973. exports.gui = gui;
  37974. var GUI$1 = GUI;
  37975. exports.GUI = GUI$1;
  37976. var index = {
  37977. color: color,
  37978. controllers: controllers,
  37979. dom: dom$1,
  37980. gui: gui,
  37981. GUI: GUI$1
  37982. };
  37983. var _default = index;
  37984. exports.default = _default;
  37985. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  37986. "use strict";
  37987. Object.defineProperty(exports, "__esModule", {
  37988. value: true
  37989. });
  37990. exports.default = void 0;
  37991. /**
  37992. * @author mrdoob / http://mrdoob.com/
  37993. */
  37994. var Stats = function () {
  37995. var mode = 0;
  37996. var container = document.createElement('div');
  37997. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  37998. container.addEventListener('click', function (event) {
  37999. event.preventDefault();
  38000. showPanel(++mode % container.children.length);
  38001. }, false); //
  38002. function addPanel(panel) {
  38003. container.appendChild(panel.dom);
  38004. return panel;
  38005. }
  38006. function showPanel(id) {
  38007. for (var i = 0; i < container.children.length; i++) {
  38008. container.children[i].style.display = i === id ? 'block' : 'none';
  38009. }
  38010. mode = id;
  38011. } //
  38012. var beginTime = (performance || Date).now(),
  38013. prevTime = beginTime,
  38014. frames = 0;
  38015. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  38016. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  38017. if (self.performance && self.performance.memory) {
  38018. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  38019. }
  38020. showPanel(0);
  38021. return {
  38022. REVISION: 16,
  38023. dom: container,
  38024. addPanel: addPanel,
  38025. showPanel: showPanel,
  38026. begin: function () {
  38027. beginTime = (performance || Date).now();
  38028. },
  38029. end: function () {
  38030. frames++;
  38031. var time = (performance || Date).now();
  38032. msPanel.update(time - beginTime, 200);
  38033. if (time >= prevTime + 1000) {
  38034. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  38035. prevTime = time;
  38036. frames = 0;
  38037. if (memPanel) {
  38038. var memory = performance.memory;
  38039. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  38040. }
  38041. }
  38042. return time;
  38043. },
  38044. update: function () {
  38045. beginTime = this.end();
  38046. },
  38047. // Backwards Compatibility
  38048. domElement: container,
  38049. setMode: showPanel
  38050. };
  38051. };
  38052. Stats.Panel = function (name, fg, bg) {
  38053. var min = Infinity,
  38054. max = 0,
  38055. round = Math.round;
  38056. var PR = round(window.devicePixelRatio || 1);
  38057. var WIDTH = 80 * PR,
  38058. HEIGHT = 48 * PR,
  38059. TEXT_X = 3 * PR,
  38060. TEXT_Y = 2 * PR,
  38061. GRAPH_X = 3 * PR,
  38062. GRAPH_Y = 15 * PR,
  38063. GRAPH_WIDTH = 74 * PR,
  38064. GRAPH_HEIGHT = 30 * PR;
  38065. var canvas = document.createElement('canvas');
  38066. canvas.width = WIDTH;
  38067. canvas.height = HEIGHT;
  38068. canvas.style.cssText = 'width:80px;height:48px';
  38069. var context = canvas.getContext('2d');
  38070. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  38071. context.textBaseline = 'top';
  38072. context.fillStyle = bg;
  38073. context.fillRect(0, 0, WIDTH, HEIGHT);
  38074. context.fillStyle = fg;
  38075. context.fillText(name, TEXT_X, TEXT_Y);
  38076. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  38077. context.fillStyle = bg;
  38078. context.globalAlpha = 0.9;
  38079. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  38080. return {
  38081. dom: canvas,
  38082. update: function (value, maxValue) {
  38083. min = Math.min(min, value);
  38084. max = Math.max(max, value);
  38085. context.fillStyle = bg;
  38086. context.globalAlpha = 1;
  38087. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  38088. context.fillStyle = fg;
  38089. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  38090. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  38091. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  38092. context.fillStyle = bg;
  38093. context.globalAlpha = 0.9;
  38094. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  38095. }
  38096. };
  38097. };
  38098. var _default = Stats;
  38099. exports.default = _default;
  38100. },{}],"index.js":[function(require,module,exports) {
  38101. "use strict";
  38102. var _index = require("../src/index.js");
  38103. var _three = require("three");
  38104. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  38105. var _BufferGeometryUtils = require("three/examples/jsm/utils/BufferGeometryUtils.js");
  38106. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  38107. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  38108. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  38109. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  38110. 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; }
  38111. const ALL_HITS = 1;
  38112. const FIRST_HIT_ONLY = 2;
  38113. let camera, controls, scene, renderer, tiles, cameraHelper;
  38114. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  38115. let secondRenderer, secondCameraHelper, secondControls, secondCamera;
  38116. let orthoCamera, orthoCameraHelper;
  38117. let box;
  38118. let raycaster, mouse, rayIntersect, lastHoveredElement;
  38119. let offsetParent;
  38120. let statsContainer, stats;
  38121. let params = {
  38122. 'enableUpdate': true,
  38123. 'raycast': _index.NONE,
  38124. 'enableCacheDisplay': false,
  38125. 'orthographic': false,
  38126. 'errorTarget': 6,
  38127. 'errorThreshold': 60,
  38128. 'maxDepth': 15,
  38129. 'loadSiblings': true,
  38130. 'displayActiveTiles': false,
  38131. 'resolutionScale': 1.0,
  38132. 'up': '+Y',
  38133. 'displayBoxBounds': false,
  38134. 'colorMode': 0,
  38135. 'showThirdPerson': false,
  38136. 'showSecondView': false,
  38137. 'reload': reinstantiateTiles
  38138. };
  38139. init();
  38140. animate();
  38141. function reinstantiateTiles() {
  38142. const url = window.location.hash.replace(/^#/, '') || '../data/tileset.json';
  38143. if (tiles) {
  38144. offsetParent.remove(tiles.group);
  38145. }
  38146. tiles = new _index.DebugTilesRenderer(url);
  38147. offsetParent.add(tiles.group);
  38148. }
  38149. function init() {
  38150. scene = new _three.Scene(); // primary camera view
  38151. renderer = new _three.WebGLRenderer({
  38152. antialias: true
  38153. });
  38154. renderer.setPixelRatio(window.devicePixelRatio);
  38155. renderer.setSize(window.innerWidth, window.innerHeight);
  38156. renderer.setClearColor(0x151c1f);
  38157. renderer.outputEncoding = _three.sRGBEncoding;
  38158. document.body.appendChild(renderer.domElement);
  38159. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38160. camera.position.set(400, 400, 400);
  38161. cameraHelper = new _three.CameraHelper(camera);
  38162. scene.add(cameraHelper);
  38163. orthoCamera = new _three.OrthographicCamera();
  38164. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  38165. scene.add(orthoCameraHelper); // secondary camera view
  38166. secondCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38167. secondCamera.position.set(400, 400, -400);
  38168. secondCamera.lookAt(0, 0, 0);
  38169. secondRenderer = new _three.WebGLRenderer({
  38170. antialias: true
  38171. });
  38172. secondRenderer.setPixelRatio(window.devicePixelRatio);
  38173. secondRenderer.setSize(window.innerWidth, window.innerHeight);
  38174. secondRenderer.setClearColor(0x151c1f);
  38175. secondRenderer.outputEncoding = _three.sRGBEncoding;
  38176. document.body.appendChild(secondRenderer.domElement);
  38177. secondRenderer.domElement.style.position = 'absolute';
  38178. secondRenderer.domElement.style.right = '0';
  38179. secondRenderer.domElement.style.top = '0';
  38180. secondRenderer.domElement.style.outline = '#0f1416 solid 2px';
  38181. secondControls = new _OrbitControls.OrbitControls(secondCamera, secondRenderer.domElement);
  38182. secondControls.screenSpacePanning = false;
  38183. secondControls.minDistance = 1;
  38184. secondControls.maxDistance = 2000;
  38185. secondCameraHelper = new _three.CameraHelper(secondCamera);
  38186. scene.add(secondCameraHelper); // Third person camera view
  38187. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38188. thirdPersonCamera.position.set(50, 40, 40);
  38189. thirdPersonCamera.lookAt(0, 0, 0);
  38190. thirdPersonRenderer = new _three.WebGLRenderer({
  38191. antialias: true
  38192. });
  38193. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  38194. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  38195. thirdPersonRenderer.setClearColor(0x0f1416);
  38196. thirdPersonRenderer.outputEncoding = _three.sRGBEncoding;
  38197. document.body.appendChild(thirdPersonRenderer.domElement);
  38198. thirdPersonRenderer.domElement.style.position = 'fixed';
  38199. thirdPersonRenderer.domElement.style.left = '5px';
  38200. thirdPersonRenderer.domElement.style.bottom = '5px';
  38201. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  38202. thirdPersonControls.screenSpacePanning = false;
  38203. thirdPersonControls.minDistance = 1;
  38204. thirdPersonControls.maxDistance = 2000; // controls
  38205. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  38206. controls.screenSpacePanning = false;
  38207. controls.minDistance = 1;
  38208. controls.maxDistance = 2000; // lights
  38209. const dirLight = new _three.DirectionalLight(0xffffff);
  38210. dirLight.position.set(1, 2, 3);
  38211. scene.add(dirLight);
  38212. const ambLight = new _three.AmbientLight(0xffffff, 0.2);
  38213. scene.add(ambLight);
  38214. box = new _three.Box3();
  38215. offsetParent = new _three.Group();
  38216. scene.add(offsetParent); // Raycasting init
  38217. raycaster = new _three.Raycaster();
  38218. mouse = new _three.Vector2();
  38219. rayIntersect = new _three.Group();
  38220. const rayIntersectMat = new _three.MeshBasicMaterial({
  38221. color: 0xe91e63
  38222. });
  38223. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 6), rayIntersectMat);
  38224. rayMesh.rotation.x = Math.PI / 2;
  38225. rayMesh.position.z += 3;
  38226. rayIntersect.add(rayMesh);
  38227. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  38228. rayIntersect.add(rayRing);
  38229. scene.add(rayIntersect);
  38230. rayIntersect.visible = false;
  38231. reinstantiateTiles();
  38232. onWindowResize();
  38233. window.addEventListener('resize', onWindowResize, false);
  38234. renderer.domElement.addEventListener('mousemove', onMouseMove, false);
  38235. renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  38236. renderer.domElement.addEventListener('mouseup', onMouseUp, false);
  38237. renderer.domElement.addEventListener('mouseleave', onMouseLeave, false);
  38238. secondRenderer.domElement.addEventListener('mousemove', onMouseMove, false);
  38239. secondRenderer.domElement.addEventListener('mousedown', onMouseDown, false);
  38240. secondRenderer.domElement.addEventListener('mouseup', onMouseUp, false);
  38241. secondRenderer.domElement.addEventListener('mouseleave', onMouseLeave, false); // GUI
  38242. const gui = new dat.GUI();
  38243. gui.width = 300;
  38244. const tileOptions = gui.addFolder('Tiles Options');
  38245. tileOptions.add(params, 'loadSiblings');
  38246. tileOptions.add(params, 'displayActiveTiles');
  38247. tileOptions.add(params, 'errorTarget').min(0).max(50);
  38248. tileOptions.add(params, 'errorThreshold').min(0).max(1000);
  38249. tileOptions.add(params, 'maxDepth').min(1).max(100);
  38250. tileOptions.add(params, 'up', ['+Y', '-Z']);
  38251. tileOptions.open();
  38252. const debug = gui.addFolder('Debug Options');
  38253. debug.add(params, 'displayBoxBounds');
  38254. debug.add(params, 'colorMode', {
  38255. NONE: _index.NONE,
  38256. SCREEN_ERROR: _index.SCREEN_ERROR,
  38257. GEOMETRIC_ERROR: _index.GEOMETRIC_ERROR,
  38258. DISTANCE: _index.DISTANCE,
  38259. DEPTH: _index.DEPTH,
  38260. RELATIVE_DEPTH: _index.RELATIVE_DEPTH,
  38261. IS_LEAF: _index.IS_LEAF,
  38262. RANDOM_COLOR: _index.RANDOM_COLOR
  38263. });
  38264. debug.open();
  38265. const exampleOptions = gui.addFolder('Example Options');
  38266. exampleOptions.add(params, 'resolutionScale').min(0.01).max(2.0).step(0.01).onChange(onWindowResize);
  38267. exampleOptions.add(params, 'orthographic');
  38268. exampleOptions.add(params, 'showThirdPerson');
  38269. exampleOptions.add(params, 'showSecondView').onChange(onWindowResize);
  38270. exampleOptions.add(params, 'enableUpdate').onChange(v => {
  38271. tiles.parseQueue.autoUpdate = v;
  38272. tiles.downloadQueue.autoUpdate = v;
  38273. if (v) {
  38274. tiles.parseQueue.scheduleJobRun();
  38275. tiles.downloadQueue.scheduleJobRun();
  38276. }
  38277. });
  38278. exampleOptions.add(params, 'raycast', {
  38279. NONE: _index.NONE,
  38280. ALL_HITS,
  38281. FIRST_HIT_ONLY
  38282. });
  38283. exampleOptions.add(params, 'enableCacheDisplay');
  38284. exampleOptions.open();
  38285. gui.add(params, 'reload');
  38286. gui.open();
  38287. statsContainer = document.createElement('div');
  38288. statsContainer.style.position = 'absolute';
  38289. statsContainer.style.top = 0;
  38290. statsContainer.style.left = 0;
  38291. statsContainer.style.color = 'white';
  38292. statsContainer.style.width = '100%';
  38293. statsContainer.style.textAlign = 'center';
  38294. statsContainer.style.padding = '5px';
  38295. statsContainer.style.pointerEvents = 'none';
  38296. statsContainer.style.lineHeight = '1.5em';
  38297. document.body.appendChild(statsContainer); // Stats
  38298. stats = new _statsModule.default();
  38299. stats.showPanel(0);
  38300. document.body.appendChild(stats.dom);
  38301. }
  38302. function onWindowResize() {
  38303. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  38304. thirdPersonCamera.updateProjectionMatrix();
  38305. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  38306. if (params.showSecondView) {
  38307. camera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  38308. renderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  38309. secondCamera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  38310. secondRenderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  38311. secondRenderer.domElement.style.display = 'block';
  38312. } else {
  38313. camera.aspect = window.innerWidth / window.innerHeight;
  38314. renderer.setSize(window.innerWidth, window.innerHeight);
  38315. secondRenderer.domElement.style.display = 'none';
  38316. }
  38317. camera.updateProjectionMatrix();
  38318. renderer.setPixelRatio(window.devicePixelRatio * params.resolutionScale);
  38319. secondCamera.updateProjectionMatrix();
  38320. secondRenderer.setPixelRatio(window.devicePixelRatio);
  38321. updateOrthoCamera();
  38322. }
  38323. function onMouseLeave(e) {
  38324. lastHoveredElement = null;
  38325. }
  38326. function onMouseMove(e) {
  38327. const bounds = this.getBoundingClientRect();
  38328. mouse.x = e.clientX - bounds.x;
  38329. mouse.y = e.clientY - bounds.y;
  38330. mouse.x = mouse.x / bounds.width * 2 - 1;
  38331. mouse.y = -(mouse.y / bounds.height) * 2 + 1;
  38332. lastHoveredElement = this;
  38333. }
  38334. const startPos = new _three.Vector2();
  38335. const endPos = new _three.Vector2();
  38336. function onMouseDown(e) {
  38337. const bounds = this.getBoundingClientRect();
  38338. startPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  38339. }
  38340. function onMouseUp(e) {
  38341. const bounds = this.getBoundingClientRect();
  38342. endPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  38343. if (startPos.distanceTo(endPos) > 2) {
  38344. return;
  38345. }
  38346. if (lastHoveredElement === secondRenderer.domElement) {
  38347. raycaster.setFromCamera(mouse, secondCamera);
  38348. } else {
  38349. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  38350. }
  38351. raycaster.firstHitOnly = true;
  38352. const results = raycaster.intersectObject(tiles.group, true);
  38353. if (results.length) {
  38354. const object = results[0].object;
  38355. const info = tiles.getTileInformationFromActiveObject(object);
  38356. let str = '';
  38357. for (const key in info) {
  38358. let val = info[key];
  38359. if (typeof val === 'number') {
  38360. val = Math.floor(val * 1e5) / 1e5;
  38361. }
  38362. let name = key;
  38363. while (name.length < 20) {
  38364. name += ' ';
  38365. }
  38366. str += `${name} : ${val}\n`;
  38367. }
  38368. console.log(str);
  38369. }
  38370. }
  38371. function updateOrthoCamera() {
  38372. orthoCamera.position.copy(camera.position);
  38373. orthoCamera.rotation.copy(camera.rotation);
  38374. const scale = camera.position.distanceTo(controls.target) / 2.0;
  38375. let aspect = window.innerWidth / window.innerHeight;
  38376. if (params.showSecondView) {
  38377. aspect *= 0.5;
  38378. }
  38379. orthoCamera.left = -aspect * scale;
  38380. orthoCamera.right = aspect * scale;
  38381. orthoCamera.bottom = -scale;
  38382. orthoCamera.top = scale;
  38383. orthoCamera.near = camera.near;
  38384. orthoCamera.far = camera.far;
  38385. orthoCamera.updateProjectionMatrix();
  38386. }
  38387. function animate() {
  38388. requestAnimationFrame(animate); // update options
  38389. tiles.errorTarget = params.errorTarget;
  38390. tiles.errorThreshold = params.errorThreshold;
  38391. tiles.loadSiblings = params.loadSiblings;
  38392. tiles.displayActiveTiles = params.displayActiveTiles;
  38393. tiles.maxDepth = params.maxDepth;
  38394. tiles.displayBoxBounds = params.displayBoxBounds;
  38395. tiles.colorMode = parseFloat(params.colorMode);
  38396. if (params.orthographic) {
  38397. tiles.deleteCamera(camera);
  38398. tiles.setCamera(orthoCamera);
  38399. tiles.setResolutionFromRenderer(orthoCamera, renderer);
  38400. } else {
  38401. tiles.deleteCamera(orthoCamera);
  38402. tiles.setCamera(camera);
  38403. tiles.setResolutionFromRenderer(camera, renderer);
  38404. }
  38405. if (params.showSecondView) {
  38406. tiles.setCamera(secondCamera);
  38407. tiles.setResolutionFromRenderer(secondCamera, secondRenderer);
  38408. } else {
  38409. tiles.deleteCamera(secondCamera);
  38410. }
  38411. offsetParent.rotation.set(0, 0, 0);
  38412. if (params.up === '-Z') {
  38413. offsetParent.rotation.x = Math.PI / 2;
  38414. }
  38415. offsetParent.updateMatrixWorld(true); // update tiles center
  38416. if (tiles.getBounds(box)) {
  38417. box.getCenter(tiles.group.position);
  38418. tiles.group.position.multiplyScalar(-1);
  38419. }
  38420. if (parseFloat(params.raycast) !== _index.NONE && lastHoveredElement !== null) {
  38421. if (lastHoveredElement === renderer.domElement) {
  38422. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  38423. } else {
  38424. raycaster.setFromCamera(mouse, secondCamera);
  38425. }
  38426. raycaster.firstHitOnly = parseFloat(params.raycast) === FIRST_HIT_ONLY;
  38427. const results = raycaster.intersectObject(tiles.group, true);
  38428. if (results.length) {
  38429. const closestHit = results[0];
  38430. const point = closestHit.point;
  38431. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  38432. if (closestHit.face) {
  38433. const normal = closestHit.face.normal;
  38434. normal.transformDirection(closestHit.object.matrixWorld);
  38435. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  38436. }
  38437. rayIntersect.visible = true;
  38438. } else {
  38439. rayIntersect.visible = false;
  38440. }
  38441. } else {
  38442. rayIntersect.visible = false;
  38443. } // update tiles
  38444. window.tiles = tiles;
  38445. if (params.enableUpdate) {
  38446. secondCamera.updateMatrixWorld();
  38447. camera.updateMatrixWorld();
  38448. orthoCamera.updateMatrixWorld();
  38449. tiles.update();
  38450. }
  38451. render();
  38452. stats.update();
  38453. }
  38454. function render() {
  38455. updateOrthoCamera();
  38456. cameraHelper.visible = false;
  38457. orthoCameraHelper.visible = false;
  38458. secondCameraHelper.visible = false; // render primary view
  38459. if (params.orthographic) {
  38460. const dist = orthoCamera.position.distanceTo(rayIntersect.position);
  38461. rayIntersect.scale.setScalar(dist / 150);
  38462. } else {
  38463. const dist = camera.position.distanceTo(rayIntersect.position);
  38464. rayIntersect.scale.setScalar(dist * camera.fov / 6000);
  38465. }
  38466. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render secondary view
  38467. if (params.showSecondView) {
  38468. const dist = secondCamera.position.distanceTo(rayIntersect.position);
  38469. rayIntersect.scale.setScalar(dist * secondCamera.fov / 6000);
  38470. secondRenderer.render(scene, secondCamera);
  38471. } // render third person view
  38472. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  38473. if (params.showThirdPerson) {
  38474. cameraHelper.update();
  38475. cameraHelper.visible = !params.orthographic;
  38476. orthoCameraHelper.update();
  38477. orthoCameraHelper.visible = params.orthographic;
  38478. if (params.showSecondView) {
  38479. secondCameraHelper.update();
  38480. secondCameraHelper.visible = true;
  38481. }
  38482. const dist = thirdPersonCamera.position.distanceTo(rayIntersect.position);
  38483. rayIntersect.scale.setScalar(dist * thirdPersonCamera.fov / 6000);
  38484. thirdPersonRenderer.render(scene, thirdPersonCamera);
  38485. }
  38486. const cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.minSize;
  38487. let str = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length - 2}`;
  38488. if (params.enableCacheDisplay) {
  38489. const geomSet = new Set();
  38490. tiles.traverse(tile => {
  38491. const scene = tile.cached.scene;
  38492. if (scene) {
  38493. scene.traverse(c => {
  38494. if (c.geometry) {
  38495. geomSet.add(c.geometry);
  38496. }
  38497. });
  38498. }
  38499. });
  38500. let count = 0;
  38501. geomSet.forEach(g => {
  38502. count += _BufferGeometryUtils.BufferGeometryUtils.estimateBytesUsed(g);
  38503. });
  38504. str += `<br/>Cache: ${(100 * cacheFullness).toFixed(2)}% ~${(count / 1000 / 1000).toFixed(2)}mb`;
  38505. }
  38506. if (statsContainer.innerHTML !== str) {
  38507. statsContainer.innerHTML = str;
  38508. }
  38509. }
  38510. },{"../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/utils/BufferGeometryUtils.js":"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.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) {
  38511. var global = arguments[3];
  38512. var OVERLAY_ID = '__parcel__error__overlay__';
  38513. var OldModule = module.bundle.Module;
  38514. function Module(moduleName) {
  38515. OldModule.call(this, moduleName);
  38516. this.hot = {
  38517. data: module.bundle.hotData,
  38518. _acceptCallbacks: [],
  38519. _disposeCallbacks: [],
  38520. accept: function (fn) {
  38521. this._acceptCallbacks.push(fn || function () {});
  38522. },
  38523. dispose: function (fn) {
  38524. this._disposeCallbacks.push(fn);
  38525. }
  38526. };
  38527. module.bundle.hotData = null;
  38528. }
  38529. module.bundle.Module = Module;
  38530. var checkedAssets, assetsToAccept;
  38531. var parent = module.bundle.parent;
  38532. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  38533. var hostname = "" || location.hostname;
  38534. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  38535. var ws = new WebSocket(protocol + '://' + hostname + ':' + "50060" + '/');
  38536. ws.onmessage = function (event) {
  38537. checkedAssets = {};
  38538. assetsToAccept = [];
  38539. var data = JSON.parse(event.data);
  38540. if (data.type === 'update') {
  38541. var handled = false;
  38542. data.assets.forEach(function (asset) {
  38543. if (!asset.isNew) {
  38544. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  38545. if (didAccept) {
  38546. handled = true;
  38547. }
  38548. }
  38549. }); // Enable HMR for CSS by default.
  38550. handled = handled || data.assets.every(function (asset) {
  38551. return asset.type === 'css' && asset.generated.js;
  38552. });
  38553. if (handled) {
  38554. console.clear();
  38555. data.assets.forEach(function (asset) {
  38556. hmrApply(global.parcelRequire, asset);
  38557. });
  38558. assetsToAccept.forEach(function (v) {
  38559. hmrAcceptRun(v[0], v[1]);
  38560. });
  38561. } else if (location.reload) {
  38562. // `location` global exists in a web worker context but lacks `.reload()` function.
  38563. location.reload();
  38564. }
  38565. }
  38566. if (data.type === 'reload') {
  38567. ws.close();
  38568. ws.onclose = function () {
  38569. location.reload();
  38570. };
  38571. }
  38572. if (data.type === 'error-resolved') {
  38573. console.log('[parcel] ✨ Error resolved');
  38574. removeErrorOverlay();
  38575. }
  38576. if (data.type === 'error') {
  38577. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  38578. removeErrorOverlay();
  38579. var overlay = createErrorOverlay(data);
  38580. document.body.appendChild(overlay);
  38581. }
  38582. };
  38583. }
  38584. function removeErrorOverlay() {
  38585. var overlay = document.getElementById(OVERLAY_ID);
  38586. if (overlay) {
  38587. overlay.remove();
  38588. }
  38589. }
  38590. function createErrorOverlay(data) {
  38591. var overlay = document.createElement('div');
  38592. overlay.id = OVERLAY_ID; // html encode message and stack trace
  38593. var message = document.createElement('div');
  38594. var stackTrace = document.createElement('pre');
  38595. message.innerText = data.error.message;
  38596. stackTrace.innerText = data.error.stack;
  38597. 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>';
  38598. return overlay;
  38599. }
  38600. function getParents(bundle, id) {
  38601. var modules = bundle.modules;
  38602. if (!modules) {
  38603. return [];
  38604. }
  38605. var parents = [];
  38606. var k, d, dep;
  38607. for (k in modules) {
  38608. for (d in modules[k][1]) {
  38609. dep = modules[k][1][d];
  38610. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  38611. parents.push(k);
  38612. }
  38613. }
  38614. }
  38615. if (bundle.parent) {
  38616. parents = parents.concat(getParents(bundle.parent, id));
  38617. }
  38618. return parents;
  38619. }
  38620. function hmrApply(bundle, asset) {
  38621. var modules = bundle.modules;
  38622. if (!modules) {
  38623. return;
  38624. }
  38625. if (modules[asset.id] || !bundle.parent) {
  38626. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  38627. asset.isNew = !modules[asset.id];
  38628. modules[asset.id] = [fn, asset.deps];
  38629. } else if (bundle.parent) {
  38630. hmrApply(bundle.parent, asset);
  38631. }
  38632. }
  38633. function hmrAcceptCheck(bundle, id) {
  38634. var modules = bundle.modules;
  38635. if (!modules) {
  38636. return;
  38637. }
  38638. if (!modules[id] && bundle.parent) {
  38639. return hmrAcceptCheck(bundle.parent, id);
  38640. }
  38641. if (checkedAssets[id]) {
  38642. return;
  38643. }
  38644. checkedAssets[id] = true;
  38645. var cached = bundle.cache[id];
  38646. assetsToAccept.push([bundle, id]);
  38647. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  38648. return true;
  38649. }
  38650. return getParents(global.parcelRequire, id).some(function (id) {
  38651. return hmrAcceptCheck(global.parcelRequire, id);
  38652. });
  38653. }
  38654. function hmrAcceptRun(bundle, id) {
  38655. var cached = bundle.cache[id];
  38656. bundle.hotData = {};
  38657. if (cached) {
  38658. cached.hot.data = bundle.hotData;
  38659. }
  38660. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  38661. cached.hot._disposeCallbacks.forEach(function (cb) {
  38662. cb(bundle.hotData);
  38663. });
  38664. }
  38665. delete bundle.cache[id];
  38666. bundle(id);
  38667. cached = bundle.cache[id];
  38668. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  38669. cached.hot._acceptCallbacks.forEach(function (cb) {
  38670. cb();
  38671. });
  38672. return true;
  38673. }
  38674. }
  38675. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  38676. //# sourceMappingURL=example.e31bb0bc.js.map