example.e31bb0bc.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751
  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/process/browser.js":[function(require,module,exports) {
  101. // shim for using process in browser
  102. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  103. // don't break things. But we need to wrap it in a try catch in case it is
  104. // wrapped in strict mode code which doesn't define any globals. It's inside a
  105. // function because try/catches deoptimize in certain engines.
  106. var cachedSetTimeout;
  107. var cachedClearTimeout;
  108. function defaultSetTimout() {
  109. throw new Error('setTimeout has not been defined');
  110. }
  111. function defaultClearTimeout() {
  112. throw new Error('clearTimeout has not been defined');
  113. }
  114. (function () {
  115. try {
  116. if (typeof setTimeout === 'function') {
  117. cachedSetTimeout = setTimeout;
  118. } else {
  119. cachedSetTimeout = defaultSetTimout;
  120. }
  121. } catch (e) {
  122. cachedSetTimeout = defaultSetTimout;
  123. }
  124. try {
  125. if (typeof clearTimeout === 'function') {
  126. cachedClearTimeout = clearTimeout;
  127. } else {
  128. cachedClearTimeout = defaultClearTimeout;
  129. }
  130. } catch (e) {
  131. cachedClearTimeout = defaultClearTimeout;
  132. }
  133. })();
  134. function runTimeout(fun) {
  135. if (cachedSetTimeout === setTimeout) {
  136. //normal enviroments in sane situations
  137. return setTimeout(fun, 0);
  138. } // if setTimeout wasn't available but was latter defined
  139. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  140. cachedSetTimeout = setTimeout;
  141. return setTimeout(fun, 0);
  142. }
  143. try {
  144. // when when somebody has screwed with setTimeout but no I.E. maddness
  145. return cachedSetTimeout(fun, 0);
  146. } catch (e) {
  147. try {
  148. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  149. return cachedSetTimeout.call(null, fun, 0);
  150. } catch (e) {
  151. // 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
  152. return cachedSetTimeout.call(this, fun, 0);
  153. }
  154. }
  155. }
  156. function runClearTimeout(marker) {
  157. if (cachedClearTimeout === clearTimeout) {
  158. //normal enviroments in sane situations
  159. return clearTimeout(marker);
  160. } // if clearTimeout wasn't available but was latter defined
  161. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  162. cachedClearTimeout = clearTimeout;
  163. return clearTimeout(marker);
  164. }
  165. try {
  166. // when when somebody has screwed with setTimeout but no I.E. maddness
  167. return cachedClearTimeout(marker);
  168. } catch (e) {
  169. try {
  170. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  171. return cachedClearTimeout.call(null, marker);
  172. } catch (e) {
  173. // 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.
  174. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  175. return cachedClearTimeout.call(this, marker);
  176. }
  177. }
  178. }
  179. var queue = [];
  180. var draining = false;
  181. var currentQueue;
  182. var queueIndex = -1;
  183. function cleanUpNextTick() {
  184. if (!draining || !currentQueue) {
  185. return;
  186. }
  187. draining = false;
  188. if (currentQueue.length) {
  189. queue = currentQueue.concat(queue);
  190. } else {
  191. queueIndex = -1;
  192. }
  193. if (queue.length) {
  194. drainQueue();
  195. }
  196. }
  197. function drainQueue() {
  198. if (draining) {
  199. return;
  200. }
  201. var timeout = runTimeout(cleanUpNextTick);
  202. draining = true;
  203. var len = queue.length;
  204. while (len) {
  205. currentQueue = queue;
  206. queue = [];
  207. while (++queueIndex < len) {
  208. if (currentQueue) {
  209. currentQueue[queueIndex].run();
  210. }
  211. }
  212. queueIndex = -1;
  213. len = queue.length;
  214. }
  215. currentQueue = null;
  216. draining = false;
  217. runClearTimeout(timeout);
  218. }
  219. process.nextTick = function (fun) {
  220. var args = new Array(arguments.length - 1);
  221. if (arguments.length > 1) {
  222. for (var i = 1; i < arguments.length; i++) {
  223. args[i - 1] = arguments[i];
  224. }
  225. }
  226. queue.push(new Item(fun, args));
  227. if (queue.length === 1 && !draining) {
  228. runTimeout(drainQueue);
  229. }
  230. }; // v8 likes predictible objects
  231. function Item(fun, array) {
  232. this.fun = fun;
  233. this.array = array;
  234. }
  235. Item.prototype.run = function () {
  236. this.fun.apply(null, this.array);
  237. };
  238. process.title = 'browser';
  239. process.env = {};
  240. process.argv = [];
  241. process.version = ''; // empty string to avoid regexp issues
  242. process.versions = {};
  243. function noop() {}
  244. process.on = noop;
  245. process.addListener = noop;
  246. process.once = noop;
  247. process.off = noop;
  248. process.removeListener = noop;
  249. process.removeAllListeners = noop;
  250. process.emit = noop;
  251. process.prependListener = noop;
  252. process.prependOnceListener = noop;
  253. process.listeners = function (name) {
  254. return [];
  255. };
  256. process.binding = function (name) {
  257. throw new Error('process.binding is not supported');
  258. };
  259. process.cwd = function () {
  260. return '/';
  261. };
  262. process.chdir = function (dir) {
  263. throw new Error('process.chdir is not supported');
  264. };
  265. process.umask = function () {
  266. return 0;
  267. };
  268. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  269. var process = require("process");
  270. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  271. // backported and transplited with Babel, with backwards-compat fixes
  272. // Copyright Joyent, Inc. and other Node contributors.
  273. //
  274. // Permission is hereby granted, free of charge, to any person obtaining a
  275. // copy of this software and associated documentation files (the
  276. // "Software"), to deal in the Software without restriction, including
  277. // without limitation the rights to use, copy, modify, merge, publish,
  278. // distribute, sublicense, and/or sell copies of the Software, and to permit
  279. // persons to whom the Software is furnished to do so, subject to the
  280. // following conditions:
  281. //
  282. // The above copyright notice and this permission notice shall be included
  283. // in all copies or substantial portions of the Software.
  284. //
  285. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  286. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  287. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  288. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  289. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  290. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  291. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  292. // resolves . and .. elements in a path array with directory names there
  293. // must be no slashes, empty elements, or device names (c:\) in the array
  294. // (so also no leading and trailing slashes - it does not distinguish
  295. // relative and absolute paths)
  296. function normalizeArray(parts, allowAboveRoot) {
  297. // if the path tries to go above the root, `up` ends up > 0
  298. var up = 0;
  299. for (var i = parts.length - 1; i >= 0; i--) {
  300. var last = parts[i];
  301. if (last === '.') {
  302. parts.splice(i, 1);
  303. } else if (last === '..') {
  304. parts.splice(i, 1);
  305. up++;
  306. } else if (up) {
  307. parts.splice(i, 1);
  308. up--;
  309. }
  310. }
  311. // if the path is allowed to go above the root, restore leading ..s
  312. if (allowAboveRoot) {
  313. for (; up--; up) {
  314. parts.unshift('..');
  315. }
  316. }
  317. return parts;
  318. }
  319. // path.resolve([from ...], to)
  320. // posix version
  321. exports.resolve = function() {
  322. var resolvedPath = '',
  323. resolvedAbsolute = false;
  324. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  325. var path = (i >= 0) ? arguments[i] : process.cwd();
  326. // Skip empty and invalid entries
  327. if (typeof path !== 'string') {
  328. throw new TypeError('Arguments to path.resolve must be strings');
  329. } else if (!path) {
  330. continue;
  331. }
  332. resolvedPath = path + '/' + resolvedPath;
  333. resolvedAbsolute = path.charAt(0) === '/';
  334. }
  335. // At this point the path should be resolved to a full absolute path, but
  336. // handle relative paths to be safe (might happen when process.cwd() fails)
  337. // Normalize the path
  338. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  339. return !!p;
  340. }), !resolvedAbsolute).join('/');
  341. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  342. };
  343. // path.normalize(path)
  344. // posix version
  345. exports.normalize = function(path) {
  346. var isAbsolute = exports.isAbsolute(path),
  347. trailingSlash = substr(path, -1) === '/';
  348. // Normalize the path
  349. path = normalizeArray(filter(path.split('/'), function(p) {
  350. return !!p;
  351. }), !isAbsolute).join('/');
  352. if (!path && !isAbsolute) {
  353. path = '.';
  354. }
  355. if (path && trailingSlash) {
  356. path += '/';
  357. }
  358. return (isAbsolute ? '/' : '') + path;
  359. };
  360. // posix version
  361. exports.isAbsolute = function(path) {
  362. return path.charAt(0) === '/';
  363. };
  364. // posix version
  365. exports.join = function() {
  366. var paths = Array.prototype.slice.call(arguments, 0);
  367. return exports.normalize(filter(paths, function(p, index) {
  368. if (typeof p !== 'string') {
  369. throw new TypeError('Arguments to path.join must be strings');
  370. }
  371. return p;
  372. }).join('/'));
  373. };
  374. // path.relative(from, to)
  375. // posix version
  376. exports.relative = function(from, to) {
  377. from = exports.resolve(from).substr(1);
  378. to = exports.resolve(to).substr(1);
  379. function trim(arr) {
  380. var start = 0;
  381. for (; start < arr.length; start++) {
  382. if (arr[start] !== '') break;
  383. }
  384. var end = arr.length - 1;
  385. for (; end >= 0; end--) {
  386. if (arr[end] !== '') break;
  387. }
  388. if (start > end) return [];
  389. return arr.slice(start, end - start + 1);
  390. }
  391. var fromParts = trim(from.split('/'));
  392. var toParts = trim(to.split('/'));
  393. var length = Math.min(fromParts.length, toParts.length);
  394. var samePartsLength = length;
  395. for (var i = 0; i < length; i++) {
  396. if (fromParts[i] !== toParts[i]) {
  397. samePartsLength = i;
  398. break;
  399. }
  400. }
  401. var outputParts = [];
  402. for (var i = samePartsLength; i < fromParts.length; i++) {
  403. outputParts.push('..');
  404. }
  405. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  406. return outputParts.join('/');
  407. };
  408. exports.sep = '/';
  409. exports.delimiter = ':';
  410. exports.dirname = function (path) {
  411. if (typeof path !== 'string') path = path + '';
  412. if (path.length === 0) return '.';
  413. var code = path.charCodeAt(0);
  414. var hasRoot = code === 47 /*/*/;
  415. var end = -1;
  416. var matchedSlash = true;
  417. for (var i = path.length - 1; i >= 1; --i) {
  418. code = path.charCodeAt(i);
  419. if (code === 47 /*/*/) {
  420. if (!matchedSlash) {
  421. end = i;
  422. break;
  423. }
  424. } else {
  425. // We saw the first non-path separator
  426. matchedSlash = false;
  427. }
  428. }
  429. if (end === -1) return hasRoot ? '/' : '.';
  430. if (hasRoot && end === 1) {
  431. // return '//';
  432. // Backwards-compat fix:
  433. return '/';
  434. }
  435. return path.slice(0, end);
  436. };
  437. function basename(path) {
  438. if (typeof path !== 'string') path = path + '';
  439. var start = 0;
  440. var end = -1;
  441. var matchedSlash = true;
  442. var i;
  443. for (i = path.length - 1; i >= 0; --i) {
  444. if (path.charCodeAt(i) === 47 /*/*/) {
  445. // If we reached a path separator that was not part of a set of path
  446. // separators at the end of the string, stop now
  447. if (!matchedSlash) {
  448. start = i + 1;
  449. break;
  450. }
  451. } else if (end === -1) {
  452. // We saw the first non-path separator, mark this as the end of our
  453. // path component
  454. matchedSlash = false;
  455. end = i + 1;
  456. }
  457. }
  458. if (end === -1) return '';
  459. return path.slice(start, end);
  460. }
  461. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  462. // in new Node.js versions, so only basename() above is backported here
  463. exports.basename = function (path, ext) {
  464. var f = basename(path);
  465. if (ext && f.substr(-1 * ext.length) === ext) {
  466. f = f.substr(0, f.length - ext.length);
  467. }
  468. return f;
  469. };
  470. exports.extname = function (path) {
  471. if (typeof path !== 'string') path = path + '';
  472. var startDot = -1;
  473. var startPart = 0;
  474. var end = -1;
  475. var matchedSlash = true;
  476. // Track the state of characters (if any) we see before our first dot and
  477. // after any path separator we find
  478. var preDotState = 0;
  479. for (var i = path.length - 1; i >= 0; --i) {
  480. var code = path.charCodeAt(i);
  481. if (code === 47 /*/*/) {
  482. // If we reached a path separator that was not part of a set of path
  483. // separators at the end of the string, stop now
  484. if (!matchedSlash) {
  485. startPart = i + 1;
  486. break;
  487. }
  488. continue;
  489. }
  490. if (end === -1) {
  491. // We saw the first non-path separator, mark this as the end of our
  492. // extension
  493. matchedSlash = false;
  494. end = i + 1;
  495. }
  496. if (code === 46 /*.*/) {
  497. // If this is our first dot, mark it as the start of our extension
  498. if (startDot === -1)
  499. startDot = i;
  500. else if (preDotState !== 1)
  501. preDotState = 1;
  502. } else if (startDot !== -1) {
  503. // We saw a non-dot and non-path separator before our dot, so we should
  504. // have a good chance at having a non-empty extension
  505. preDotState = -1;
  506. }
  507. }
  508. if (startDot === -1 || end === -1 ||
  509. // We saw a non-dot character immediately before the dot
  510. preDotState === 0 ||
  511. // The (right-most) trimmed path component is exactly '..'
  512. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  513. return '';
  514. }
  515. return path.slice(startDot, end);
  516. };
  517. function filter (xs, f) {
  518. if (xs.filter) return xs.filter(f);
  519. var res = [];
  520. for (var i = 0; i < xs.length; i++) {
  521. if (f(xs[i], i, xs)) res.push(xs[i]);
  522. }
  523. return res;
  524. }
  525. // String.prototype.substr - negative index don't work in IE8
  526. var substr = 'ab'.substr(-1) === 'b'
  527. ? function (str, start, len) { return str.substr(start, len) }
  528. : function (str, start, len) {
  529. if (start < 0) start = str.length + start;
  530. return str.substr(start, len);
  531. }
  532. ;
  533. },{"process":"../node_modules/process/browser.js"}],"../src/LRUCache.js":[function(require,module,exports) {
  534. "use strict";
  535. Object.defineProperty(exports, "__esModule", {
  536. value: true
  537. });
  538. exports.LRUCache = void 0;
  539. class LRUCache {
  540. constructor() {
  541. // options
  542. this.maxSize = 800;
  543. this.minSize = 600;
  544. this.unloadPercent = 0.2;
  545. this.usedSet = new Set();
  546. this.itemSet = new Set();
  547. this.itemList = [];
  548. this.callbacks = new Map();
  549. } // Returns whether or not the cache has reached the maximum size
  550. isFull() {
  551. return this.itemSet.size >= this.maxSize;
  552. }
  553. add(item, removeCb) {
  554. const itemSet = this.itemSet;
  555. if (itemSet.has(item)) {
  556. return false;
  557. }
  558. if (this.isFull()) {
  559. return false;
  560. }
  561. const usedSet = this.usedSet;
  562. const itemList = this.itemList;
  563. const callbacks = this.callbacks;
  564. itemList.push(item);
  565. usedSet.add(item);
  566. itemSet.add(item);
  567. callbacks.set(item, removeCb);
  568. return true;
  569. }
  570. remove(item) {
  571. const usedSet = this.usedSet;
  572. const itemSet = this.itemSet;
  573. const itemList = this.itemList;
  574. const callbacks = this.callbacks;
  575. if (itemSet.has(item)) {
  576. callbacks.get(item)(item);
  577. const index = itemList.indexOf(item);
  578. itemList.splice(index, 1);
  579. usedSet.delete(item);
  580. itemSet.delete(item);
  581. callbacks.delete(item);
  582. return true;
  583. }
  584. return false;
  585. }
  586. markUsed(item) {
  587. const itemSet = this.itemSet;
  588. const usedSet = this.usedSet;
  589. if (itemSet.has(item) && !usedSet.has(item)) {
  590. const itemList = this.itemList;
  591. const index = itemList.indexOf(item);
  592. itemList.splice(index, 1);
  593. itemList.push(item);
  594. usedSet.add(item);
  595. }
  596. }
  597. markAllUnused() {
  598. this.usedSet.clear();
  599. }
  600. unloadUnusedContent(prioritySortCb) {
  601. const unloadPercent = this.unloadPercent;
  602. const targetSize = this.minSize;
  603. const itemList = this.itemList;
  604. const itemSet = this.itemSet;
  605. const usedSet = this.usedSet;
  606. const callbacks = this.callbacks;
  607. const unused = itemList.length - usedSet.size;
  608. if (itemList.length > targetSize && unused > 0) {
  609. // TODO: sort by priority
  610. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  611. nodesToUnload = Math.ceil(nodesToUnload);
  612. nodesToUnload = Math.min(unused, nodesToUnload);
  613. const removedItems = itemList.splice(0, nodesToUnload);
  614. for (let i = 0, l = removedItems.length; i < l; i++) {
  615. const item = removedItems[i];
  616. callbacks.get(item)(item);
  617. itemSet.delete(item);
  618. callbacks.delete(item);
  619. }
  620. }
  621. }
  622. scheduleUnload(prioritySortCb, markAllUnused = true) {
  623. if (!this.scheduled) {
  624. this.scheduled = true;
  625. Promise.resolve().then(() => {
  626. this.scheduled = false;
  627. this.unloadUnusedContent(prioritySortCb);
  628. if (markAllUnused) {
  629. this.markAllUnused();
  630. }
  631. });
  632. }
  633. }
  634. }
  635. exports.LRUCache = LRUCache;
  636. },{}],"../src/PriorityQueue.js":[function(require,module,exports) {
  637. "use strict";
  638. Object.defineProperty(exports, "__esModule", {
  639. value: true
  640. });
  641. exports.PriorityQueue = void 0;
  642. class PriorityQueue {
  643. constructor(maxJobs = 6) {
  644. // options
  645. this.maxJobs = maxJobs;
  646. this.items = [];
  647. this.currJobs = 0;
  648. this.scheduled = false;
  649. }
  650. add(item, priority, callback) {
  651. return new Promise((resolve, reject) => {
  652. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  653. const items = this.items;
  654. for (let i = 0, l = items.length; i < l; i++) {
  655. const thisItem = items[i];
  656. if (thisItem.priority > priority) {
  657. items.splice(i, 0, {
  658. priority,
  659. item,
  660. callback: prCallback
  661. });
  662. this.scheduleJobRun();
  663. return;
  664. }
  665. }
  666. items.push({
  667. priority,
  668. item,
  669. callback: prCallback
  670. });
  671. this.scheduleJobRun();
  672. });
  673. }
  674. remove(item) {
  675. const items = this.items;
  676. for (let i = 0, l = items.length; i < l; i++) {
  677. const thisItem = items[i];
  678. if (thisItem.item === item) {
  679. items.splice(i, 1);
  680. break;
  681. }
  682. }
  683. }
  684. tryRunJobs() {
  685. const items = this.items;
  686. const maxJobs = this.maxJobs;
  687. while (maxJobs > this.currJobs && items.length > 0) {
  688. this.currJobs++;
  689. const {
  690. item,
  691. priority,
  692. callback
  693. } = items.pop();
  694. callback(item, priority).then(() => {
  695. this.currJobs--;
  696. this.scheduleJobRun();
  697. }).catch(() => {
  698. this.currJobs--;
  699. this.scheduleJobRun();
  700. });
  701. }
  702. }
  703. scheduleJobRun() {
  704. if (!this.scheduled) {
  705. Promise.resolve().then(() => {
  706. this.tryRunJobs();
  707. this.scheduled = false;
  708. });
  709. this.scheduled = true;
  710. }
  711. }
  712. }
  713. exports.PriorityQueue = PriorityQueue;
  714. },{}],"../src/TilesRenderer.js":[function(require,module,exports) {
  715. "use strict";
  716. Object.defineProperty(exports, "__esModule", {
  717. value: true
  718. });
  719. exports.TilesRenderer = void 0;
  720. var _path = _interopRequireDefault(require("path"));
  721. var _LRUCache = require("./LRUCache.js");
  722. var _PriorityQueue = require("./PriorityQueue.js");
  723. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  724. // TODO: find out why tiles are left dangling in the hierarchy
  725. // TODO: Address the issue of too many promises, garbage collection
  726. // TODO: remove more redundant computation
  727. // TODO: See if using classes improves performance
  728. // TODO: See if declaring function inline improves performance
  729. // TODO: Make sure active state works as expected
  730. const UNLOADED = 0;
  731. const LOADING = 1;
  732. const PARSING = 2;
  733. const LOADED = 3;
  734. const FAILED = 4;
  735. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  736. if (beforeCb && beforeCb(tile, parent, depth)) {
  737. if (afterCb) {
  738. afterCb(tile, parent, depth);
  739. }
  740. return;
  741. }
  742. const children = tile.children;
  743. for (let i = 0, l = children.length; i < l; i++) {
  744. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  745. }
  746. if (afterCb) {
  747. afterCb(tile, parent, depth);
  748. }
  749. }
  750. function isUsedThisFrame(tile, frameCount) {
  751. return tile.__lastFrameVisited === frameCount && tile.__used;
  752. }
  753. function resetFrameState(tile, frameCount) {
  754. if (tile.__lastFrameVisited !== frameCount) {
  755. tile.__lastFrameVisited = frameCount;
  756. tile.__used = false;
  757. tile.__inFrustum = false;
  758. tile.__isLeaf = false;
  759. tile.__visible = false;
  760. tile.__active = false;
  761. tile.__error = 0;
  762. }
  763. }
  764. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  765. resetFrameState(tile, frameCount);
  766. tile.__used = true;
  767. lruCache.markUsed(tile);
  768. if (tile.__contentEmpty) {
  769. const children = tile.children;
  770. for (let i = 0, l = children.length; i < l; i++) {
  771. recursivelyMarkUsed(children[i], frameCount, lruCache);
  772. }
  773. }
  774. } // TODO: include frustum mask here?
  775. function determineFrustumSet(tile, renderer) {
  776. const stats = renderer.stats;
  777. const frameCount = renderer.frameCount;
  778. const errorTarget = renderer.errorTarget;
  779. const maxDepth = renderer.maxDepth;
  780. const loadSiblings = renderer.loadSiblings;
  781. const lruCache = renderer.lruCache;
  782. resetFrameState(tile, frameCount);
  783. const inFrustum = renderer.tileInView(tile);
  784. if (inFrustum === false) {
  785. return false;
  786. }
  787. tile.__used = true;
  788. lruCache.markUsed(tile);
  789. tile.__inFrustum = true;
  790. stats.inFrustum++;
  791. if (!tile.__contentEmpty) {
  792. const error = renderer.calculateError(tile);
  793. tile.__error = error;
  794. if (error <= errorTarget) {
  795. return true;
  796. }
  797. }
  798. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  799. return true;
  800. }
  801. let anyChildrenUsed = false;
  802. const children = tile.children;
  803. for (let i = 0, l = children.length; i < l; i++) {
  804. const c = children[i];
  805. const r = determineFrustumSet(c, renderer);
  806. anyChildrenUsed = anyChildrenUsed || r;
  807. }
  808. if (anyChildrenUsed && loadSiblings) {
  809. for (let i = 0, l = children.length; i < l; i++) {
  810. recursivelyMarkUsed(tile, frameCount, lruCache);
  811. }
  812. }
  813. return true;
  814. }
  815. function markUsedSetLeaves(tile, renderer) {
  816. const stats = renderer.stats;
  817. const frameCount = renderer.frameCount;
  818. if (!isUsedThisFrame(tile, frameCount)) {
  819. return;
  820. }
  821. stats.used++;
  822. const children = tile.children;
  823. let anyChildrenUsed = false;
  824. for (let i = 0, l = children.length; i < l; i++) {
  825. const c = children[i];
  826. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  827. }
  828. if (!anyChildrenUsed) {
  829. tile.__isLeaf = true; // TODO: stats
  830. } else {
  831. for (let i = 0, l = children.length; i < l; i++) {
  832. const c = children[i];
  833. markUsedSetLeaves(c, renderer);
  834. }
  835. }
  836. }
  837. function skipTraversal(tile, renderer) {
  838. const stats = renderer.stats;
  839. const frameCount = renderer.frameCount;
  840. if (!isUsedThisFrame(tile, frameCount)) {
  841. return;
  842. }
  843. const lruCache = renderer.lruCache;
  844. if (tile.__isLeaf) {
  845. if (tile.__loadingState === LOADED) {
  846. if (tile.__inFrustum) {
  847. tile.__visible = true;
  848. stats.visible++;
  849. }
  850. tile.__active = true;
  851. stats.active++;
  852. } else if (!lruCache.isFull()) {
  853. renderer.requestTileContents(tile);
  854. }
  855. return;
  856. }
  857. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  858. const meetsSSE = tile.__error < errorRequirement;
  859. const hasContent = tile.__loadingState === LOADED && !tile.__contentEmpty;
  860. const children = tile.children;
  861. let allChildrenHaveContent = true;
  862. for (let i = 0, l = children.length; i < l; i++) {
  863. const c = children[i];
  864. if (isUsedThisFrame(c, frameCount)) {
  865. const childContent = c.__loadingState === LOADED || tile.__contentEmpty;
  866. allChildrenHaveContent = allChildrenHaveContent && childContent;
  867. }
  868. }
  869. if (meetsSSE && !hasContent && !lruCache.isFull()) {
  870. renderer.requestTileContents(tile);
  871. }
  872. if (meetsSSE && hasContent && !allChildrenHaveContent) {
  873. if (tile.__inFrustum) {
  874. tile.__visible = true;
  875. stats.visible++;
  876. }
  877. tile.__active = true;
  878. stats.active++;
  879. for (let i = 0, l = children.length; i < l; i++) {
  880. const c = children[i];
  881. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  882. renderer.requestTileContents(c);
  883. }
  884. }
  885. return;
  886. }
  887. for (let i = 0, l = children.length; i < l; i++) {
  888. const c = children[i];
  889. if (isUsedThisFrame(c, frameCount)) {
  890. skipTraversal(c, renderer);
  891. }
  892. }
  893. }
  894. function toggleTiles(tile, renderer) {
  895. const frameCount = renderer.frameCount;
  896. const isUsed = isUsedThisFrame(tile, frameCount);
  897. if (isUsed || tile.__usedLastFrame) {
  898. if (!isUsed) {
  899. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  900. renderer.setTileVisible(tile, false);
  901. renderer.setTileActive(tile, false);
  902. }
  903. tile.__usedLastFrame = false;
  904. } else {
  905. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  906. // enable visibility if active due to shadows
  907. renderer.setTileActive(tile, tile.__active);
  908. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  909. }
  910. tile.__usedLastFrame = true;
  911. }
  912. const children = tile.children;
  913. for (let i = 0, l = children.length; i < l; i++) {
  914. const c = children[i];
  915. toggleTiles(c, renderer);
  916. }
  917. }
  918. }
  919. class TilesRenderer {
  920. get root() {
  921. const tileSet = this.tileSets[this.rootSet];
  922. if (!tileSet || tileSet instanceof Promise) {
  923. return null;
  924. } else {
  925. return tileSet.root;
  926. }
  927. }
  928. constructor(url, cache = new _LRUCache.LRUCache(), downloadQueue = new _PriorityQueue.PriorityQueue(6), parseQueue = new _PriorityQueue.PriorityQueue(2)) {
  929. // state
  930. this.tileSets = {};
  931. this.rootSet = url;
  932. this.lruCache = cache;
  933. this.downloadQueue = downloadQueue;
  934. this.parseQueue = parseQueue;
  935. this.stats = {
  936. parsing: 0,
  937. downloading: 0,
  938. inFrustum: 0,
  939. used: 0,
  940. active: 0,
  941. visible: 0
  942. };
  943. this.frameCount = 0; // options
  944. this.errorTarget = 6.0;
  945. this.errorThreshold = 6.0;
  946. this.loadSiblings = true;
  947. this.maxDepth = Infinity;
  948. this.loadSiblings = true;
  949. this.loadTileSet(url);
  950. }
  951. traverse(cb) {
  952. const tileSets = this.tileSets;
  953. const rootTileSet = tileSets[this.rootSet];
  954. if (!rootTileSet || !rootTileSet.root) return;
  955. traverseSet(rootTileSet.root, cb);
  956. } // Public API
  957. update() {
  958. const stats = this.stats;
  959. const lruCache = this.lruCache;
  960. const tileSets = this.tileSets;
  961. const rootTileSet = tileSets[this.rootSet];
  962. if (!rootTileSet || !rootTileSet.root) return;
  963. const root = rootTileSet.root;
  964. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  965. determineFrustumSet(root, this);
  966. markUsedSetLeaves(root, this);
  967. skipTraversal(root, this);
  968. toggleTiles(root, this); // TODO: We may want to add this function in the requestTileContents function
  969. lruCache.scheduleUnload(null);
  970. } // Overrideable
  971. parseTile(buffer, tile) {
  972. return null;
  973. }
  974. disposeTile(tile) {}
  975. preprocessNode(tile, parentTile, tileSetDir) {
  976. if (tile.content) {
  977. if (!('uri' in tile.content) && 'url' in tile.content) {
  978. tile.content.uri = tile.content.url;
  979. delete tile.content.url;
  980. }
  981. if (tile.content.uri) {
  982. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  983. } // TODO: fix for some cases where tilesets provide the bounding volume
  984. // but volumes are not present. See
  985. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  986. delete tile.content.boundingVolume;
  987. }
  988. }
  989. tile.parent = parentTile;
  990. tile.children = tile.children || [];
  991. tile.__contentEmpty = !tile.content || !tile.content.uri;
  992. tile.__error = 0.0;
  993. tile.__inFrustum = false;
  994. tile.__isLeaf = false;
  995. tile.__wasUsed = false;
  996. tile.__used = false;
  997. tile.__wasVisible = false;
  998. tile.__visible = false;
  999. tile.__wasActive = false;
  1000. tile.__active = false;
  1001. tile.__childrenActive = false;
  1002. tile.__loadingState = UNLOADED;
  1003. tile.__loadIndex = 0;
  1004. tile.__loadAbort = null;
  1005. if (parentTile === null) {
  1006. tile.__depth = 0;
  1007. } else {
  1008. tile.__depth = parentTile.__depth + 1;
  1009. }
  1010. }
  1011. setTileActive(tile, state) {}
  1012. setTileVisible(tile, state) {}
  1013. calculateError(tile) {
  1014. return 0;
  1015. }
  1016. tileInView(tile) {
  1017. return true;
  1018. } // Private Functions
  1019. loadTileSet(url) {
  1020. const tileSets = this.tileSets;
  1021. if (!(url in tileSets)) {
  1022. const pr = fetch(url, {
  1023. credentials: 'same-origin'
  1024. }).then(res => {
  1025. if (res.ok) {
  1026. return res.json();
  1027. } else {
  1028. throw new Error(`Status ${res.status} (${res.statusText})`);
  1029. }
  1030. }).then(json => {
  1031. // TODO: Add version query?
  1032. const version = json.asset.version;
  1033. console.assert(version === '1.0' || version === '0.0');
  1034. const basePath = _path.default.dirname(url);
  1035. traverseSet(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  1036. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  1037. this.update();
  1038. });
  1039. pr.catch(e => {
  1040. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  1041. console.error(e);
  1042. delete tileSets[url];
  1043. });
  1044. tileSets[url] = pr;
  1045. }
  1046. return Promise.resolve(tileSets[url]);
  1047. }
  1048. requestTileContents(tile) {
  1049. // If the tile is already being loaded then don't
  1050. // start it again.
  1051. if (tile.__loadingState !== UNLOADED) {
  1052. return;
  1053. } // TODO: reuse the functions created here?
  1054. const lruCache = this.lruCache;
  1055. const downloadQueue = this.downloadQueue;
  1056. const parseQueue = this.parseQueue;
  1057. lruCache.add(tile, t => {
  1058. if (t.__loadingState === LOADING) {
  1059. t.__loadAbort.abort();
  1060. t.__loadAbort = null;
  1061. } else {
  1062. this.disposeTile(t);
  1063. }
  1064. if (t.__loadingState === LOADING) {
  1065. stats.downloading--;
  1066. } else if (t.__loadingState === PARSING) {
  1067. stats.parsing--;
  1068. }
  1069. t.__loadingState = UNLOADED;
  1070. t.__loadIndex++; // TODO: Removing from the queues here is slow
  1071. // parseQueue.remove( t );
  1072. // downloadQueue.remove( t );
  1073. });
  1074. tile.__loadIndex++;
  1075. const loadIndex = tile.__loadIndex;
  1076. const priority = 1 / (tile.__depth + 1);
  1077. const stats = this.stats;
  1078. const controller = new AbortController();
  1079. const signal = controller.signal;
  1080. stats.downloading++;
  1081. tile.__loadAbort = controller;
  1082. tile.__loadingState = LOADING;
  1083. downloadQueue.add(tile, priority, tile => {
  1084. if (tile.__loadIndex !== loadIndex) {
  1085. return Promise.resolve();
  1086. }
  1087. return fetch(tile.content.uri, {
  1088. credentials: 'same-origin',
  1089. signal
  1090. });
  1091. }).then(res => {
  1092. if (tile.__loadIndex !== loadIndex) {
  1093. return;
  1094. }
  1095. if (res.ok) {
  1096. return res.arrayBuffer();
  1097. } else {
  1098. throw new Error(`Failed to load model with error code ${res.status}`);
  1099. }
  1100. }).then(buffer => {
  1101. if (tile.__loadIndex !== loadIndex) {
  1102. return;
  1103. }
  1104. stats.downloading--;
  1105. stats.parsing++;
  1106. tile.__loadAbort = null;
  1107. tile.__loadingState = PARSING;
  1108. return parseQueue.add(buffer, priority, buffer => {
  1109. if (tile.__loadIndex !== loadIndex) {
  1110. return Promise.resolve();
  1111. }
  1112. return this.parseTile(buffer, tile);
  1113. });
  1114. }).then(() => {
  1115. if (tile.__loadIndex !== loadIndex) {
  1116. return;
  1117. }
  1118. stats.parsing--;
  1119. tile.__loadingState = LOADED;
  1120. this.setTileActive(tile, tile.__active);
  1121. this.setTileVisible(tile, tile.__visible);
  1122. }).catch(e => {
  1123. // if it has been unloaded then the tile has been disposed
  1124. if (tile.__loadIndex !== loadIndex) {
  1125. return;
  1126. }
  1127. if (e.name !== 'AbortError') {
  1128. console.error('TilesRenderer : Failed to load tile.');
  1129. console.error(e);
  1130. tile.__loadingState = FAILED;
  1131. } else {
  1132. lruCache.remove(tile);
  1133. }
  1134. });
  1135. }
  1136. }
  1137. exports.TilesRenderer = TilesRenderer;
  1138. },{"path":"../node_modules/path-browserify/index.js","./LRUCache.js":"../src/LRUCache.js","./PriorityQueue.js":"../src/PriorityQueue.js"}],"../src/B3DMLoader.js":[function(require,module,exports) {
  1139. "use strict";
  1140. Object.defineProperty(exports, "__esModule", {
  1141. value: true
  1142. });
  1143. exports.B3DMLoader = void 0;
  1144. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  1145. // convert an array of numbers to a string
  1146. function arrayToString(array) {
  1147. let str = '';
  1148. for (let i = 0, l = array.length; i < l; i++) {
  1149. str += String.fromCharCode(array[i]);
  1150. }
  1151. return str;
  1152. }
  1153. class B3DMLoader {
  1154. load(url) {
  1155. return fetch(url, {
  1156. credentials: 'same-origin'
  1157. }).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  1158. }
  1159. parse(buffer) {
  1160. const dataView = new DataView(buffer); // 28-byte header
  1161. // 4 bytes
  1162. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  1163. console.assert(magic === 'b3dm'); // 4 bytes
  1164. const version = dataView.getUint32(4, true);
  1165. console.assert(version === 1); // 4 bytes
  1166. const byteLength = dataView.getUint32(8, true);
  1167. console.assert(byteLength === buffer.byteLength); // 4 bytes
  1168. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  1169. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  1170. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  1171. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  1172. const featureTableStart = 28;
  1173. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  1174. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  1175. const binFeatureTableData = new Uint8Array(buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength); // TODO: dereference the json feature table data in to the binary array.
  1176. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1177. // Batch Table
  1178. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  1179. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  1180. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  1181. const binBatchTableData = new Uint8Array(buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength); // TODO: dereference the json batch table data in to the binary array.
  1182. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1183. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  1184. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  1185. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  1186. return {
  1187. version,
  1188. featureTable: jsonFeatureTable,
  1189. batchTable: jsonBatchTable,
  1190. glbBytes
  1191. };
  1192. }
  1193. }
  1194. exports.B3DMLoader = B3DMLoader;
  1195. },{}],"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  1196. "use strict";
  1197. Object.defineProperty(exports, "__esModule", {
  1198. value: true
  1199. });
  1200. exports.AmbientLight = AmbientLight;
  1201. exports.AmbientLightProbe = AmbientLightProbe;
  1202. exports.AnimationClip = AnimationClip;
  1203. exports.AnimationLoader = AnimationLoader;
  1204. exports.AnimationMixer = AnimationMixer;
  1205. exports.AnimationObjectGroup = AnimationObjectGroup;
  1206. exports.ArcCurve = ArcCurve;
  1207. exports.ArrayCamera = ArrayCamera;
  1208. exports.ArrowHelper = ArrowHelper;
  1209. exports.Audio = Audio;
  1210. exports.AudioAnalyser = AudioAnalyser;
  1211. exports.AudioListener = AudioListener;
  1212. exports.AudioLoader = AudioLoader;
  1213. exports.AxesHelper = AxesHelper;
  1214. exports.AxisHelper = AxisHelper;
  1215. exports.BinaryTextureLoader = BinaryTextureLoader;
  1216. exports.Bone = Bone;
  1217. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  1218. exports.BoundingBoxHelper = BoundingBoxHelper;
  1219. exports.Box2 = Box2;
  1220. exports.Box3 = Box3;
  1221. exports.Box3Helper = Box3Helper;
  1222. exports.BoxHelper = BoxHelper;
  1223. exports.BufferAttribute = BufferAttribute;
  1224. exports.BufferGeometry = BufferGeometry;
  1225. exports.BufferGeometryLoader = BufferGeometryLoader;
  1226. exports.Camera = Camera;
  1227. exports.CameraHelper = CameraHelper;
  1228. exports.CanvasRenderer = CanvasRenderer;
  1229. exports.CanvasTexture = CanvasTexture;
  1230. exports.CatmullRomCurve3 = CatmullRomCurve3;
  1231. exports.CircleBufferGeometry = CircleBufferGeometry;
  1232. exports.CircleGeometry = CircleGeometry;
  1233. exports.Clock = Clock;
  1234. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  1235. exports.Color = Color;
  1236. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  1237. exports.CompressedTexture = CompressedTexture;
  1238. exports.CompressedTextureLoader = CompressedTextureLoader;
  1239. exports.ConeBufferGeometry = ConeBufferGeometry;
  1240. exports.ConeGeometry = ConeGeometry;
  1241. exports.CubeCamera = CubeCamera;
  1242. exports.CubeTexture = CubeTexture;
  1243. exports.CubeTextureLoader = CubeTextureLoader;
  1244. exports.CubicBezierCurve = CubicBezierCurve;
  1245. exports.CubicBezierCurve3 = CubicBezierCurve3;
  1246. exports.CubicInterpolant = CubicInterpolant;
  1247. exports.Curve = Curve;
  1248. exports.CurvePath = CurvePath;
  1249. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  1250. exports.CylinderGeometry = CylinderGeometry;
  1251. exports.Cylindrical = Cylindrical;
  1252. exports.DataTexture = DataTexture;
  1253. exports.DataTexture2DArray = DataTexture2DArray;
  1254. exports.DataTexture3D = DataTexture3D;
  1255. exports.DataTextureLoader = DataTextureLoader;
  1256. exports.DepthTexture = DepthTexture;
  1257. exports.DirectionalLight = DirectionalLight;
  1258. exports.DirectionalLightHelper = DirectionalLightHelper;
  1259. exports.DirectionalLightShadow = DirectionalLightShadow;
  1260. exports.DiscreteInterpolant = DiscreteInterpolant;
  1261. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  1262. exports.DodecahedronGeometry = DodecahedronGeometry;
  1263. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  1264. exports.EdgesGeometry = EdgesGeometry;
  1265. exports.EdgesHelper = EdgesHelper;
  1266. exports.EllipseCurve = EllipseCurve;
  1267. exports.Euler = Euler;
  1268. exports.EventDispatcher = EventDispatcher;
  1269. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  1270. exports.ExtrudeGeometry = ExtrudeGeometry;
  1271. exports.Face3 = Face3;
  1272. exports.Face4 = Face4;
  1273. exports.FaceNormalsHelper = FaceNormalsHelper;
  1274. exports.FileLoader = FileLoader;
  1275. exports.Float32Attribute = Float32Attribute;
  1276. exports.Float32BufferAttribute = Float32BufferAttribute;
  1277. exports.Float64Attribute = Float64Attribute;
  1278. exports.Float64BufferAttribute = Float64BufferAttribute;
  1279. exports.Fog = Fog;
  1280. exports.FogExp2 = FogExp2;
  1281. exports.Font = Font;
  1282. exports.FontLoader = FontLoader;
  1283. exports.Frustum = Frustum;
  1284. exports.Geometry = Geometry;
  1285. exports.GridHelper = GridHelper;
  1286. exports.Group = Group;
  1287. exports.HemisphereLight = HemisphereLight;
  1288. exports.HemisphereLightHelper = HemisphereLightHelper;
  1289. exports.HemisphereLightProbe = HemisphereLightProbe;
  1290. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  1291. exports.IcosahedronGeometry = IcosahedronGeometry;
  1292. exports.ImageBitmapLoader = ImageBitmapLoader;
  1293. exports.ImageLoader = ImageLoader;
  1294. exports.ImmediateRenderObject = ImmediateRenderObject;
  1295. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  1296. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  1297. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  1298. exports.InstancedMesh = InstancedMesh;
  1299. exports.Int16Attribute = Int16Attribute;
  1300. exports.Int16BufferAttribute = Int16BufferAttribute;
  1301. exports.Int32Attribute = Int32Attribute;
  1302. exports.Int32BufferAttribute = Int32BufferAttribute;
  1303. exports.Int8Attribute = Int8Attribute;
  1304. exports.Int8BufferAttribute = Int8BufferAttribute;
  1305. exports.InterleavedBuffer = InterleavedBuffer;
  1306. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  1307. exports.Interpolant = Interpolant;
  1308. exports.JSONLoader = JSONLoader;
  1309. exports.KeyframeTrack = KeyframeTrack;
  1310. exports.LOD = LOD;
  1311. exports.LatheBufferGeometry = LatheBufferGeometry;
  1312. exports.LatheGeometry = LatheGeometry;
  1313. exports.Layers = Layers;
  1314. exports.LensFlare = LensFlare;
  1315. exports.Light = Light;
  1316. exports.LightProbe = LightProbe;
  1317. exports.LightProbeHelper = LightProbeHelper;
  1318. exports.LightShadow = LightShadow;
  1319. exports.Line = Line;
  1320. exports.Line3 = Line3;
  1321. exports.LineBasicMaterial = LineBasicMaterial;
  1322. exports.LineCurve = LineCurve;
  1323. exports.LineCurve3 = LineCurve3;
  1324. exports.LineDashedMaterial = LineDashedMaterial;
  1325. exports.LineLoop = LineLoop;
  1326. exports.LineSegments = LineSegments;
  1327. exports.LinearInterpolant = LinearInterpolant;
  1328. exports.Loader = Loader;
  1329. exports.LoadingManager = LoadingManager;
  1330. exports.Material = Material;
  1331. exports.MaterialLoader = MaterialLoader;
  1332. exports.Matrix3 = Matrix3;
  1333. exports.Matrix4 = Matrix4;
  1334. exports.Mesh = Mesh;
  1335. exports.MeshBasicMaterial = MeshBasicMaterial;
  1336. exports.MeshDepthMaterial = MeshDepthMaterial;
  1337. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  1338. exports.MeshFaceMaterial = MeshFaceMaterial;
  1339. exports.MeshLambertMaterial = MeshLambertMaterial;
  1340. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  1341. exports.MeshNormalMaterial = MeshNormalMaterial;
  1342. exports.MeshPhongMaterial = MeshPhongMaterial;
  1343. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  1344. exports.MeshStandardMaterial = MeshStandardMaterial;
  1345. exports.MeshToonMaterial = MeshToonMaterial;
  1346. exports.MultiMaterial = MultiMaterial;
  1347. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  1348. exports.Object3D = Object3D;
  1349. exports.ObjectLoader = ObjectLoader;
  1350. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  1351. exports.OctahedronGeometry = OctahedronGeometry;
  1352. exports.OrthographicCamera = OrthographicCamera;
  1353. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  1354. exports.ParametricGeometry = ParametricGeometry;
  1355. exports.Particle = Particle;
  1356. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  1357. exports.ParticleSystem = ParticleSystem;
  1358. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  1359. exports.Path = Path;
  1360. exports.PerspectiveCamera = PerspectiveCamera;
  1361. exports.Plane = Plane;
  1362. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  1363. exports.PlaneGeometry = PlaneGeometry;
  1364. exports.PlaneHelper = PlaneHelper;
  1365. exports.PointCloud = PointCloud;
  1366. exports.PointCloudMaterial = PointCloudMaterial;
  1367. exports.PointLight = PointLight;
  1368. exports.PointLightHelper = PointLightHelper;
  1369. exports.Points = Points;
  1370. exports.PointsMaterial = PointsMaterial;
  1371. exports.PolarGridHelper = PolarGridHelper;
  1372. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  1373. exports.PolyhedronGeometry = PolyhedronGeometry;
  1374. exports.PositionalAudio = PositionalAudio;
  1375. exports.PositionalAudioHelper = PositionalAudioHelper;
  1376. exports.PropertyBinding = PropertyBinding;
  1377. exports.PropertyMixer = PropertyMixer;
  1378. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  1379. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  1380. exports.Quaternion = Quaternion;
  1381. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  1382. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  1383. exports.RawShaderMaterial = RawShaderMaterial;
  1384. exports.Ray = Ray;
  1385. exports.Raycaster = Raycaster;
  1386. exports.RectAreaLight = RectAreaLight;
  1387. exports.RectAreaLightHelper = RectAreaLightHelper;
  1388. exports.RingBufferGeometry = RingBufferGeometry;
  1389. exports.RingGeometry = RingGeometry;
  1390. exports.Scene = Scene;
  1391. exports.ShaderMaterial = ShaderMaterial;
  1392. exports.ShadowMaterial = ShadowMaterial;
  1393. exports.Shape = Shape;
  1394. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  1395. exports.ShapeGeometry = ShapeGeometry;
  1396. exports.ShapePath = ShapePath;
  1397. exports.Skeleton = Skeleton;
  1398. exports.SkeletonHelper = SkeletonHelper;
  1399. exports.SkinnedMesh = SkinnedMesh;
  1400. exports.Sphere = Sphere;
  1401. exports.SphereBufferGeometry = SphereBufferGeometry;
  1402. exports.SphereGeometry = SphereGeometry;
  1403. exports.Spherical = Spherical;
  1404. exports.SphericalHarmonics3 = SphericalHarmonics3;
  1405. exports.Spline = Spline;
  1406. exports.SplineCurve = SplineCurve;
  1407. exports.SplineCurve3 = SplineCurve3;
  1408. exports.SpotLight = SpotLight;
  1409. exports.SpotLightHelper = SpotLightHelper;
  1410. exports.SpotLightShadow = SpotLightShadow;
  1411. exports.Sprite = Sprite;
  1412. exports.SpriteMaterial = SpriteMaterial;
  1413. exports.StereoCamera = StereoCamera;
  1414. exports.StringKeyframeTrack = StringKeyframeTrack;
  1415. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  1416. exports.TetrahedronGeometry = TetrahedronGeometry;
  1417. exports.TextBufferGeometry = TextBufferGeometry;
  1418. exports.TextGeometry = TextGeometry;
  1419. exports.Texture = Texture;
  1420. exports.TextureLoader = TextureLoader;
  1421. exports.TorusBufferGeometry = TorusBufferGeometry;
  1422. exports.TorusGeometry = TorusGeometry;
  1423. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  1424. exports.TorusKnotGeometry = TorusKnotGeometry;
  1425. exports.Triangle = Triangle;
  1426. exports.TubeBufferGeometry = TubeBufferGeometry;
  1427. exports.TubeGeometry = TubeGeometry;
  1428. exports.Uint16Attribute = Uint16Attribute;
  1429. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  1430. exports.Uint32Attribute = Uint32Attribute;
  1431. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  1432. exports.Uint8Attribute = Uint8Attribute;
  1433. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  1434. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  1435. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  1436. exports.Uniform = Uniform;
  1437. exports.Vector2 = Vector2;
  1438. exports.Vector3 = Vector3;
  1439. exports.Vector4 = Vector4;
  1440. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  1441. exports.Vertex = Vertex;
  1442. exports.VertexNormalsHelper = VertexNormalsHelper;
  1443. exports.VideoTexture = VideoTexture;
  1444. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  1445. exports.WebGLRenderTarget = WebGLRenderTarget;
  1446. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  1447. exports.WebGLRenderer = WebGLRenderer;
  1448. exports.WebGLUtils = WebGLUtils;
  1449. exports.WireframeGeometry = WireframeGeometry;
  1450. exports.WireframeHelper = WireframeHelper;
  1451. exports.XHRLoader = XHRLoader;
  1452. exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = exports.NeverDepth = exports.NearestMipmapNearestFilter = exports.NearestMipmapLinearFilter = exports.NearestMipMapNearestFilter = exports.NearestMipMapLinearFilter = exports.NearestFilter = exports.MultiplyOperation = exports.MultiplyBlending = exports.MixOperation = exports.MirroredRepeatWrapping = exports.MinEquation = exports.MaxEquation = exports.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.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;
  1453. 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 = exports.UniformsLib = exports.Uncharted2ToneMapping = exports.UVMapping = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SphericalReflectionMapping = exports.SmoothShading = exports.ShortType = exports.ShapeUtils = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = 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_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.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 = void 0;
  1454. // Polyfills
  1455. if (Number.EPSILON === undefined) {
  1456. Number.EPSILON = Math.pow(2, -52);
  1457. }
  1458. if (Number.isInteger === undefined) {
  1459. // Missing in IE
  1460. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  1461. Number.isInteger = function (value) {
  1462. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  1463. };
  1464. } //
  1465. if (Math.sign === undefined) {
  1466. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  1467. Math.sign = function (x) {
  1468. return x < 0 ? -1 : x > 0 ? 1 : +x;
  1469. };
  1470. }
  1471. if ('name' in Function.prototype === false) {
  1472. // Missing in IE
  1473. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  1474. Object.defineProperty(Function.prototype, 'name', {
  1475. get: function () {
  1476. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  1477. }
  1478. });
  1479. }
  1480. if (Object.assign === undefined) {
  1481. // Missing in IE
  1482. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  1483. Object.assign = function (target) {
  1484. if (target === undefined || target === null) {
  1485. throw new TypeError('Cannot convert undefined or null to object');
  1486. }
  1487. var output = Object(target);
  1488. for (var index = 1; index < arguments.length; index++) {
  1489. var source = arguments[index];
  1490. if (source !== undefined && source !== null) {
  1491. for (var nextKey in source) {
  1492. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  1493. output[nextKey] = source[nextKey];
  1494. }
  1495. }
  1496. }
  1497. }
  1498. return output;
  1499. };
  1500. }
  1501. var REVISION = '109';
  1502. exports.REVISION = REVISION;
  1503. var MOUSE = {
  1504. LEFT: 0,
  1505. MIDDLE: 1,
  1506. RIGHT: 2,
  1507. ROTATE: 0,
  1508. DOLLY: 1,
  1509. PAN: 2
  1510. };
  1511. exports.MOUSE = MOUSE;
  1512. var TOUCH = {
  1513. ROTATE: 0,
  1514. PAN: 1,
  1515. DOLLY_PAN: 2,
  1516. DOLLY_ROTATE: 3
  1517. };
  1518. exports.TOUCH = TOUCH;
  1519. var CullFaceNone = 0;
  1520. exports.CullFaceNone = CullFaceNone;
  1521. var CullFaceBack = 1;
  1522. exports.CullFaceBack = CullFaceBack;
  1523. var CullFaceFront = 2;
  1524. exports.CullFaceFront = CullFaceFront;
  1525. var CullFaceFrontBack = 3;
  1526. exports.CullFaceFrontBack = CullFaceFrontBack;
  1527. var FrontFaceDirectionCW = 0;
  1528. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  1529. var FrontFaceDirectionCCW = 1;
  1530. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  1531. var BasicShadowMap = 0;
  1532. exports.BasicShadowMap = BasicShadowMap;
  1533. var PCFShadowMap = 1;
  1534. exports.PCFShadowMap = PCFShadowMap;
  1535. var PCFSoftShadowMap = 2;
  1536. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  1537. var VSMShadowMap = 3;
  1538. exports.VSMShadowMap = VSMShadowMap;
  1539. var FrontSide = 0;
  1540. exports.FrontSide = FrontSide;
  1541. var BackSide = 1;
  1542. exports.BackSide = BackSide;
  1543. var DoubleSide = 2;
  1544. exports.DoubleSide = DoubleSide;
  1545. var FlatShading = 1;
  1546. exports.FlatShading = FlatShading;
  1547. var SmoothShading = 2;
  1548. exports.SmoothShading = SmoothShading;
  1549. var NoColors = 0;
  1550. exports.NoColors = NoColors;
  1551. var FaceColors = 1;
  1552. exports.FaceColors = FaceColors;
  1553. var VertexColors = 2;
  1554. exports.VertexColors = VertexColors;
  1555. var NoBlending = 0;
  1556. exports.NoBlending = NoBlending;
  1557. var NormalBlending = 1;
  1558. exports.NormalBlending = NormalBlending;
  1559. var AdditiveBlending = 2;
  1560. exports.AdditiveBlending = AdditiveBlending;
  1561. var SubtractiveBlending = 3;
  1562. exports.SubtractiveBlending = SubtractiveBlending;
  1563. var MultiplyBlending = 4;
  1564. exports.MultiplyBlending = MultiplyBlending;
  1565. var CustomBlending = 5;
  1566. exports.CustomBlending = CustomBlending;
  1567. var AddEquation = 100;
  1568. exports.AddEquation = AddEquation;
  1569. var SubtractEquation = 101;
  1570. exports.SubtractEquation = SubtractEquation;
  1571. var ReverseSubtractEquation = 102;
  1572. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  1573. var MinEquation = 103;
  1574. exports.MinEquation = MinEquation;
  1575. var MaxEquation = 104;
  1576. exports.MaxEquation = MaxEquation;
  1577. var ZeroFactor = 200;
  1578. exports.ZeroFactor = ZeroFactor;
  1579. var OneFactor = 201;
  1580. exports.OneFactor = OneFactor;
  1581. var SrcColorFactor = 202;
  1582. exports.SrcColorFactor = SrcColorFactor;
  1583. var OneMinusSrcColorFactor = 203;
  1584. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  1585. var SrcAlphaFactor = 204;
  1586. exports.SrcAlphaFactor = SrcAlphaFactor;
  1587. var OneMinusSrcAlphaFactor = 205;
  1588. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  1589. var DstAlphaFactor = 206;
  1590. exports.DstAlphaFactor = DstAlphaFactor;
  1591. var OneMinusDstAlphaFactor = 207;
  1592. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  1593. var DstColorFactor = 208;
  1594. exports.DstColorFactor = DstColorFactor;
  1595. var OneMinusDstColorFactor = 209;
  1596. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  1597. var SrcAlphaSaturateFactor = 210;
  1598. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  1599. var NeverDepth = 0;
  1600. exports.NeverDepth = NeverDepth;
  1601. var AlwaysDepth = 1;
  1602. exports.AlwaysDepth = AlwaysDepth;
  1603. var LessDepth = 2;
  1604. exports.LessDepth = LessDepth;
  1605. var LessEqualDepth = 3;
  1606. exports.LessEqualDepth = LessEqualDepth;
  1607. var EqualDepth = 4;
  1608. exports.EqualDepth = EqualDepth;
  1609. var GreaterEqualDepth = 5;
  1610. exports.GreaterEqualDepth = GreaterEqualDepth;
  1611. var GreaterDepth = 6;
  1612. exports.GreaterDepth = GreaterDepth;
  1613. var NotEqualDepth = 7;
  1614. exports.NotEqualDepth = NotEqualDepth;
  1615. var MultiplyOperation = 0;
  1616. exports.MultiplyOperation = MultiplyOperation;
  1617. var MixOperation = 1;
  1618. exports.MixOperation = MixOperation;
  1619. var AddOperation = 2;
  1620. exports.AddOperation = AddOperation;
  1621. var NoToneMapping = 0;
  1622. exports.NoToneMapping = NoToneMapping;
  1623. var LinearToneMapping = 1;
  1624. exports.LinearToneMapping = LinearToneMapping;
  1625. var ReinhardToneMapping = 2;
  1626. exports.ReinhardToneMapping = ReinhardToneMapping;
  1627. var Uncharted2ToneMapping = 3;
  1628. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  1629. var CineonToneMapping = 4;
  1630. exports.CineonToneMapping = CineonToneMapping;
  1631. var ACESFilmicToneMapping = 5;
  1632. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  1633. var UVMapping = 300;
  1634. exports.UVMapping = UVMapping;
  1635. var CubeReflectionMapping = 301;
  1636. exports.CubeReflectionMapping = CubeReflectionMapping;
  1637. var CubeRefractionMapping = 302;
  1638. exports.CubeRefractionMapping = CubeRefractionMapping;
  1639. var EquirectangularReflectionMapping = 303;
  1640. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  1641. var EquirectangularRefractionMapping = 304;
  1642. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  1643. var SphericalReflectionMapping = 305;
  1644. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  1645. var CubeUVReflectionMapping = 306;
  1646. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  1647. var CubeUVRefractionMapping = 307;
  1648. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  1649. var RepeatWrapping = 1000;
  1650. exports.RepeatWrapping = RepeatWrapping;
  1651. var ClampToEdgeWrapping = 1001;
  1652. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  1653. var MirroredRepeatWrapping = 1002;
  1654. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  1655. var NearestFilter = 1003;
  1656. exports.NearestFilter = NearestFilter;
  1657. var NearestMipmapNearestFilter = 1004;
  1658. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  1659. var NearestMipMapNearestFilter = 1004;
  1660. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  1661. var NearestMipmapLinearFilter = 1005;
  1662. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  1663. var NearestMipMapLinearFilter = 1005;
  1664. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  1665. var LinearFilter = 1006;
  1666. exports.LinearFilter = LinearFilter;
  1667. var LinearMipmapNearestFilter = 1007;
  1668. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  1669. var LinearMipMapNearestFilter = 1007;
  1670. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  1671. var LinearMipmapLinearFilter = 1008;
  1672. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  1673. var LinearMipMapLinearFilter = 1008;
  1674. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  1675. var UnsignedByteType = 1009;
  1676. exports.UnsignedByteType = UnsignedByteType;
  1677. var ByteType = 1010;
  1678. exports.ByteType = ByteType;
  1679. var ShortType = 1011;
  1680. exports.ShortType = ShortType;
  1681. var UnsignedShortType = 1012;
  1682. exports.UnsignedShortType = UnsignedShortType;
  1683. var IntType = 1013;
  1684. exports.IntType = IntType;
  1685. var UnsignedIntType = 1014;
  1686. exports.UnsignedIntType = UnsignedIntType;
  1687. var FloatType = 1015;
  1688. exports.FloatType = FloatType;
  1689. var HalfFloatType = 1016;
  1690. exports.HalfFloatType = HalfFloatType;
  1691. var UnsignedShort4444Type = 1017;
  1692. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  1693. var UnsignedShort5551Type = 1018;
  1694. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  1695. var UnsignedShort565Type = 1019;
  1696. exports.UnsignedShort565Type = UnsignedShort565Type;
  1697. var UnsignedInt248Type = 1020;
  1698. exports.UnsignedInt248Type = UnsignedInt248Type;
  1699. var AlphaFormat = 1021;
  1700. exports.AlphaFormat = AlphaFormat;
  1701. var RGBFormat = 1022;
  1702. exports.RGBFormat = RGBFormat;
  1703. var RGBAFormat = 1023;
  1704. exports.RGBAFormat = RGBAFormat;
  1705. var LuminanceFormat = 1024;
  1706. exports.LuminanceFormat = LuminanceFormat;
  1707. var LuminanceAlphaFormat = 1025;
  1708. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  1709. var RGBEFormat = RGBAFormat;
  1710. exports.RGBEFormat = RGBEFormat;
  1711. var DepthFormat = 1026;
  1712. exports.DepthFormat = DepthFormat;
  1713. var DepthStencilFormat = 1027;
  1714. exports.DepthStencilFormat = DepthStencilFormat;
  1715. var RedFormat = 1028;
  1716. exports.RedFormat = RedFormat;
  1717. var RGB_S3TC_DXT1_Format = 33776;
  1718. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  1719. var RGBA_S3TC_DXT1_Format = 33777;
  1720. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  1721. var RGBA_S3TC_DXT3_Format = 33778;
  1722. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  1723. var RGBA_S3TC_DXT5_Format = 33779;
  1724. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  1725. var RGB_PVRTC_4BPPV1_Format = 35840;
  1726. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  1727. var RGB_PVRTC_2BPPV1_Format = 35841;
  1728. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  1729. var RGBA_PVRTC_4BPPV1_Format = 35842;
  1730. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  1731. var RGBA_PVRTC_2BPPV1_Format = 35843;
  1732. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  1733. var RGB_ETC1_Format = 36196;
  1734. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  1735. var RGBA_ASTC_4x4_Format = 37808;
  1736. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  1737. var RGBA_ASTC_5x4_Format = 37809;
  1738. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  1739. var RGBA_ASTC_5x5_Format = 37810;
  1740. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  1741. var RGBA_ASTC_6x5_Format = 37811;
  1742. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  1743. var RGBA_ASTC_6x6_Format = 37812;
  1744. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  1745. var RGBA_ASTC_8x5_Format = 37813;
  1746. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  1747. var RGBA_ASTC_8x6_Format = 37814;
  1748. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  1749. var RGBA_ASTC_8x8_Format = 37815;
  1750. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  1751. var RGBA_ASTC_10x5_Format = 37816;
  1752. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  1753. var RGBA_ASTC_10x6_Format = 37817;
  1754. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  1755. var RGBA_ASTC_10x8_Format = 37818;
  1756. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  1757. var RGBA_ASTC_10x10_Format = 37819;
  1758. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  1759. var RGBA_ASTC_12x10_Format = 37820;
  1760. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  1761. var RGBA_ASTC_12x12_Format = 37821;
  1762. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  1763. var LoopOnce = 2200;
  1764. exports.LoopOnce = LoopOnce;
  1765. var LoopRepeat = 2201;
  1766. exports.LoopRepeat = LoopRepeat;
  1767. var LoopPingPong = 2202;
  1768. exports.LoopPingPong = LoopPingPong;
  1769. var InterpolateDiscrete = 2300;
  1770. exports.InterpolateDiscrete = InterpolateDiscrete;
  1771. var InterpolateLinear = 2301;
  1772. exports.InterpolateLinear = InterpolateLinear;
  1773. var InterpolateSmooth = 2302;
  1774. exports.InterpolateSmooth = InterpolateSmooth;
  1775. var ZeroCurvatureEnding = 2400;
  1776. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  1777. var ZeroSlopeEnding = 2401;
  1778. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  1779. var WrapAroundEnding = 2402;
  1780. exports.WrapAroundEnding = WrapAroundEnding;
  1781. var TrianglesDrawMode = 0;
  1782. exports.TrianglesDrawMode = TrianglesDrawMode;
  1783. var TriangleStripDrawMode = 1;
  1784. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  1785. var TriangleFanDrawMode = 2;
  1786. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  1787. var LinearEncoding = 3000;
  1788. exports.LinearEncoding = LinearEncoding;
  1789. var sRGBEncoding = 3001;
  1790. exports.sRGBEncoding = sRGBEncoding;
  1791. var GammaEncoding = 3007;
  1792. exports.GammaEncoding = GammaEncoding;
  1793. var RGBEEncoding = 3002;
  1794. exports.RGBEEncoding = RGBEEncoding;
  1795. var LogLuvEncoding = 3003;
  1796. exports.LogLuvEncoding = LogLuvEncoding;
  1797. var RGBM7Encoding = 3004;
  1798. exports.RGBM7Encoding = RGBM7Encoding;
  1799. var RGBM16Encoding = 3005;
  1800. exports.RGBM16Encoding = RGBM16Encoding;
  1801. var RGBDEncoding = 3006;
  1802. exports.RGBDEncoding = RGBDEncoding;
  1803. var BasicDepthPacking = 3200;
  1804. exports.BasicDepthPacking = BasicDepthPacking;
  1805. var RGBADepthPacking = 3201;
  1806. exports.RGBADepthPacking = RGBADepthPacking;
  1807. var TangentSpaceNormalMap = 0;
  1808. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  1809. var ObjectSpaceNormalMap = 1;
  1810. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  1811. var ZeroStencilOp = 0;
  1812. exports.ZeroStencilOp = ZeroStencilOp;
  1813. var KeepStencilOp = 7680;
  1814. exports.KeepStencilOp = KeepStencilOp;
  1815. var ReplaceStencilOp = 7681;
  1816. exports.ReplaceStencilOp = ReplaceStencilOp;
  1817. var IncrementStencilOp = 7682;
  1818. exports.IncrementStencilOp = IncrementStencilOp;
  1819. var DecrementStencilOp = 7683;
  1820. exports.DecrementStencilOp = DecrementStencilOp;
  1821. var IncrementWrapStencilOp = 34055;
  1822. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  1823. var DecrementWrapStencilOp = 34056;
  1824. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  1825. var InvertStencilOp = 5386;
  1826. exports.InvertStencilOp = InvertStencilOp;
  1827. var NeverStencilFunc = 512;
  1828. exports.NeverStencilFunc = NeverStencilFunc;
  1829. var LessStencilFunc = 513;
  1830. exports.LessStencilFunc = LessStencilFunc;
  1831. var EqualStencilFunc = 514;
  1832. exports.EqualStencilFunc = EqualStencilFunc;
  1833. var LessEqualStencilFunc = 515;
  1834. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  1835. var GreaterStencilFunc = 516;
  1836. exports.GreaterStencilFunc = GreaterStencilFunc;
  1837. var NotEqualStencilFunc = 517;
  1838. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  1839. var GreaterEqualStencilFunc = 518;
  1840. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  1841. var AlwaysStencilFunc = 519;
  1842. /**
  1843. * https://github.com/mrdoob/eventdispatcher.js/
  1844. */
  1845. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  1846. function EventDispatcher() {}
  1847. Object.assign(EventDispatcher.prototype, {
  1848. addEventListener: function (type, listener) {
  1849. if (this._listeners === undefined) this._listeners = {};
  1850. var listeners = this._listeners;
  1851. if (listeners[type] === undefined) {
  1852. listeners[type] = [];
  1853. }
  1854. if (listeners[type].indexOf(listener) === -1) {
  1855. listeners[type].push(listener);
  1856. }
  1857. },
  1858. hasEventListener: function (type, listener) {
  1859. if (this._listeners === undefined) return false;
  1860. var listeners = this._listeners;
  1861. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  1862. },
  1863. removeEventListener: function (type, listener) {
  1864. if (this._listeners === undefined) return;
  1865. var listeners = this._listeners;
  1866. var listenerArray = listeners[type];
  1867. if (listenerArray !== undefined) {
  1868. var index = listenerArray.indexOf(listener);
  1869. if (index !== -1) {
  1870. listenerArray.splice(index, 1);
  1871. }
  1872. }
  1873. },
  1874. dispatchEvent: function (event) {
  1875. if (this._listeners === undefined) return;
  1876. var listeners = this._listeners;
  1877. var listenerArray = listeners[event.type];
  1878. if (listenerArray !== undefined) {
  1879. event.target = this;
  1880. var array = listenerArray.slice(0);
  1881. for (var i = 0, l = array.length; i < l; i++) {
  1882. array[i].call(this, event);
  1883. }
  1884. }
  1885. }
  1886. });
  1887. /**
  1888. * @author alteredq / http://alteredqualia.com/
  1889. * @author mrdoob / http://mrdoob.com/
  1890. */
  1891. var _lut = [];
  1892. for (var i = 0; i < 256; i++) {
  1893. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  1894. }
  1895. var _Math = {
  1896. DEG2RAD: Math.PI / 180,
  1897. RAD2DEG: 180 / Math.PI,
  1898. generateUUID: function () {
  1899. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1900. var d0 = Math.random() * 0xffffffff | 0;
  1901. var d1 = Math.random() * 0xffffffff | 0;
  1902. var d2 = Math.random() * 0xffffffff | 0;
  1903. var d3 = Math.random() * 0xffffffff | 0;
  1904. 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.
  1905. return uuid.toUpperCase();
  1906. },
  1907. clamp: function (value, min, max) {
  1908. return Math.max(min, Math.min(max, value));
  1909. },
  1910. // compute euclidian modulo of m % n
  1911. // https://en.wikipedia.org/wiki/Modulo_operation
  1912. euclideanModulo: function (n, m) {
  1913. return (n % m + m) % m;
  1914. },
  1915. // Linear mapping from range <a1, a2> to range <b1, b2>
  1916. mapLinear: function (x, a1, a2, b1, b2) {
  1917. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  1918. },
  1919. // https://en.wikipedia.org/wiki/Linear_interpolation
  1920. lerp: function (x, y, t) {
  1921. return (1 - t) * x + t * y;
  1922. },
  1923. // http://en.wikipedia.org/wiki/Smoothstep
  1924. smoothstep: function (x, min, max) {
  1925. if (x <= min) return 0;
  1926. if (x >= max) return 1;
  1927. x = (x - min) / (max - min);
  1928. return x * x * (3 - 2 * x);
  1929. },
  1930. smootherstep: function (x, min, max) {
  1931. if (x <= min) return 0;
  1932. if (x >= max) return 1;
  1933. x = (x - min) / (max - min);
  1934. return x * x * x * (x * (x * 6 - 15) + 10);
  1935. },
  1936. // Random integer from <low, high> interval
  1937. randInt: function (low, high) {
  1938. return low + Math.floor(Math.random() * (high - low + 1));
  1939. },
  1940. // Random float from <low, high> interval
  1941. randFloat: function (low, high) {
  1942. return low + Math.random() * (high - low);
  1943. },
  1944. // Random float from <-range/2, range/2> interval
  1945. randFloatSpread: function (range) {
  1946. return range * (0.5 - Math.random());
  1947. },
  1948. degToRad: function (degrees) {
  1949. return degrees * _Math.DEG2RAD;
  1950. },
  1951. radToDeg: function (radians) {
  1952. return radians * _Math.RAD2DEG;
  1953. },
  1954. isPowerOfTwo: function (value) {
  1955. return (value & value - 1) === 0 && value !== 0;
  1956. },
  1957. ceilPowerOfTwo: function (value) {
  1958. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  1959. },
  1960. floorPowerOfTwo: function (value) {
  1961. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  1962. }
  1963. };
  1964. /**
  1965. * @author mrdoob / http://mrdoob.com/
  1966. * @author philogb / http://blog.thejit.org/
  1967. * @author egraether / http://egraether.com/
  1968. * @author zz85 / http://www.lab4games.net/zz85/blog
  1969. */
  1970. exports.Math = _Math;
  1971. function Vector2(x, y) {
  1972. this.x = x || 0;
  1973. this.y = y || 0;
  1974. }
  1975. Object.defineProperties(Vector2.prototype, {
  1976. "width": {
  1977. get: function () {
  1978. return this.x;
  1979. },
  1980. set: function (value) {
  1981. this.x = value;
  1982. }
  1983. },
  1984. "height": {
  1985. get: function () {
  1986. return this.y;
  1987. },
  1988. set: function (value) {
  1989. this.y = value;
  1990. }
  1991. }
  1992. });
  1993. Object.assign(Vector2.prototype, {
  1994. isVector2: true,
  1995. set: function (x, y) {
  1996. this.x = x;
  1997. this.y = y;
  1998. return this;
  1999. },
  2000. setScalar: function (scalar) {
  2001. this.x = scalar;
  2002. this.y = scalar;
  2003. return this;
  2004. },
  2005. setX: function (x) {
  2006. this.x = x;
  2007. return this;
  2008. },
  2009. setY: function (y) {
  2010. this.y = y;
  2011. return this;
  2012. },
  2013. setComponent: function (index, value) {
  2014. switch (index) {
  2015. case 0:
  2016. this.x = value;
  2017. break;
  2018. case 1:
  2019. this.y = value;
  2020. break;
  2021. default:
  2022. throw new Error('index is out of range: ' + index);
  2023. }
  2024. return this;
  2025. },
  2026. getComponent: function (index) {
  2027. switch (index) {
  2028. case 0:
  2029. return this.x;
  2030. case 1:
  2031. return this.y;
  2032. default:
  2033. throw new Error('index is out of range: ' + index);
  2034. }
  2035. },
  2036. clone: function () {
  2037. return new this.constructor(this.x, this.y);
  2038. },
  2039. copy: function (v) {
  2040. this.x = v.x;
  2041. this.y = v.y;
  2042. return this;
  2043. },
  2044. add: function (v, w) {
  2045. if (w !== undefined) {
  2046. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2047. return this.addVectors(v, w);
  2048. }
  2049. this.x += v.x;
  2050. this.y += v.y;
  2051. return this;
  2052. },
  2053. addScalar: function (s) {
  2054. this.x += s;
  2055. this.y += s;
  2056. return this;
  2057. },
  2058. addVectors: function (a, b) {
  2059. this.x = a.x + b.x;
  2060. this.y = a.y + b.y;
  2061. return this;
  2062. },
  2063. addScaledVector: function (v, s) {
  2064. this.x += v.x * s;
  2065. this.y += v.y * s;
  2066. return this;
  2067. },
  2068. sub: function (v, w) {
  2069. if (w !== undefined) {
  2070. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2071. return this.subVectors(v, w);
  2072. }
  2073. this.x -= v.x;
  2074. this.y -= v.y;
  2075. return this;
  2076. },
  2077. subScalar: function (s) {
  2078. this.x -= s;
  2079. this.y -= s;
  2080. return this;
  2081. },
  2082. subVectors: function (a, b) {
  2083. this.x = a.x - b.x;
  2084. this.y = a.y - b.y;
  2085. return this;
  2086. },
  2087. multiply: function (v) {
  2088. this.x *= v.x;
  2089. this.y *= v.y;
  2090. return this;
  2091. },
  2092. multiplyScalar: function (scalar) {
  2093. this.x *= scalar;
  2094. this.y *= scalar;
  2095. return this;
  2096. },
  2097. divide: function (v) {
  2098. this.x /= v.x;
  2099. this.y /= v.y;
  2100. return this;
  2101. },
  2102. divideScalar: function (scalar) {
  2103. return this.multiplyScalar(1 / scalar);
  2104. },
  2105. applyMatrix3: function (m) {
  2106. var x = this.x,
  2107. y = this.y;
  2108. var e = m.elements;
  2109. this.x = e[0] * x + e[3] * y + e[6];
  2110. this.y = e[1] * x + e[4] * y + e[7];
  2111. return this;
  2112. },
  2113. min: function (v) {
  2114. this.x = Math.min(this.x, v.x);
  2115. this.y = Math.min(this.y, v.y);
  2116. return this;
  2117. },
  2118. max: function (v) {
  2119. this.x = Math.max(this.x, v.x);
  2120. this.y = Math.max(this.y, v.y);
  2121. return this;
  2122. },
  2123. clamp: function (min, max) {
  2124. // assumes min < max, componentwise
  2125. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2126. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2127. return this;
  2128. },
  2129. clampScalar: function (minVal, maxVal) {
  2130. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2131. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2132. return this;
  2133. },
  2134. clampLength: function (min, max) {
  2135. var length = this.length();
  2136. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2137. },
  2138. floor: function () {
  2139. this.x = Math.floor(this.x);
  2140. this.y = Math.floor(this.y);
  2141. return this;
  2142. },
  2143. ceil: function () {
  2144. this.x = Math.ceil(this.x);
  2145. this.y = Math.ceil(this.y);
  2146. return this;
  2147. },
  2148. round: function () {
  2149. this.x = Math.round(this.x);
  2150. this.y = Math.round(this.y);
  2151. return this;
  2152. },
  2153. roundToZero: function () {
  2154. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2155. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2156. return this;
  2157. },
  2158. negate: function () {
  2159. this.x = -this.x;
  2160. this.y = -this.y;
  2161. return this;
  2162. },
  2163. dot: function (v) {
  2164. return this.x * v.x + this.y * v.y;
  2165. },
  2166. cross: function (v) {
  2167. return this.x * v.y - this.y * v.x;
  2168. },
  2169. lengthSq: function () {
  2170. return this.x * this.x + this.y * this.y;
  2171. },
  2172. length: function () {
  2173. return Math.sqrt(this.x * this.x + this.y * this.y);
  2174. },
  2175. manhattanLength: function () {
  2176. return Math.abs(this.x) + Math.abs(this.y);
  2177. },
  2178. normalize: function () {
  2179. return this.divideScalar(this.length() || 1);
  2180. },
  2181. angle: function () {
  2182. // computes the angle in radians with respect to the positive x-axis
  2183. var angle = Math.atan2(this.y, this.x);
  2184. if (angle < 0) angle += 2 * Math.PI;
  2185. return angle;
  2186. },
  2187. distanceTo: function (v) {
  2188. return Math.sqrt(this.distanceToSquared(v));
  2189. },
  2190. distanceToSquared: function (v) {
  2191. var dx = this.x - v.x,
  2192. dy = this.y - v.y;
  2193. return dx * dx + dy * dy;
  2194. },
  2195. manhattanDistanceTo: function (v) {
  2196. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  2197. },
  2198. setLength: function (length) {
  2199. return this.normalize().multiplyScalar(length);
  2200. },
  2201. lerp: function (v, alpha) {
  2202. this.x += (v.x - this.x) * alpha;
  2203. this.y += (v.y - this.y) * alpha;
  2204. return this;
  2205. },
  2206. lerpVectors: function (v1, v2, alpha) {
  2207. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2208. },
  2209. equals: function (v) {
  2210. return v.x === this.x && v.y === this.y;
  2211. },
  2212. fromArray: function (array, offset) {
  2213. if (offset === undefined) offset = 0;
  2214. this.x = array[offset];
  2215. this.y = array[offset + 1];
  2216. return this;
  2217. },
  2218. toArray: function (array, offset) {
  2219. if (array === undefined) array = [];
  2220. if (offset === undefined) offset = 0;
  2221. array[offset] = this.x;
  2222. array[offset + 1] = this.y;
  2223. return array;
  2224. },
  2225. fromBufferAttribute: function (attribute, index, offset) {
  2226. if (offset !== undefined) {
  2227. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  2228. }
  2229. this.x = attribute.getX(index);
  2230. this.y = attribute.getY(index);
  2231. return this;
  2232. },
  2233. rotateAround: function (center, angle) {
  2234. var c = Math.cos(angle),
  2235. s = Math.sin(angle);
  2236. var x = this.x - center.x;
  2237. var y = this.y - center.y;
  2238. this.x = x * c - y * s + center.x;
  2239. this.y = x * s + y * c + center.y;
  2240. return this;
  2241. }
  2242. });
  2243. /**
  2244. * @author mikael emtinger / http://gomo.se/
  2245. * @author alteredq / http://alteredqualia.com/
  2246. * @author WestLangley / http://github.com/WestLangley
  2247. * @author bhouston / http://clara.io
  2248. */
  2249. function Quaternion(x, y, z, w) {
  2250. this._x = x || 0;
  2251. this._y = y || 0;
  2252. this._z = z || 0;
  2253. this._w = w !== undefined ? w : 1;
  2254. }
  2255. Object.assign(Quaternion, {
  2256. slerp: function (qa, qb, qm, t) {
  2257. return qm.copy(qa).slerp(qb, t);
  2258. },
  2259. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2260. // fuzz-free, array-based Quaternion SLERP operation
  2261. var x0 = src0[srcOffset0 + 0],
  2262. y0 = src0[srcOffset0 + 1],
  2263. z0 = src0[srcOffset0 + 2],
  2264. w0 = src0[srcOffset0 + 3],
  2265. x1 = src1[srcOffset1 + 0],
  2266. y1 = src1[srcOffset1 + 1],
  2267. z1 = src1[srcOffset1 + 2],
  2268. w1 = src1[srcOffset1 + 3];
  2269. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2270. var s = 1 - t,
  2271. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2272. dir = cos >= 0 ? 1 : -1,
  2273. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2274. if (sqrSin > Number.EPSILON) {
  2275. var sin = Math.sqrt(sqrSin),
  2276. len = Math.atan2(sin, cos * dir);
  2277. s = Math.sin(s * len) / sin;
  2278. t = Math.sin(t * len) / sin;
  2279. }
  2280. var tDir = t * dir;
  2281. x0 = x0 * s + x1 * tDir;
  2282. y0 = y0 * s + y1 * tDir;
  2283. z0 = z0 * s + z1 * tDir;
  2284. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2285. if (s === 1 - t) {
  2286. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2287. x0 *= f;
  2288. y0 *= f;
  2289. z0 *= f;
  2290. w0 *= f;
  2291. }
  2292. }
  2293. dst[dstOffset] = x0;
  2294. dst[dstOffset + 1] = y0;
  2295. dst[dstOffset + 2] = z0;
  2296. dst[dstOffset + 3] = w0;
  2297. }
  2298. });
  2299. Object.defineProperties(Quaternion.prototype, {
  2300. x: {
  2301. get: function () {
  2302. return this._x;
  2303. },
  2304. set: function (value) {
  2305. this._x = value;
  2306. this._onChangeCallback();
  2307. }
  2308. },
  2309. y: {
  2310. get: function () {
  2311. return this._y;
  2312. },
  2313. set: function (value) {
  2314. this._y = value;
  2315. this._onChangeCallback();
  2316. }
  2317. },
  2318. z: {
  2319. get: function () {
  2320. return this._z;
  2321. },
  2322. set: function (value) {
  2323. this._z = value;
  2324. this._onChangeCallback();
  2325. }
  2326. },
  2327. w: {
  2328. get: function () {
  2329. return this._w;
  2330. },
  2331. set: function (value) {
  2332. this._w = value;
  2333. this._onChangeCallback();
  2334. }
  2335. }
  2336. });
  2337. Object.assign(Quaternion.prototype, {
  2338. isQuaternion: true,
  2339. set: function (x, y, z, w) {
  2340. this._x = x;
  2341. this._y = y;
  2342. this._z = z;
  2343. this._w = w;
  2344. this._onChangeCallback();
  2345. return this;
  2346. },
  2347. clone: function () {
  2348. return new this.constructor(this._x, this._y, this._z, this._w);
  2349. },
  2350. copy: function (quaternion) {
  2351. this._x = quaternion.x;
  2352. this._y = quaternion.y;
  2353. this._z = quaternion.z;
  2354. this._w = quaternion.w;
  2355. this._onChangeCallback();
  2356. return this;
  2357. },
  2358. setFromEuler: function (euler, update) {
  2359. if (!(euler && euler.isEuler)) {
  2360. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2361. }
  2362. var x = euler._x,
  2363. y = euler._y,
  2364. z = euler._z,
  2365. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2366. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2367. // content/SpinCalc.m
  2368. var cos = Math.cos;
  2369. var sin = Math.sin;
  2370. var c1 = cos(x / 2);
  2371. var c2 = cos(y / 2);
  2372. var c3 = cos(z / 2);
  2373. var s1 = sin(x / 2);
  2374. var s2 = sin(y / 2);
  2375. var s3 = sin(z / 2);
  2376. if (order === 'XYZ') {
  2377. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2378. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2379. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2380. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2381. } else if (order === 'YXZ') {
  2382. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2383. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2384. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2385. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2386. } else if (order === 'ZXY') {
  2387. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2388. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2389. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2390. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2391. } else if (order === 'ZYX') {
  2392. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2393. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2394. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2395. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2396. } else if (order === 'YZX') {
  2397. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2398. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2399. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2400. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2401. } else if (order === 'XZY') {
  2402. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2403. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2404. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2405. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2406. }
  2407. if (update !== false) this._onChangeCallback();
  2408. return this;
  2409. },
  2410. setFromAxisAngle: function (axis, angle) {
  2411. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2412. // assumes axis is normalized
  2413. var halfAngle = angle / 2,
  2414. s = Math.sin(halfAngle);
  2415. this._x = axis.x * s;
  2416. this._y = axis.y * s;
  2417. this._z = axis.z * s;
  2418. this._w = Math.cos(halfAngle);
  2419. this._onChangeCallback();
  2420. return this;
  2421. },
  2422. setFromRotationMatrix: function (m) {
  2423. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2424. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2425. var te = m.elements,
  2426. m11 = te[0],
  2427. m12 = te[4],
  2428. m13 = te[8],
  2429. m21 = te[1],
  2430. m22 = te[5],
  2431. m23 = te[9],
  2432. m31 = te[2],
  2433. m32 = te[6],
  2434. m33 = te[10],
  2435. trace = m11 + m22 + m33,
  2436. s;
  2437. if (trace > 0) {
  2438. s = 0.5 / Math.sqrt(trace + 1.0);
  2439. this._w = 0.25 / s;
  2440. this._x = (m32 - m23) * s;
  2441. this._y = (m13 - m31) * s;
  2442. this._z = (m21 - m12) * s;
  2443. } else if (m11 > m22 && m11 > m33) {
  2444. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2445. this._w = (m32 - m23) / s;
  2446. this._x = 0.25 * s;
  2447. this._y = (m12 + m21) / s;
  2448. this._z = (m13 + m31) / s;
  2449. } else if (m22 > m33) {
  2450. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2451. this._w = (m13 - m31) / s;
  2452. this._x = (m12 + m21) / s;
  2453. this._y = 0.25 * s;
  2454. this._z = (m23 + m32) / s;
  2455. } else {
  2456. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2457. this._w = (m21 - m12) / s;
  2458. this._x = (m13 + m31) / s;
  2459. this._y = (m23 + m32) / s;
  2460. this._z = 0.25 * s;
  2461. }
  2462. this._onChangeCallback();
  2463. return this;
  2464. },
  2465. setFromUnitVectors: function (vFrom, vTo) {
  2466. // assumes direction vectors vFrom and vTo are normalized
  2467. var EPS = 0.000001;
  2468. var r = vFrom.dot(vTo) + 1;
  2469. if (r < EPS) {
  2470. r = 0;
  2471. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2472. this._x = -vFrom.y;
  2473. this._y = vFrom.x;
  2474. this._z = 0;
  2475. this._w = r;
  2476. } else {
  2477. this._x = 0;
  2478. this._y = -vFrom.z;
  2479. this._z = vFrom.y;
  2480. this._w = r;
  2481. }
  2482. } else {
  2483. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2484. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2485. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2486. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2487. this._w = r;
  2488. }
  2489. return this.normalize();
  2490. },
  2491. angleTo: function (q) {
  2492. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  2493. },
  2494. rotateTowards: function (q, step) {
  2495. var angle = this.angleTo(q);
  2496. if (angle === 0) return this;
  2497. var t = Math.min(1, step / angle);
  2498. this.slerp(q, t);
  2499. return this;
  2500. },
  2501. inverse: function () {
  2502. // quaternion is assumed to have unit length
  2503. return this.conjugate();
  2504. },
  2505. conjugate: function () {
  2506. this._x *= -1;
  2507. this._y *= -1;
  2508. this._z *= -1;
  2509. this._onChangeCallback();
  2510. return this;
  2511. },
  2512. dot: function (v) {
  2513. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2514. },
  2515. lengthSq: function () {
  2516. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2517. },
  2518. length: function () {
  2519. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2520. },
  2521. normalize: function () {
  2522. var l = this.length();
  2523. if (l === 0) {
  2524. this._x = 0;
  2525. this._y = 0;
  2526. this._z = 0;
  2527. this._w = 1;
  2528. } else {
  2529. l = 1 / l;
  2530. this._x = this._x * l;
  2531. this._y = this._y * l;
  2532. this._z = this._z * l;
  2533. this._w = this._w * l;
  2534. }
  2535. this._onChangeCallback();
  2536. return this;
  2537. },
  2538. multiply: function (q, p) {
  2539. if (p !== undefined) {
  2540. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2541. return this.multiplyQuaternions(q, p);
  2542. }
  2543. return this.multiplyQuaternions(this, q);
  2544. },
  2545. premultiply: function (q) {
  2546. return this.multiplyQuaternions(q, this);
  2547. },
  2548. multiplyQuaternions: function (a, b) {
  2549. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2550. var qax = a._x,
  2551. qay = a._y,
  2552. qaz = a._z,
  2553. qaw = a._w;
  2554. var qbx = b._x,
  2555. qby = b._y,
  2556. qbz = b._z,
  2557. qbw = b._w;
  2558. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2559. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2560. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2561. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2562. this._onChangeCallback();
  2563. return this;
  2564. },
  2565. slerp: function (qb, t) {
  2566. if (t === 0) return this;
  2567. if (t === 1) return this.copy(qb);
  2568. var x = this._x,
  2569. y = this._y,
  2570. z = this._z,
  2571. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2572. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2573. if (cosHalfTheta < 0) {
  2574. this._w = -qb._w;
  2575. this._x = -qb._x;
  2576. this._y = -qb._y;
  2577. this._z = -qb._z;
  2578. cosHalfTheta = -cosHalfTheta;
  2579. } else {
  2580. this.copy(qb);
  2581. }
  2582. if (cosHalfTheta >= 1.0) {
  2583. this._w = w;
  2584. this._x = x;
  2585. this._y = y;
  2586. this._z = z;
  2587. return this;
  2588. }
  2589. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2590. if (sqrSinHalfTheta <= Number.EPSILON) {
  2591. var s = 1 - t;
  2592. this._w = s * w + t * this._w;
  2593. this._x = s * x + t * this._x;
  2594. this._y = s * y + t * this._y;
  2595. this._z = s * z + t * this._z;
  2596. this.normalize();
  2597. this._onChangeCallback();
  2598. return this;
  2599. }
  2600. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2601. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2602. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2603. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2604. this._w = w * ratioA + this._w * ratioB;
  2605. this._x = x * ratioA + this._x * ratioB;
  2606. this._y = y * ratioA + this._y * ratioB;
  2607. this._z = z * ratioA + this._z * ratioB;
  2608. this._onChangeCallback();
  2609. return this;
  2610. },
  2611. equals: function (quaternion) {
  2612. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2613. },
  2614. fromArray: function (array, offset) {
  2615. if (offset === undefined) offset = 0;
  2616. this._x = array[offset];
  2617. this._y = array[offset + 1];
  2618. this._z = array[offset + 2];
  2619. this._w = array[offset + 3];
  2620. this._onChangeCallback();
  2621. return this;
  2622. },
  2623. toArray: function (array, offset) {
  2624. if (array === undefined) array = [];
  2625. if (offset === undefined) offset = 0;
  2626. array[offset] = this._x;
  2627. array[offset + 1] = this._y;
  2628. array[offset + 2] = this._z;
  2629. array[offset + 3] = this._w;
  2630. return array;
  2631. },
  2632. _onChange: function (callback) {
  2633. this._onChangeCallback = callback;
  2634. return this;
  2635. },
  2636. _onChangeCallback: function () {}
  2637. });
  2638. /**
  2639. * @author mrdoob / http://mrdoob.com/
  2640. * @author kile / http://kile.stravaganza.org/
  2641. * @author philogb / http://blog.thejit.org/
  2642. * @author mikael emtinger / http://gomo.se/
  2643. * @author egraether / http://egraether.com/
  2644. * @author WestLangley / http://github.com/WestLangley
  2645. */
  2646. var _vector = new Vector3();
  2647. var _quaternion = new Quaternion();
  2648. function Vector3(x, y, z) {
  2649. this.x = x || 0;
  2650. this.y = y || 0;
  2651. this.z = z || 0;
  2652. }
  2653. Object.assign(Vector3.prototype, {
  2654. isVector3: true,
  2655. set: function (x, y, z) {
  2656. this.x = x;
  2657. this.y = y;
  2658. this.z = z;
  2659. return this;
  2660. },
  2661. setScalar: function (scalar) {
  2662. this.x = scalar;
  2663. this.y = scalar;
  2664. this.z = scalar;
  2665. return this;
  2666. },
  2667. setX: function (x) {
  2668. this.x = x;
  2669. return this;
  2670. },
  2671. setY: function (y) {
  2672. this.y = y;
  2673. return this;
  2674. },
  2675. setZ: function (z) {
  2676. this.z = z;
  2677. return this;
  2678. },
  2679. setComponent: function (index, value) {
  2680. switch (index) {
  2681. case 0:
  2682. this.x = value;
  2683. break;
  2684. case 1:
  2685. this.y = value;
  2686. break;
  2687. case 2:
  2688. this.z = value;
  2689. break;
  2690. default:
  2691. throw new Error('index is out of range: ' + index);
  2692. }
  2693. return this;
  2694. },
  2695. getComponent: function (index) {
  2696. switch (index) {
  2697. case 0:
  2698. return this.x;
  2699. case 1:
  2700. return this.y;
  2701. case 2:
  2702. return this.z;
  2703. default:
  2704. throw new Error('index is out of range: ' + index);
  2705. }
  2706. },
  2707. clone: function () {
  2708. return new this.constructor(this.x, this.y, this.z);
  2709. },
  2710. copy: function (v) {
  2711. this.x = v.x;
  2712. this.y = v.y;
  2713. this.z = v.z;
  2714. return this;
  2715. },
  2716. add: function (v, w) {
  2717. if (w !== undefined) {
  2718. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2719. return this.addVectors(v, w);
  2720. }
  2721. this.x += v.x;
  2722. this.y += v.y;
  2723. this.z += v.z;
  2724. return this;
  2725. },
  2726. addScalar: function (s) {
  2727. this.x += s;
  2728. this.y += s;
  2729. this.z += s;
  2730. return this;
  2731. },
  2732. addVectors: function (a, b) {
  2733. this.x = a.x + b.x;
  2734. this.y = a.y + b.y;
  2735. this.z = a.z + b.z;
  2736. return this;
  2737. },
  2738. addScaledVector: function (v, s) {
  2739. this.x += v.x * s;
  2740. this.y += v.y * s;
  2741. this.z += v.z * s;
  2742. return this;
  2743. },
  2744. sub: function (v, w) {
  2745. if (w !== undefined) {
  2746. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2747. return this.subVectors(v, w);
  2748. }
  2749. this.x -= v.x;
  2750. this.y -= v.y;
  2751. this.z -= v.z;
  2752. return this;
  2753. },
  2754. subScalar: function (s) {
  2755. this.x -= s;
  2756. this.y -= s;
  2757. this.z -= s;
  2758. return this;
  2759. },
  2760. subVectors: function (a, b) {
  2761. this.x = a.x - b.x;
  2762. this.y = a.y - b.y;
  2763. this.z = a.z - b.z;
  2764. return this;
  2765. },
  2766. multiply: function (v, w) {
  2767. if (w !== undefined) {
  2768. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2769. return this.multiplyVectors(v, w);
  2770. }
  2771. this.x *= v.x;
  2772. this.y *= v.y;
  2773. this.z *= v.z;
  2774. return this;
  2775. },
  2776. multiplyScalar: function (scalar) {
  2777. this.x *= scalar;
  2778. this.y *= scalar;
  2779. this.z *= scalar;
  2780. return this;
  2781. },
  2782. multiplyVectors: function (a, b) {
  2783. this.x = a.x * b.x;
  2784. this.y = a.y * b.y;
  2785. this.z = a.z * b.z;
  2786. return this;
  2787. },
  2788. applyEuler: function (euler) {
  2789. if (!(euler && euler.isEuler)) {
  2790. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2791. }
  2792. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2793. },
  2794. applyAxisAngle: function (axis, angle) {
  2795. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2796. },
  2797. applyMatrix3: function (m) {
  2798. var x = this.x,
  2799. y = this.y,
  2800. z = this.z;
  2801. var e = m.elements;
  2802. this.x = e[0] * x + e[3] * y + e[6] * z;
  2803. this.y = e[1] * x + e[4] * y + e[7] * z;
  2804. this.z = e[2] * x + e[5] * y + e[8] * z;
  2805. return this;
  2806. },
  2807. applyMatrix4: function (m) {
  2808. var x = this.x,
  2809. y = this.y,
  2810. z = this.z;
  2811. var e = m.elements;
  2812. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2813. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2814. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2815. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2816. return this;
  2817. },
  2818. applyQuaternion: function (q) {
  2819. var x = this.x,
  2820. y = this.y,
  2821. z = this.z;
  2822. var qx = q.x,
  2823. qy = q.y,
  2824. qz = q.z,
  2825. qw = q.w; // calculate quat * vector
  2826. var ix = qw * x + qy * z - qz * y;
  2827. var iy = qw * y + qz * x - qx * z;
  2828. var iz = qw * z + qx * y - qy * x;
  2829. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2830. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2831. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2832. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2833. return this;
  2834. },
  2835. project: function (camera) {
  2836. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2837. },
  2838. unproject: function (camera) {
  2839. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2840. },
  2841. transformDirection: function (m) {
  2842. // input: THREE.Matrix4 affine matrix
  2843. // vector interpreted as a direction
  2844. var x = this.x,
  2845. y = this.y,
  2846. z = this.z;
  2847. var e = m.elements;
  2848. this.x = e[0] * x + e[4] * y + e[8] * z;
  2849. this.y = e[1] * x + e[5] * y + e[9] * z;
  2850. this.z = e[2] * x + e[6] * y + e[10] * z;
  2851. return this.normalize();
  2852. },
  2853. divide: function (v) {
  2854. this.x /= v.x;
  2855. this.y /= v.y;
  2856. this.z /= v.z;
  2857. return this;
  2858. },
  2859. divideScalar: function (scalar) {
  2860. return this.multiplyScalar(1 / scalar);
  2861. },
  2862. min: function (v) {
  2863. this.x = Math.min(this.x, v.x);
  2864. this.y = Math.min(this.y, v.y);
  2865. this.z = Math.min(this.z, v.z);
  2866. return this;
  2867. },
  2868. max: function (v) {
  2869. this.x = Math.max(this.x, v.x);
  2870. this.y = Math.max(this.y, v.y);
  2871. this.z = Math.max(this.z, v.z);
  2872. return this;
  2873. },
  2874. clamp: function (min, max) {
  2875. // assumes min < max, componentwise
  2876. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2877. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2878. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2879. return this;
  2880. },
  2881. clampScalar: function (minVal, maxVal) {
  2882. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2883. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2884. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2885. return this;
  2886. },
  2887. clampLength: function (min, max) {
  2888. var length = this.length();
  2889. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2890. },
  2891. floor: function () {
  2892. this.x = Math.floor(this.x);
  2893. this.y = Math.floor(this.y);
  2894. this.z = Math.floor(this.z);
  2895. return this;
  2896. },
  2897. ceil: function () {
  2898. this.x = Math.ceil(this.x);
  2899. this.y = Math.ceil(this.y);
  2900. this.z = Math.ceil(this.z);
  2901. return this;
  2902. },
  2903. round: function () {
  2904. this.x = Math.round(this.x);
  2905. this.y = Math.round(this.y);
  2906. this.z = Math.round(this.z);
  2907. return this;
  2908. },
  2909. roundToZero: function () {
  2910. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2911. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2912. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2913. return this;
  2914. },
  2915. negate: function () {
  2916. this.x = -this.x;
  2917. this.y = -this.y;
  2918. this.z = -this.z;
  2919. return this;
  2920. },
  2921. dot: function (v) {
  2922. return this.x * v.x + this.y * v.y + this.z * v.z;
  2923. },
  2924. // TODO lengthSquared?
  2925. lengthSq: function () {
  2926. return this.x * this.x + this.y * this.y + this.z * this.z;
  2927. },
  2928. length: function () {
  2929. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2930. },
  2931. manhattanLength: function () {
  2932. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2933. },
  2934. normalize: function () {
  2935. return this.divideScalar(this.length() || 1);
  2936. },
  2937. setLength: function (length) {
  2938. return this.normalize().multiplyScalar(length);
  2939. },
  2940. lerp: function (v, alpha) {
  2941. this.x += (v.x - this.x) * alpha;
  2942. this.y += (v.y - this.y) * alpha;
  2943. this.z += (v.z - this.z) * alpha;
  2944. return this;
  2945. },
  2946. lerpVectors: function (v1, v2, alpha) {
  2947. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2948. },
  2949. cross: function (v, w) {
  2950. if (w !== undefined) {
  2951. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2952. return this.crossVectors(v, w);
  2953. }
  2954. return this.crossVectors(this, v);
  2955. },
  2956. crossVectors: function (a, b) {
  2957. var ax = a.x,
  2958. ay = a.y,
  2959. az = a.z;
  2960. var bx = b.x,
  2961. by = b.y,
  2962. bz = b.z;
  2963. this.x = ay * bz - az * by;
  2964. this.y = az * bx - ax * bz;
  2965. this.z = ax * by - ay * bx;
  2966. return this;
  2967. },
  2968. projectOnVector: function (v) {
  2969. // v cannot be the zero v
  2970. var scalar = v.dot(this) / v.lengthSq();
  2971. return this.copy(v).multiplyScalar(scalar);
  2972. },
  2973. projectOnPlane: function (planeNormal) {
  2974. _vector.copy(this).projectOnVector(planeNormal);
  2975. return this.sub(_vector);
  2976. },
  2977. reflect: function (normal) {
  2978. // reflect incident vector off plane orthogonal to normal
  2979. // normal is assumed to have unit length
  2980. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2981. },
  2982. angleTo: function (v) {
  2983. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2984. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  2985. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2986. return Math.acos(_Math.clamp(theta, -1, 1));
  2987. },
  2988. distanceTo: function (v) {
  2989. return Math.sqrt(this.distanceToSquared(v));
  2990. },
  2991. distanceToSquared: function (v) {
  2992. var dx = this.x - v.x,
  2993. dy = this.y - v.y,
  2994. dz = this.z - v.z;
  2995. return dx * dx + dy * dy + dz * dz;
  2996. },
  2997. manhattanDistanceTo: function (v) {
  2998. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2999. },
  3000. setFromSpherical: function (s) {
  3001. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3002. },
  3003. setFromSphericalCoords: function (radius, phi, theta) {
  3004. var sinPhiRadius = Math.sin(phi) * radius;
  3005. this.x = sinPhiRadius * Math.sin(theta);
  3006. this.y = Math.cos(phi) * radius;
  3007. this.z = sinPhiRadius * Math.cos(theta);
  3008. return this;
  3009. },
  3010. setFromCylindrical: function (c) {
  3011. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3012. },
  3013. setFromCylindricalCoords: function (radius, theta, y) {
  3014. this.x = radius * Math.sin(theta);
  3015. this.y = y;
  3016. this.z = radius * Math.cos(theta);
  3017. return this;
  3018. },
  3019. setFromMatrixPosition: function (m) {
  3020. var e = m.elements;
  3021. this.x = e[12];
  3022. this.y = e[13];
  3023. this.z = e[14];
  3024. return this;
  3025. },
  3026. setFromMatrixScale: function (m) {
  3027. var sx = this.setFromMatrixColumn(m, 0).length();
  3028. var sy = this.setFromMatrixColumn(m, 1).length();
  3029. var sz = this.setFromMatrixColumn(m, 2).length();
  3030. this.x = sx;
  3031. this.y = sy;
  3032. this.z = sz;
  3033. return this;
  3034. },
  3035. setFromMatrixColumn: function (m, index) {
  3036. return this.fromArray(m.elements, index * 4);
  3037. },
  3038. equals: function (v) {
  3039. return v.x === this.x && v.y === this.y && v.z === this.z;
  3040. },
  3041. fromArray: function (array, offset) {
  3042. if (offset === undefined) offset = 0;
  3043. this.x = array[offset];
  3044. this.y = array[offset + 1];
  3045. this.z = array[offset + 2];
  3046. return this;
  3047. },
  3048. toArray: function (array, offset) {
  3049. if (array === undefined) array = [];
  3050. if (offset === undefined) offset = 0;
  3051. array[offset] = this.x;
  3052. array[offset + 1] = this.y;
  3053. array[offset + 2] = this.z;
  3054. return array;
  3055. },
  3056. fromBufferAttribute: function (attribute, index, offset) {
  3057. if (offset !== undefined) {
  3058. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3059. }
  3060. this.x = attribute.getX(index);
  3061. this.y = attribute.getY(index);
  3062. this.z = attribute.getZ(index);
  3063. return this;
  3064. }
  3065. });
  3066. /**
  3067. * @author alteredq / http://alteredqualia.com/
  3068. * @author WestLangley / http://github.com/WestLangley
  3069. * @author bhouston / http://clara.io
  3070. * @author tschw
  3071. */
  3072. var _vector$1 = new Vector3();
  3073. function Matrix3() {
  3074. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3075. if (arguments.length > 0) {
  3076. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  3077. }
  3078. }
  3079. Object.assign(Matrix3.prototype, {
  3080. isMatrix3: true,
  3081. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  3082. var te = this.elements;
  3083. te[0] = n11;
  3084. te[1] = n21;
  3085. te[2] = n31;
  3086. te[3] = n12;
  3087. te[4] = n22;
  3088. te[5] = n32;
  3089. te[6] = n13;
  3090. te[7] = n23;
  3091. te[8] = n33;
  3092. return this;
  3093. },
  3094. identity: function () {
  3095. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  3096. return this;
  3097. },
  3098. clone: function () {
  3099. return new this.constructor().fromArray(this.elements);
  3100. },
  3101. copy: function (m) {
  3102. var te = this.elements;
  3103. var me = m.elements;
  3104. te[0] = me[0];
  3105. te[1] = me[1];
  3106. te[2] = me[2];
  3107. te[3] = me[3];
  3108. te[4] = me[4];
  3109. te[5] = me[5];
  3110. te[6] = me[6];
  3111. te[7] = me[7];
  3112. te[8] = me[8];
  3113. return this;
  3114. },
  3115. setFromMatrix4: function (m) {
  3116. var me = m.elements;
  3117. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  3118. return this;
  3119. },
  3120. applyToBufferAttribute: function (attribute) {
  3121. for (var i = 0, l = attribute.count; i < l; i++) {
  3122. _vector$1.x = attribute.getX(i);
  3123. _vector$1.y = attribute.getY(i);
  3124. _vector$1.z = attribute.getZ(i);
  3125. _vector$1.applyMatrix3(this);
  3126. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  3127. }
  3128. return attribute;
  3129. },
  3130. multiply: function (m) {
  3131. return this.multiplyMatrices(this, m);
  3132. },
  3133. premultiply: function (m) {
  3134. return this.multiplyMatrices(m, this);
  3135. },
  3136. multiplyMatrices: function (a, b) {
  3137. var ae = a.elements;
  3138. var be = b.elements;
  3139. var te = this.elements;
  3140. var a11 = ae[0],
  3141. a12 = ae[3],
  3142. a13 = ae[6];
  3143. var a21 = ae[1],
  3144. a22 = ae[4],
  3145. a23 = ae[7];
  3146. var a31 = ae[2],
  3147. a32 = ae[5],
  3148. a33 = ae[8];
  3149. var b11 = be[0],
  3150. b12 = be[3],
  3151. b13 = be[6];
  3152. var b21 = be[1],
  3153. b22 = be[4],
  3154. b23 = be[7];
  3155. var b31 = be[2],
  3156. b32 = be[5],
  3157. b33 = be[8];
  3158. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  3159. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  3160. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  3161. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  3162. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  3163. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  3164. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  3165. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  3166. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  3167. return this;
  3168. },
  3169. multiplyScalar: function (s) {
  3170. var te = this.elements;
  3171. te[0] *= s;
  3172. te[3] *= s;
  3173. te[6] *= s;
  3174. te[1] *= s;
  3175. te[4] *= s;
  3176. te[7] *= s;
  3177. te[2] *= s;
  3178. te[5] *= s;
  3179. te[8] *= s;
  3180. return this;
  3181. },
  3182. determinant: function () {
  3183. var te = this.elements;
  3184. var a = te[0],
  3185. b = te[1],
  3186. c = te[2],
  3187. d = te[3],
  3188. e = te[4],
  3189. f = te[5],
  3190. g = te[6],
  3191. h = te[7],
  3192. i = te[8];
  3193. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3194. },
  3195. getInverse: function (matrix, throwOnDegenerate) {
  3196. if (matrix && matrix.isMatrix4) {
  3197. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  3198. }
  3199. var me = matrix.elements,
  3200. te = this.elements,
  3201. n11 = me[0],
  3202. n21 = me[1],
  3203. n31 = me[2],
  3204. n12 = me[3],
  3205. n22 = me[4],
  3206. n32 = me[5],
  3207. n13 = me[6],
  3208. n23 = me[7],
  3209. n33 = me[8],
  3210. t11 = n33 * n22 - n32 * n23,
  3211. t12 = n32 * n13 - n33 * n12,
  3212. t13 = n23 * n12 - n22 * n13,
  3213. det = n11 * t11 + n21 * t12 + n31 * t13;
  3214. if (det === 0) {
  3215. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  3216. if (throwOnDegenerate === true) {
  3217. throw new Error(msg);
  3218. } else {
  3219. console.warn(msg);
  3220. }
  3221. return this.identity();
  3222. }
  3223. var detInv = 1 / det;
  3224. te[0] = t11 * detInv;
  3225. te[1] = (n31 * n23 - n33 * n21) * detInv;
  3226. te[2] = (n32 * n21 - n31 * n22) * detInv;
  3227. te[3] = t12 * detInv;
  3228. te[4] = (n33 * n11 - n31 * n13) * detInv;
  3229. te[5] = (n31 * n12 - n32 * n11) * detInv;
  3230. te[6] = t13 * detInv;
  3231. te[7] = (n21 * n13 - n23 * n11) * detInv;
  3232. te[8] = (n22 * n11 - n21 * n12) * detInv;
  3233. return this;
  3234. },
  3235. transpose: function () {
  3236. var tmp,
  3237. m = this.elements;
  3238. tmp = m[1];
  3239. m[1] = m[3];
  3240. m[3] = tmp;
  3241. tmp = m[2];
  3242. m[2] = m[6];
  3243. m[6] = tmp;
  3244. tmp = m[5];
  3245. m[5] = m[7];
  3246. m[7] = tmp;
  3247. return this;
  3248. },
  3249. getNormalMatrix: function (matrix4) {
  3250. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  3251. },
  3252. transposeIntoArray: function (r) {
  3253. var m = this.elements;
  3254. r[0] = m[0];
  3255. r[1] = m[3];
  3256. r[2] = m[6];
  3257. r[3] = m[1];
  3258. r[4] = m[4];
  3259. r[5] = m[7];
  3260. r[6] = m[2];
  3261. r[7] = m[5];
  3262. r[8] = m[8];
  3263. return this;
  3264. },
  3265. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  3266. var c = Math.cos(rotation);
  3267. var s = Math.sin(rotation);
  3268. 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);
  3269. },
  3270. scale: function (sx, sy) {
  3271. var te = this.elements;
  3272. te[0] *= sx;
  3273. te[3] *= sx;
  3274. te[6] *= sx;
  3275. te[1] *= sy;
  3276. te[4] *= sy;
  3277. te[7] *= sy;
  3278. return this;
  3279. },
  3280. rotate: function (theta) {
  3281. var c = Math.cos(theta);
  3282. var s = Math.sin(theta);
  3283. var te = this.elements;
  3284. var a11 = te[0],
  3285. a12 = te[3],
  3286. a13 = te[6];
  3287. var a21 = te[1],
  3288. a22 = te[4],
  3289. a23 = te[7];
  3290. te[0] = c * a11 + s * a21;
  3291. te[3] = c * a12 + s * a22;
  3292. te[6] = c * a13 + s * a23;
  3293. te[1] = -s * a11 + c * a21;
  3294. te[4] = -s * a12 + c * a22;
  3295. te[7] = -s * a13 + c * a23;
  3296. return this;
  3297. },
  3298. translate: function (tx, ty) {
  3299. var te = this.elements;
  3300. te[0] += tx * te[2];
  3301. te[3] += tx * te[5];
  3302. te[6] += tx * te[8];
  3303. te[1] += ty * te[2];
  3304. te[4] += ty * te[5];
  3305. te[7] += ty * te[8];
  3306. return this;
  3307. },
  3308. equals: function (matrix) {
  3309. var te = this.elements;
  3310. var me = matrix.elements;
  3311. for (var i = 0; i < 9; i++) {
  3312. if (te[i] !== me[i]) return false;
  3313. }
  3314. return true;
  3315. },
  3316. fromArray: function (array, offset) {
  3317. if (offset === undefined) offset = 0;
  3318. for (var i = 0; i < 9; i++) {
  3319. this.elements[i] = array[i + offset];
  3320. }
  3321. return this;
  3322. },
  3323. toArray: function (array, offset) {
  3324. if (array === undefined) array = [];
  3325. if (offset === undefined) offset = 0;
  3326. var te = this.elements;
  3327. array[offset] = te[0];
  3328. array[offset + 1] = te[1];
  3329. array[offset + 2] = te[2];
  3330. array[offset + 3] = te[3];
  3331. array[offset + 4] = te[4];
  3332. array[offset + 5] = te[5];
  3333. array[offset + 6] = te[6];
  3334. array[offset + 7] = te[7];
  3335. array[offset + 8] = te[8];
  3336. return array;
  3337. }
  3338. });
  3339. /**
  3340. * @author mrdoob / http://mrdoob.com/
  3341. * @author alteredq / http://alteredqualia.com/
  3342. * @author szimek / https://github.com/szimek/
  3343. */
  3344. var _canvas;
  3345. var ImageUtils = {
  3346. getDataURL: function (image) {
  3347. var canvas;
  3348. if (typeof HTMLCanvasElement == 'undefined') {
  3349. return image.src;
  3350. } else if (image instanceof HTMLCanvasElement) {
  3351. canvas = image;
  3352. } else {
  3353. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  3354. _canvas.width = image.width;
  3355. _canvas.height = image.height;
  3356. var context = _canvas.getContext('2d');
  3357. if (image instanceof ImageData) {
  3358. context.putImageData(image, 0, 0);
  3359. } else {
  3360. context.drawImage(image, 0, 0, image.width, image.height);
  3361. }
  3362. canvas = _canvas;
  3363. }
  3364. if (canvas.width > 2048 || canvas.height > 2048) {
  3365. return canvas.toDataURL('image/jpeg', 0.6);
  3366. } else {
  3367. return canvas.toDataURL('image/png');
  3368. }
  3369. }
  3370. };
  3371. /**
  3372. * @author mrdoob / http://mrdoob.com/
  3373. * @author alteredq / http://alteredqualia.com/
  3374. * @author szimek / https://github.com/szimek/
  3375. */
  3376. exports.ImageUtils = ImageUtils;
  3377. var textureId = 0;
  3378. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  3379. Object.defineProperty(this, 'id', {
  3380. value: textureId++
  3381. });
  3382. this.uuid = _Math.generateUUID();
  3383. this.name = '';
  3384. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  3385. this.mipmaps = [];
  3386. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  3387. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  3388. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  3389. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  3390. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  3391. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  3392. this.format = format !== undefined ? format : RGBAFormat;
  3393. this.type = type !== undefined ? type : UnsignedByteType;
  3394. this.offset = new Vector2(0, 0);
  3395. this.repeat = new Vector2(1, 1);
  3396. this.center = new Vector2(0, 0);
  3397. this.rotation = 0;
  3398. this.matrixAutoUpdate = true;
  3399. this.matrix = new Matrix3();
  3400. this.generateMipmaps = true;
  3401. this.premultiplyAlpha = false;
  3402. this.flipY = true;
  3403. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3404. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  3405. //
  3406. // Also changing the encoding after already used by a Material will not automatically make the Material
  3407. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  3408. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  3409. this.version = 0;
  3410. this.onUpdate = null;
  3411. }
  3412. Texture.DEFAULT_IMAGE = undefined;
  3413. Texture.DEFAULT_MAPPING = UVMapping;
  3414. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3415. constructor: Texture,
  3416. isTexture: true,
  3417. updateMatrix: function () {
  3418. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  3419. },
  3420. clone: function () {
  3421. return new this.constructor().copy(this);
  3422. },
  3423. copy: function (source) {
  3424. this.name = source.name;
  3425. this.image = source.image;
  3426. this.mipmaps = source.mipmaps.slice(0);
  3427. this.mapping = source.mapping;
  3428. this.wrapS = source.wrapS;
  3429. this.wrapT = source.wrapT;
  3430. this.magFilter = source.magFilter;
  3431. this.minFilter = source.minFilter;
  3432. this.anisotropy = source.anisotropy;
  3433. this.format = source.format;
  3434. this.type = source.type;
  3435. this.offset.copy(source.offset);
  3436. this.repeat.copy(source.repeat);
  3437. this.center.copy(source.center);
  3438. this.rotation = source.rotation;
  3439. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3440. this.matrix.copy(source.matrix);
  3441. this.generateMipmaps = source.generateMipmaps;
  3442. this.premultiplyAlpha = source.premultiplyAlpha;
  3443. this.flipY = source.flipY;
  3444. this.unpackAlignment = source.unpackAlignment;
  3445. this.encoding = source.encoding;
  3446. return this;
  3447. },
  3448. toJSON: function (meta) {
  3449. var isRootObject = meta === undefined || typeof meta === 'string';
  3450. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  3451. return meta.textures[this.uuid];
  3452. }
  3453. var output = {
  3454. metadata: {
  3455. version: 4.5,
  3456. type: 'Texture',
  3457. generator: 'Texture.toJSON'
  3458. },
  3459. uuid: this.uuid,
  3460. name: this.name,
  3461. mapping: this.mapping,
  3462. repeat: [this.repeat.x, this.repeat.y],
  3463. offset: [this.offset.x, this.offset.y],
  3464. center: [this.center.x, this.center.y],
  3465. rotation: this.rotation,
  3466. wrap: [this.wrapS, this.wrapT],
  3467. format: this.format,
  3468. type: this.type,
  3469. encoding: this.encoding,
  3470. minFilter: this.minFilter,
  3471. magFilter: this.magFilter,
  3472. anisotropy: this.anisotropy,
  3473. flipY: this.flipY,
  3474. premultiplyAlpha: this.premultiplyAlpha,
  3475. unpackAlignment: this.unpackAlignment
  3476. };
  3477. if (this.image !== undefined) {
  3478. // TODO: Move to THREE.Image
  3479. var image = this.image;
  3480. if (image.uuid === undefined) {
  3481. image.uuid = _Math.generateUUID(); // UGH
  3482. }
  3483. if (!isRootObject && meta.images[image.uuid] === undefined) {
  3484. var url;
  3485. if (Array.isArray(image)) {
  3486. // process array of images e.g. CubeTexture
  3487. url = [];
  3488. for (var i = 0, l = image.length; i < l; i++) {
  3489. url.push(ImageUtils.getDataURL(image[i]));
  3490. }
  3491. } else {
  3492. // process single image
  3493. url = ImageUtils.getDataURL(image);
  3494. }
  3495. meta.images[image.uuid] = {
  3496. uuid: image.uuid,
  3497. url: url
  3498. };
  3499. }
  3500. output.image = image.uuid;
  3501. }
  3502. if (!isRootObject) {
  3503. meta.textures[this.uuid] = output;
  3504. }
  3505. return output;
  3506. },
  3507. dispose: function () {
  3508. this.dispatchEvent({
  3509. type: 'dispose'
  3510. });
  3511. },
  3512. transformUv: function (uv) {
  3513. if (this.mapping !== UVMapping) return uv;
  3514. uv.applyMatrix3(this.matrix);
  3515. if (uv.x < 0 || uv.x > 1) {
  3516. switch (this.wrapS) {
  3517. case RepeatWrapping:
  3518. uv.x = uv.x - Math.floor(uv.x);
  3519. break;
  3520. case ClampToEdgeWrapping:
  3521. uv.x = uv.x < 0 ? 0 : 1;
  3522. break;
  3523. case MirroredRepeatWrapping:
  3524. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  3525. uv.x = Math.ceil(uv.x) - uv.x;
  3526. } else {
  3527. uv.x = uv.x - Math.floor(uv.x);
  3528. }
  3529. break;
  3530. }
  3531. }
  3532. if (uv.y < 0 || uv.y > 1) {
  3533. switch (this.wrapT) {
  3534. case RepeatWrapping:
  3535. uv.y = uv.y - Math.floor(uv.y);
  3536. break;
  3537. case ClampToEdgeWrapping:
  3538. uv.y = uv.y < 0 ? 0 : 1;
  3539. break;
  3540. case MirroredRepeatWrapping:
  3541. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  3542. uv.y = Math.ceil(uv.y) - uv.y;
  3543. } else {
  3544. uv.y = uv.y - Math.floor(uv.y);
  3545. }
  3546. break;
  3547. }
  3548. }
  3549. if (this.flipY) {
  3550. uv.y = 1 - uv.y;
  3551. }
  3552. return uv;
  3553. }
  3554. });
  3555. Object.defineProperty(Texture.prototype, "needsUpdate", {
  3556. set: function (value) {
  3557. if (value === true) this.version++;
  3558. }
  3559. });
  3560. /**
  3561. * @author supereggbert / http://www.paulbrunt.co.uk/
  3562. * @author philogb / http://blog.thejit.org/
  3563. * @author mikael emtinger / http://gomo.se/
  3564. * @author egraether / http://egraether.com/
  3565. * @author WestLangley / http://github.com/WestLangley
  3566. */
  3567. function Vector4(x, y, z, w) {
  3568. this.x = x || 0;
  3569. this.y = y || 0;
  3570. this.z = z || 0;
  3571. this.w = w !== undefined ? w : 1;
  3572. }
  3573. Object.defineProperties(Vector4.prototype, {
  3574. "width": {
  3575. get: function () {
  3576. return this.z;
  3577. },
  3578. set: function (value) {
  3579. this.z = value;
  3580. }
  3581. },
  3582. "height": {
  3583. get: function () {
  3584. return this.w;
  3585. },
  3586. set: function (value) {
  3587. this.w = value;
  3588. }
  3589. }
  3590. });
  3591. Object.assign(Vector4.prototype, {
  3592. isVector4: true,
  3593. set: function (x, y, z, w) {
  3594. this.x = x;
  3595. this.y = y;
  3596. this.z = z;
  3597. this.w = w;
  3598. return this;
  3599. },
  3600. setScalar: function (scalar) {
  3601. this.x = scalar;
  3602. this.y = scalar;
  3603. this.z = scalar;
  3604. this.w = scalar;
  3605. return this;
  3606. },
  3607. setX: function (x) {
  3608. this.x = x;
  3609. return this;
  3610. },
  3611. setY: function (y) {
  3612. this.y = y;
  3613. return this;
  3614. },
  3615. setZ: function (z) {
  3616. this.z = z;
  3617. return this;
  3618. },
  3619. setW: function (w) {
  3620. this.w = w;
  3621. return this;
  3622. },
  3623. setComponent: function (index, value) {
  3624. switch (index) {
  3625. case 0:
  3626. this.x = value;
  3627. break;
  3628. case 1:
  3629. this.y = value;
  3630. break;
  3631. case 2:
  3632. this.z = value;
  3633. break;
  3634. case 3:
  3635. this.w = value;
  3636. break;
  3637. default:
  3638. throw new Error('index is out of range: ' + index);
  3639. }
  3640. return this;
  3641. },
  3642. getComponent: function (index) {
  3643. switch (index) {
  3644. case 0:
  3645. return this.x;
  3646. case 1:
  3647. return this.y;
  3648. case 2:
  3649. return this.z;
  3650. case 3:
  3651. return this.w;
  3652. default:
  3653. throw new Error('index is out of range: ' + index);
  3654. }
  3655. },
  3656. clone: function () {
  3657. return new this.constructor(this.x, this.y, this.z, this.w);
  3658. },
  3659. copy: function (v) {
  3660. this.x = v.x;
  3661. this.y = v.y;
  3662. this.z = v.z;
  3663. this.w = v.w !== undefined ? v.w : 1;
  3664. return this;
  3665. },
  3666. add: function (v, w) {
  3667. if (w !== undefined) {
  3668. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  3669. return this.addVectors(v, w);
  3670. }
  3671. this.x += v.x;
  3672. this.y += v.y;
  3673. this.z += v.z;
  3674. this.w += v.w;
  3675. return this;
  3676. },
  3677. addScalar: function (s) {
  3678. this.x += s;
  3679. this.y += s;
  3680. this.z += s;
  3681. this.w += s;
  3682. return this;
  3683. },
  3684. addVectors: function (a, b) {
  3685. this.x = a.x + b.x;
  3686. this.y = a.y + b.y;
  3687. this.z = a.z + b.z;
  3688. this.w = a.w + b.w;
  3689. return this;
  3690. },
  3691. addScaledVector: function (v, s) {
  3692. this.x += v.x * s;
  3693. this.y += v.y * s;
  3694. this.z += v.z * s;
  3695. this.w += v.w * s;
  3696. return this;
  3697. },
  3698. sub: function (v, w) {
  3699. if (w !== undefined) {
  3700. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  3701. return this.subVectors(v, w);
  3702. }
  3703. this.x -= v.x;
  3704. this.y -= v.y;
  3705. this.z -= v.z;
  3706. this.w -= v.w;
  3707. return this;
  3708. },
  3709. subScalar: function (s) {
  3710. this.x -= s;
  3711. this.y -= s;
  3712. this.z -= s;
  3713. this.w -= s;
  3714. return this;
  3715. },
  3716. subVectors: function (a, b) {
  3717. this.x = a.x - b.x;
  3718. this.y = a.y - b.y;
  3719. this.z = a.z - b.z;
  3720. this.w = a.w - b.w;
  3721. return this;
  3722. },
  3723. multiplyScalar: function (scalar) {
  3724. this.x *= scalar;
  3725. this.y *= scalar;
  3726. this.z *= scalar;
  3727. this.w *= scalar;
  3728. return this;
  3729. },
  3730. applyMatrix4: function (m) {
  3731. var x = this.x,
  3732. y = this.y,
  3733. z = this.z,
  3734. w = this.w;
  3735. var e = m.elements;
  3736. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  3737. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  3738. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  3739. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  3740. return this;
  3741. },
  3742. divideScalar: function (scalar) {
  3743. return this.multiplyScalar(1 / scalar);
  3744. },
  3745. setAxisAngleFromQuaternion: function (q) {
  3746. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3747. // q is assumed to be normalized
  3748. this.w = 2 * Math.acos(q.w);
  3749. var s = Math.sqrt(1 - q.w * q.w);
  3750. if (s < 0.0001) {
  3751. this.x = 1;
  3752. this.y = 0;
  3753. this.z = 0;
  3754. } else {
  3755. this.x = q.x / s;
  3756. this.y = q.y / s;
  3757. this.z = q.z / s;
  3758. }
  3759. return this;
  3760. },
  3761. setAxisAngleFromRotationMatrix: function (m) {
  3762. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3763. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3764. var angle,
  3765. x,
  3766. y,
  3767. z,
  3768. // variables for result
  3769. epsilon = 0.01,
  3770. // margin to allow for rounding errors
  3771. epsilon2 = 0.1,
  3772. // margin to distinguish between 0 and 180 degrees
  3773. te = m.elements,
  3774. m11 = te[0],
  3775. m12 = te[4],
  3776. m13 = te[8],
  3777. m21 = te[1],
  3778. m22 = te[5],
  3779. m23 = te[9],
  3780. m31 = te[2],
  3781. m32 = te[6],
  3782. m33 = te[10];
  3783. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  3784. // singularity found
  3785. // first check for identity matrix which must have +1 for all terms
  3786. // in leading diagonal and zero in other terms
  3787. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  3788. // this singularity is identity matrix so angle = 0
  3789. this.set(1, 0, 0, 0);
  3790. return this; // zero angle, arbitrary axis
  3791. } // otherwise this singularity is angle = 180
  3792. angle = Math.PI;
  3793. var xx = (m11 + 1) / 2;
  3794. var yy = (m22 + 1) / 2;
  3795. var zz = (m33 + 1) / 2;
  3796. var xy = (m12 + m21) / 4;
  3797. var xz = (m13 + m31) / 4;
  3798. var yz = (m23 + m32) / 4;
  3799. if (xx > yy && xx > zz) {
  3800. // m11 is the largest diagonal term
  3801. if (xx < epsilon) {
  3802. x = 0;
  3803. y = 0.707106781;
  3804. z = 0.707106781;
  3805. } else {
  3806. x = Math.sqrt(xx);
  3807. y = xy / x;
  3808. z = xz / x;
  3809. }
  3810. } else if (yy > zz) {
  3811. // m22 is the largest diagonal term
  3812. if (yy < epsilon) {
  3813. x = 0.707106781;
  3814. y = 0;
  3815. z = 0.707106781;
  3816. } else {
  3817. y = Math.sqrt(yy);
  3818. x = xy / y;
  3819. z = yz / y;
  3820. }
  3821. } else {
  3822. // m33 is the largest diagonal term so base result on this
  3823. if (zz < epsilon) {
  3824. x = 0.707106781;
  3825. y = 0.707106781;
  3826. z = 0;
  3827. } else {
  3828. z = Math.sqrt(zz);
  3829. x = xz / z;
  3830. y = yz / z;
  3831. }
  3832. }
  3833. this.set(x, y, z, angle);
  3834. return this; // return 180 deg rotation
  3835. } // as we have reached here there are no singularities so we can handle normally
  3836. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  3837. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3838. // caught by singularity test above, but I've left it in just in case
  3839. this.x = (m32 - m23) / s;
  3840. this.y = (m13 - m31) / s;
  3841. this.z = (m21 - m12) / s;
  3842. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  3843. return this;
  3844. },
  3845. min: function (v) {
  3846. this.x = Math.min(this.x, v.x);
  3847. this.y = Math.min(this.y, v.y);
  3848. this.z = Math.min(this.z, v.z);
  3849. this.w = Math.min(this.w, v.w);
  3850. return this;
  3851. },
  3852. max: function (v) {
  3853. this.x = Math.max(this.x, v.x);
  3854. this.y = Math.max(this.y, v.y);
  3855. this.z = Math.max(this.z, v.z);
  3856. this.w = Math.max(this.w, v.w);
  3857. return this;
  3858. },
  3859. clamp: function (min, max) {
  3860. // assumes min < max, componentwise
  3861. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3862. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3863. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3864. this.w = Math.max(min.w, Math.min(max.w, this.w));
  3865. return this;
  3866. },
  3867. clampScalar: function (minVal, maxVal) {
  3868. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3869. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3870. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3871. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  3872. return this;
  3873. },
  3874. clampLength: function (min, max) {
  3875. var length = this.length();
  3876. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3877. },
  3878. floor: function () {
  3879. this.x = Math.floor(this.x);
  3880. this.y = Math.floor(this.y);
  3881. this.z = Math.floor(this.z);
  3882. this.w = Math.floor(this.w);
  3883. return this;
  3884. },
  3885. ceil: function () {
  3886. this.x = Math.ceil(this.x);
  3887. this.y = Math.ceil(this.y);
  3888. this.z = Math.ceil(this.z);
  3889. this.w = Math.ceil(this.w);
  3890. return this;
  3891. },
  3892. round: function () {
  3893. this.x = Math.round(this.x);
  3894. this.y = Math.round(this.y);
  3895. this.z = Math.round(this.z);
  3896. this.w = Math.round(this.w);
  3897. return this;
  3898. },
  3899. roundToZero: function () {
  3900. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3901. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3902. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3903. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  3904. return this;
  3905. },
  3906. negate: function () {
  3907. this.x = -this.x;
  3908. this.y = -this.y;
  3909. this.z = -this.z;
  3910. this.w = -this.w;
  3911. return this;
  3912. },
  3913. dot: function (v) {
  3914. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3915. },
  3916. lengthSq: function () {
  3917. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3918. },
  3919. length: function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. },
  3922. manhattanLength: function () {
  3923. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  3924. },
  3925. normalize: function () {
  3926. return this.divideScalar(this.length() || 1);
  3927. },
  3928. setLength: function (length) {
  3929. return this.normalize().multiplyScalar(length);
  3930. },
  3931. lerp: function (v, alpha) {
  3932. this.x += (v.x - this.x) * alpha;
  3933. this.y += (v.y - this.y) * alpha;
  3934. this.z += (v.z - this.z) * alpha;
  3935. this.w += (v.w - this.w) * alpha;
  3936. return this;
  3937. },
  3938. lerpVectors: function (v1, v2, alpha) {
  3939. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  3940. },
  3941. equals: function (v) {
  3942. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  3943. },
  3944. fromArray: function (array, offset) {
  3945. if (offset === undefined) offset = 0;
  3946. this.x = array[offset];
  3947. this.y = array[offset + 1];
  3948. this.z = array[offset + 2];
  3949. this.w = array[offset + 3];
  3950. return this;
  3951. },
  3952. toArray: function (array, offset) {
  3953. if (array === undefined) array = [];
  3954. if (offset === undefined) offset = 0;
  3955. array[offset] = this.x;
  3956. array[offset + 1] = this.y;
  3957. array[offset + 2] = this.z;
  3958. array[offset + 3] = this.w;
  3959. return array;
  3960. },
  3961. fromBufferAttribute: function (attribute, index, offset) {
  3962. if (offset !== undefined) {
  3963. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  3964. }
  3965. this.x = attribute.getX(index);
  3966. this.y = attribute.getY(index);
  3967. this.z = attribute.getZ(index);
  3968. this.w = attribute.getW(index);
  3969. return this;
  3970. }
  3971. });
  3972. /**
  3973. * @author szimek / https://github.com/szimek/
  3974. * @author alteredq / http://alteredqualia.com/
  3975. * @author Marius Kintel / https://github.com/kintel
  3976. */
  3977. /*
  3978. In options, we can specify:
  3979. * Texture parameters for an auto-generated target texture
  3980. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3981. */
  3982. function WebGLRenderTarget(width, height, options) {
  3983. this.width = width;
  3984. this.height = height;
  3985. this.scissor = new Vector4(0, 0, width, height);
  3986. this.scissorTest = false;
  3987. this.viewport = new Vector4(0, 0, width, height);
  3988. options = options || {};
  3989. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  3990. this.texture.image = {};
  3991. this.texture.image.width = width;
  3992. this.texture.image.height = height;
  3993. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  3994. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  3995. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  3996. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  3997. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  3998. }
  3999. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4000. constructor: WebGLRenderTarget,
  4001. isWebGLRenderTarget: true,
  4002. setSize: function (width, height) {
  4003. if (this.width !== width || this.height !== height) {
  4004. this.width = width;
  4005. this.height = height;
  4006. this.texture.image.width = width;
  4007. this.texture.image.height = height;
  4008. this.dispose();
  4009. }
  4010. this.viewport.set(0, 0, width, height);
  4011. this.scissor.set(0, 0, width, height);
  4012. },
  4013. clone: function () {
  4014. return new this.constructor().copy(this);
  4015. },
  4016. copy: function (source) {
  4017. this.width = source.width;
  4018. this.height = source.height;
  4019. this.viewport.copy(source.viewport);
  4020. this.texture = source.texture.clone();
  4021. this.depthBuffer = source.depthBuffer;
  4022. this.stencilBuffer = source.stencilBuffer;
  4023. this.depthTexture = source.depthTexture;
  4024. return this;
  4025. },
  4026. dispose: function () {
  4027. this.dispatchEvent({
  4028. type: 'dispose'
  4029. });
  4030. }
  4031. });
  4032. /**
  4033. * @author Mugen87 / https://github.com/Mugen87
  4034. * @author Matt DesLauriers / @mattdesl
  4035. */
  4036. function WebGLMultisampleRenderTarget(width, height, options) {
  4037. WebGLRenderTarget.call(this, width, height, options);
  4038. this.samples = 4;
  4039. }
  4040. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  4041. constructor: WebGLMultisampleRenderTarget,
  4042. isWebGLMultisampleRenderTarget: true,
  4043. copy: function (source) {
  4044. WebGLRenderTarget.prototype.copy.call(this, source);
  4045. this.samples = source.samples;
  4046. return this;
  4047. }
  4048. });
  4049. var _v1 = new Vector3();
  4050. var _m1 = new Matrix4();
  4051. var _zero = new Vector3(0, 0, 0);
  4052. var _one = new Vector3(1, 1, 1);
  4053. var _x = new Vector3();
  4054. var _y = new Vector3();
  4055. var _z = new Vector3();
  4056. /**
  4057. * @author mrdoob / http://mrdoob.com/
  4058. * @author supereggbert / http://www.paulbrunt.co.uk/
  4059. * @author philogb / http://blog.thejit.org/
  4060. * @author jordi_ros / http://plattsoft.com
  4061. * @author D1plo1d / http://github.com/D1plo1d
  4062. * @author alteredq / http://alteredqualia.com/
  4063. * @author mikael emtinger / http://gomo.se/
  4064. * @author timknip / http://www.floorplanner.com/
  4065. * @author bhouston / http://clara.io
  4066. * @author WestLangley / http://github.com/WestLangley
  4067. */
  4068. function Matrix4() {
  4069. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4070. if (arguments.length > 0) {
  4071. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  4072. }
  4073. }
  4074. Object.assign(Matrix4.prototype, {
  4075. isMatrix4: true,
  4076. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  4077. var te = this.elements;
  4078. te[0] = n11;
  4079. te[4] = n12;
  4080. te[8] = n13;
  4081. te[12] = n14;
  4082. te[1] = n21;
  4083. te[5] = n22;
  4084. te[9] = n23;
  4085. te[13] = n24;
  4086. te[2] = n31;
  4087. te[6] = n32;
  4088. te[10] = n33;
  4089. te[14] = n34;
  4090. te[3] = n41;
  4091. te[7] = n42;
  4092. te[11] = n43;
  4093. te[15] = n44;
  4094. return this;
  4095. },
  4096. identity: function () {
  4097. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4098. return this;
  4099. },
  4100. clone: function () {
  4101. return new Matrix4().fromArray(this.elements);
  4102. },
  4103. copy: function (m) {
  4104. var te = this.elements;
  4105. var me = m.elements;
  4106. te[0] = me[0];
  4107. te[1] = me[1];
  4108. te[2] = me[2];
  4109. te[3] = me[3];
  4110. te[4] = me[4];
  4111. te[5] = me[5];
  4112. te[6] = me[6];
  4113. te[7] = me[7];
  4114. te[8] = me[8];
  4115. te[9] = me[9];
  4116. te[10] = me[10];
  4117. te[11] = me[11];
  4118. te[12] = me[12];
  4119. te[13] = me[13];
  4120. te[14] = me[14];
  4121. te[15] = me[15];
  4122. return this;
  4123. },
  4124. copyPosition: function (m) {
  4125. var te = this.elements,
  4126. me = m.elements;
  4127. te[12] = me[12];
  4128. te[13] = me[13];
  4129. te[14] = me[14];
  4130. return this;
  4131. },
  4132. extractBasis: function (xAxis, yAxis, zAxis) {
  4133. xAxis.setFromMatrixColumn(this, 0);
  4134. yAxis.setFromMatrixColumn(this, 1);
  4135. zAxis.setFromMatrixColumn(this, 2);
  4136. return this;
  4137. },
  4138. makeBasis: function (xAxis, yAxis, zAxis) {
  4139. 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);
  4140. return this;
  4141. },
  4142. extractRotation: function (m) {
  4143. // this method does not support reflection matrices
  4144. var te = this.elements;
  4145. var me = m.elements;
  4146. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  4147. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  4148. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  4149. te[0] = me[0] * scaleX;
  4150. te[1] = me[1] * scaleX;
  4151. te[2] = me[2] * scaleX;
  4152. te[3] = 0;
  4153. te[4] = me[4] * scaleY;
  4154. te[5] = me[5] * scaleY;
  4155. te[6] = me[6] * scaleY;
  4156. te[7] = 0;
  4157. te[8] = me[8] * scaleZ;
  4158. te[9] = me[9] * scaleZ;
  4159. te[10] = me[10] * scaleZ;
  4160. te[11] = 0;
  4161. te[12] = 0;
  4162. te[13] = 0;
  4163. te[14] = 0;
  4164. te[15] = 1;
  4165. return this;
  4166. },
  4167. makeRotationFromEuler: function (euler) {
  4168. if (!(euler && euler.isEuler)) {
  4169. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4170. }
  4171. var te = this.elements;
  4172. var x = euler.x,
  4173. y = euler.y,
  4174. z = euler.z;
  4175. var a = Math.cos(x),
  4176. b = Math.sin(x);
  4177. var c = Math.cos(y),
  4178. d = Math.sin(y);
  4179. var e = Math.cos(z),
  4180. f = Math.sin(z);
  4181. if (euler.order === 'XYZ') {
  4182. var ae = a * e,
  4183. af = a * f,
  4184. be = b * e,
  4185. bf = b * f;
  4186. te[0] = c * e;
  4187. te[4] = -c * f;
  4188. te[8] = d;
  4189. te[1] = af + be * d;
  4190. te[5] = ae - bf * d;
  4191. te[9] = -b * c;
  4192. te[2] = bf - ae * d;
  4193. te[6] = be + af * d;
  4194. te[10] = a * c;
  4195. } else if (euler.order === 'YXZ') {
  4196. var ce = c * e,
  4197. cf = c * f,
  4198. de = d * e,
  4199. df = d * f;
  4200. te[0] = ce + df * b;
  4201. te[4] = de * b - cf;
  4202. te[8] = a * d;
  4203. te[1] = a * f;
  4204. te[5] = a * e;
  4205. te[9] = -b;
  4206. te[2] = cf * b - de;
  4207. te[6] = df + ce * b;
  4208. te[10] = a * c;
  4209. } else if (euler.order === 'ZXY') {
  4210. var ce = c * e,
  4211. cf = c * f,
  4212. de = d * e,
  4213. df = d * f;
  4214. te[0] = ce - df * b;
  4215. te[4] = -a * f;
  4216. te[8] = de + cf * b;
  4217. te[1] = cf + de * b;
  4218. te[5] = a * e;
  4219. te[9] = df - ce * b;
  4220. te[2] = -a * d;
  4221. te[6] = b;
  4222. te[10] = a * c;
  4223. } else if (euler.order === 'ZYX') {
  4224. var ae = a * e,
  4225. af = a * f,
  4226. be = b * e,
  4227. bf = b * f;
  4228. te[0] = c * e;
  4229. te[4] = be * d - af;
  4230. te[8] = ae * d + bf;
  4231. te[1] = c * f;
  4232. te[5] = bf * d + ae;
  4233. te[9] = af * d - be;
  4234. te[2] = -d;
  4235. te[6] = b * c;
  4236. te[10] = a * c;
  4237. } else if (euler.order === 'YZX') {
  4238. var ac = a * c,
  4239. ad = a * d,
  4240. bc = b * c,
  4241. bd = b * d;
  4242. te[0] = c * e;
  4243. te[4] = bd - ac * f;
  4244. te[8] = bc * f + ad;
  4245. te[1] = f;
  4246. te[5] = a * e;
  4247. te[9] = -b * e;
  4248. te[2] = -d * e;
  4249. te[6] = ad * f + bc;
  4250. te[10] = ac - bd * f;
  4251. } else if (euler.order === 'XZY') {
  4252. var ac = a * c,
  4253. ad = a * d,
  4254. bc = b * c,
  4255. bd = b * d;
  4256. te[0] = c * e;
  4257. te[4] = -f;
  4258. te[8] = d * e;
  4259. te[1] = ac * f + bd;
  4260. te[5] = a * e;
  4261. te[9] = ad * f - bc;
  4262. te[2] = bc * f - ad;
  4263. te[6] = b * e;
  4264. te[10] = bd * f + ac;
  4265. } // bottom row
  4266. te[3] = 0;
  4267. te[7] = 0;
  4268. te[11] = 0; // last column
  4269. te[12] = 0;
  4270. te[13] = 0;
  4271. te[14] = 0;
  4272. te[15] = 1;
  4273. return this;
  4274. },
  4275. makeRotationFromQuaternion: function (q) {
  4276. return this.compose(_zero, q, _one);
  4277. },
  4278. lookAt: function (eye, target, up) {
  4279. var te = this.elements;
  4280. _z.subVectors(eye, target);
  4281. if (_z.lengthSq() === 0) {
  4282. // eye and target are in the same position
  4283. _z.z = 1;
  4284. }
  4285. _z.normalize();
  4286. _x.crossVectors(up, _z);
  4287. if (_x.lengthSq() === 0) {
  4288. // up and z are parallel
  4289. if (Math.abs(up.z) === 1) {
  4290. _z.x += 0.0001;
  4291. } else {
  4292. _z.z += 0.0001;
  4293. }
  4294. _z.normalize();
  4295. _x.crossVectors(up, _z);
  4296. }
  4297. _x.normalize();
  4298. _y.crossVectors(_z, _x);
  4299. te[0] = _x.x;
  4300. te[4] = _y.x;
  4301. te[8] = _z.x;
  4302. te[1] = _x.y;
  4303. te[5] = _y.y;
  4304. te[9] = _z.y;
  4305. te[2] = _x.z;
  4306. te[6] = _y.z;
  4307. te[10] = _z.z;
  4308. return this;
  4309. },
  4310. multiply: function (m, n) {
  4311. if (n !== undefined) {
  4312. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4313. return this.multiplyMatrices(m, n);
  4314. }
  4315. return this.multiplyMatrices(this, m);
  4316. },
  4317. premultiply: function (m) {
  4318. return this.multiplyMatrices(m, this);
  4319. },
  4320. multiplyMatrices: function (a, b) {
  4321. var ae = a.elements;
  4322. var be = b.elements;
  4323. var te = this.elements;
  4324. var a11 = ae[0],
  4325. a12 = ae[4],
  4326. a13 = ae[8],
  4327. a14 = ae[12];
  4328. var a21 = ae[1],
  4329. a22 = ae[5],
  4330. a23 = ae[9],
  4331. a24 = ae[13];
  4332. var a31 = ae[2],
  4333. a32 = ae[6],
  4334. a33 = ae[10],
  4335. a34 = ae[14];
  4336. var a41 = ae[3],
  4337. a42 = ae[7],
  4338. a43 = ae[11],
  4339. a44 = ae[15];
  4340. var b11 = be[0],
  4341. b12 = be[4],
  4342. b13 = be[8],
  4343. b14 = be[12];
  4344. var b21 = be[1],
  4345. b22 = be[5],
  4346. b23 = be[9],
  4347. b24 = be[13];
  4348. var b31 = be[2],
  4349. b32 = be[6],
  4350. b33 = be[10],
  4351. b34 = be[14];
  4352. var b41 = be[3],
  4353. b42 = be[7],
  4354. b43 = be[11],
  4355. b44 = be[15];
  4356. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4357. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4358. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4359. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4360. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4361. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4362. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4363. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4364. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4365. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4366. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4367. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4368. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4369. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4370. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4371. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4372. return this;
  4373. },
  4374. multiplyScalar: function (s) {
  4375. var te = this.elements;
  4376. te[0] *= s;
  4377. te[4] *= s;
  4378. te[8] *= s;
  4379. te[12] *= s;
  4380. te[1] *= s;
  4381. te[5] *= s;
  4382. te[9] *= s;
  4383. te[13] *= s;
  4384. te[2] *= s;
  4385. te[6] *= s;
  4386. te[10] *= s;
  4387. te[14] *= s;
  4388. te[3] *= s;
  4389. te[7] *= s;
  4390. te[11] *= s;
  4391. te[15] *= s;
  4392. return this;
  4393. },
  4394. applyToBufferAttribute: function (attribute) {
  4395. for (var i = 0, l = attribute.count; i < l; i++) {
  4396. _v1.x = attribute.getX(i);
  4397. _v1.y = attribute.getY(i);
  4398. _v1.z = attribute.getZ(i);
  4399. _v1.applyMatrix4(this);
  4400. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  4401. }
  4402. return attribute;
  4403. },
  4404. determinant: function () {
  4405. var te = this.elements;
  4406. var n11 = te[0],
  4407. n12 = te[4],
  4408. n13 = te[8],
  4409. n14 = te[12];
  4410. var n21 = te[1],
  4411. n22 = te[5],
  4412. n23 = te[9],
  4413. n24 = te[13];
  4414. var n31 = te[2],
  4415. n32 = te[6],
  4416. n33 = te[10],
  4417. n34 = te[14];
  4418. var n41 = te[3],
  4419. n42 = te[7],
  4420. n43 = te[11],
  4421. n44 = te[15]; //TODO: make this more efficient
  4422. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4423. 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);
  4424. },
  4425. transpose: function () {
  4426. var te = this.elements;
  4427. var tmp;
  4428. tmp = te[1];
  4429. te[1] = te[4];
  4430. te[4] = tmp;
  4431. tmp = te[2];
  4432. te[2] = te[8];
  4433. te[8] = tmp;
  4434. tmp = te[6];
  4435. te[6] = te[9];
  4436. te[9] = tmp;
  4437. tmp = te[3];
  4438. te[3] = te[12];
  4439. te[12] = tmp;
  4440. tmp = te[7];
  4441. te[7] = te[13];
  4442. te[13] = tmp;
  4443. tmp = te[11];
  4444. te[11] = te[14];
  4445. te[14] = tmp;
  4446. return this;
  4447. },
  4448. setPosition: function (x, y, z) {
  4449. var te = this.elements;
  4450. if (x.isVector3) {
  4451. te[12] = x.x;
  4452. te[13] = x.y;
  4453. te[14] = x.z;
  4454. } else {
  4455. te[12] = x;
  4456. te[13] = y;
  4457. te[14] = z;
  4458. }
  4459. return this;
  4460. },
  4461. getInverse: function (m, throwOnDegenerate) {
  4462. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4463. var te = this.elements,
  4464. me = m.elements,
  4465. n11 = me[0],
  4466. n21 = me[1],
  4467. n31 = me[2],
  4468. n41 = me[3],
  4469. n12 = me[4],
  4470. n22 = me[5],
  4471. n32 = me[6],
  4472. n42 = me[7],
  4473. n13 = me[8],
  4474. n23 = me[9],
  4475. n33 = me[10],
  4476. n43 = me[11],
  4477. n14 = me[12],
  4478. n24 = me[13],
  4479. n34 = me[14],
  4480. n44 = me[15],
  4481. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4482. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4483. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4484. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4485. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4486. if (det === 0) {
  4487. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4488. if (throwOnDegenerate === true) {
  4489. throw new Error(msg);
  4490. } else {
  4491. console.warn(msg);
  4492. }
  4493. return this.identity();
  4494. }
  4495. var detInv = 1 / det;
  4496. te[0] = t11 * detInv;
  4497. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4498. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4499. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4500. te[4] = t12 * detInv;
  4501. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4502. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4503. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4504. te[8] = t13 * detInv;
  4505. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4506. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4507. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4508. te[12] = t14 * detInv;
  4509. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4510. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4511. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4512. return this;
  4513. },
  4514. scale: function (v) {
  4515. var te = this.elements;
  4516. var x = v.x,
  4517. y = v.y,
  4518. z = v.z;
  4519. te[0] *= x;
  4520. te[4] *= y;
  4521. te[8] *= z;
  4522. te[1] *= x;
  4523. te[5] *= y;
  4524. te[9] *= z;
  4525. te[2] *= x;
  4526. te[6] *= y;
  4527. te[10] *= z;
  4528. te[3] *= x;
  4529. te[7] *= y;
  4530. te[11] *= z;
  4531. return this;
  4532. },
  4533. getMaxScaleOnAxis: function () {
  4534. var te = this.elements;
  4535. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4536. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4537. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4538. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4539. },
  4540. makeTranslation: function (x, y, z) {
  4541. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4542. return this;
  4543. },
  4544. makeRotationX: function (theta) {
  4545. var c = Math.cos(theta),
  4546. s = Math.sin(theta);
  4547. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4548. return this;
  4549. },
  4550. makeRotationY: function (theta) {
  4551. var c = Math.cos(theta),
  4552. s = Math.sin(theta);
  4553. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4554. return this;
  4555. },
  4556. makeRotationZ: function (theta) {
  4557. var c = Math.cos(theta),
  4558. s = Math.sin(theta);
  4559. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4560. return this;
  4561. },
  4562. makeRotationAxis: function (axis, angle) {
  4563. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4564. var c = Math.cos(angle);
  4565. var s = Math.sin(angle);
  4566. var t = 1 - c;
  4567. var x = axis.x,
  4568. y = axis.y,
  4569. z = axis.z;
  4570. var tx = t * x,
  4571. ty = t * y;
  4572. 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);
  4573. return this;
  4574. },
  4575. makeScale: function (x, y, z) {
  4576. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4577. return this;
  4578. },
  4579. makeShear: function (x, y, z) {
  4580. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4581. return this;
  4582. },
  4583. compose: function (position, quaternion, scale) {
  4584. var te = this.elements;
  4585. var x = quaternion._x,
  4586. y = quaternion._y,
  4587. z = quaternion._z,
  4588. w = quaternion._w;
  4589. var x2 = x + x,
  4590. y2 = y + y,
  4591. z2 = z + z;
  4592. var xx = x * x2,
  4593. xy = x * y2,
  4594. xz = x * z2;
  4595. var yy = y * y2,
  4596. yz = y * z2,
  4597. zz = z * z2;
  4598. var wx = w * x2,
  4599. wy = w * y2,
  4600. wz = w * z2;
  4601. var sx = scale.x,
  4602. sy = scale.y,
  4603. sz = scale.z;
  4604. te[0] = (1 - (yy + zz)) * sx;
  4605. te[1] = (xy + wz) * sx;
  4606. te[2] = (xz - wy) * sx;
  4607. te[3] = 0;
  4608. te[4] = (xy - wz) * sy;
  4609. te[5] = (1 - (xx + zz)) * sy;
  4610. te[6] = (yz + wx) * sy;
  4611. te[7] = 0;
  4612. te[8] = (xz + wy) * sz;
  4613. te[9] = (yz - wx) * sz;
  4614. te[10] = (1 - (xx + yy)) * sz;
  4615. te[11] = 0;
  4616. te[12] = position.x;
  4617. te[13] = position.y;
  4618. te[14] = position.z;
  4619. te[15] = 1;
  4620. return this;
  4621. },
  4622. decompose: function (position, quaternion, scale) {
  4623. var te = this.elements;
  4624. var sx = _v1.set(te[0], te[1], te[2]).length();
  4625. var sy = _v1.set(te[4], te[5], te[6]).length();
  4626. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4627. var det = this.determinant();
  4628. if (det < 0) sx = -sx;
  4629. position.x = te[12];
  4630. position.y = te[13];
  4631. position.z = te[14]; // scale the rotation part
  4632. _m1.copy(this);
  4633. var invSX = 1 / sx;
  4634. var invSY = 1 / sy;
  4635. var invSZ = 1 / sz;
  4636. _m1.elements[0] *= invSX;
  4637. _m1.elements[1] *= invSX;
  4638. _m1.elements[2] *= invSX;
  4639. _m1.elements[4] *= invSY;
  4640. _m1.elements[5] *= invSY;
  4641. _m1.elements[6] *= invSY;
  4642. _m1.elements[8] *= invSZ;
  4643. _m1.elements[9] *= invSZ;
  4644. _m1.elements[10] *= invSZ;
  4645. quaternion.setFromRotationMatrix(_m1);
  4646. scale.x = sx;
  4647. scale.y = sy;
  4648. scale.z = sz;
  4649. return this;
  4650. },
  4651. makePerspective: function (left, right, top, bottom, near, far) {
  4652. if (far === undefined) {
  4653. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4654. }
  4655. var te = this.elements;
  4656. var x = 2 * near / (right - left);
  4657. var y = 2 * near / (top - bottom);
  4658. var a = (right + left) / (right - left);
  4659. var b = (top + bottom) / (top - bottom);
  4660. var c = -(far + near) / (far - near);
  4661. var d = -2 * far * near / (far - near);
  4662. te[0] = x;
  4663. te[4] = 0;
  4664. te[8] = a;
  4665. te[12] = 0;
  4666. te[1] = 0;
  4667. te[5] = y;
  4668. te[9] = b;
  4669. te[13] = 0;
  4670. te[2] = 0;
  4671. te[6] = 0;
  4672. te[10] = c;
  4673. te[14] = d;
  4674. te[3] = 0;
  4675. te[7] = 0;
  4676. te[11] = -1;
  4677. te[15] = 0;
  4678. return this;
  4679. },
  4680. makeOrthographic: function (left, right, top, bottom, near, far) {
  4681. var te = this.elements;
  4682. var w = 1.0 / (right - left);
  4683. var h = 1.0 / (top - bottom);
  4684. var p = 1.0 / (far - near);
  4685. var x = (right + left) * w;
  4686. var y = (top + bottom) * h;
  4687. var z = (far + near) * p;
  4688. te[0] = 2 * w;
  4689. te[4] = 0;
  4690. te[8] = 0;
  4691. te[12] = -x;
  4692. te[1] = 0;
  4693. te[5] = 2 * h;
  4694. te[9] = 0;
  4695. te[13] = -y;
  4696. te[2] = 0;
  4697. te[6] = 0;
  4698. te[10] = -2 * p;
  4699. te[14] = -z;
  4700. te[3] = 0;
  4701. te[7] = 0;
  4702. te[11] = 0;
  4703. te[15] = 1;
  4704. return this;
  4705. },
  4706. equals: function (matrix) {
  4707. var te = this.elements;
  4708. var me = matrix.elements;
  4709. for (var i = 0; i < 16; i++) {
  4710. if (te[i] !== me[i]) return false;
  4711. }
  4712. return true;
  4713. },
  4714. fromArray: function (array, offset) {
  4715. if (offset === undefined) offset = 0;
  4716. for (var i = 0; i < 16; i++) {
  4717. this.elements[i] = array[i + offset];
  4718. }
  4719. return this;
  4720. },
  4721. toArray: function (array, offset) {
  4722. if (array === undefined) array = [];
  4723. if (offset === undefined) offset = 0;
  4724. var te = this.elements;
  4725. array[offset] = te[0];
  4726. array[offset + 1] = te[1];
  4727. array[offset + 2] = te[2];
  4728. array[offset + 3] = te[3];
  4729. array[offset + 4] = te[4];
  4730. array[offset + 5] = te[5];
  4731. array[offset + 6] = te[6];
  4732. array[offset + 7] = te[7];
  4733. array[offset + 8] = te[8];
  4734. array[offset + 9] = te[9];
  4735. array[offset + 10] = te[10];
  4736. array[offset + 11] = te[11];
  4737. array[offset + 12] = te[12];
  4738. array[offset + 13] = te[13];
  4739. array[offset + 14] = te[14];
  4740. array[offset + 15] = te[15];
  4741. return array;
  4742. }
  4743. });
  4744. /**
  4745. * @author mrdoob / http://mrdoob.com/
  4746. * @author WestLangley / http://github.com/WestLangley
  4747. * @author bhouston / http://clara.io
  4748. */
  4749. var _matrix = new Matrix4();
  4750. var _quaternion$1 = new Quaternion();
  4751. function Euler(x, y, z, order) {
  4752. this._x = x || 0;
  4753. this._y = y || 0;
  4754. this._z = z || 0;
  4755. this._order = order || Euler.DefaultOrder;
  4756. }
  4757. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4758. Euler.DefaultOrder = 'XYZ';
  4759. Object.defineProperties(Euler.prototype, {
  4760. x: {
  4761. get: function () {
  4762. return this._x;
  4763. },
  4764. set: function (value) {
  4765. this._x = value;
  4766. this._onChangeCallback();
  4767. }
  4768. },
  4769. y: {
  4770. get: function () {
  4771. return this._y;
  4772. },
  4773. set: function (value) {
  4774. this._y = value;
  4775. this._onChangeCallback();
  4776. }
  4777. },
  4778. z: {
  4779. get: function () {
  4780. return this._z;
  4781. },
  4782. set: function (value) {
  4783. this._z = value;
  4784. this._onChangeCallback();
  4785. }
  4786. },
  4787. order: {
  4788. get: function () {
  4789. return this._order;
  4790. },
  4791. set: function (value) {
  4792. this._order = value;
  4793. this._onChangeCallback();
  4794. }
  4795. }
  4796. });
  4797. Object.assign(Euler.prototype, {
  4798. isEuler: true,
  4799. set: function (x, y, z, order) {
  4800. this._x = x;
  4801. this._y = y;
  4802. this._z = z;
  4803. this._order = order || this._order;
  4804. this._onChangeCallback();
  4805. return this;
  4806. },
  4807. clone: function () {
  4808. return new this.constructor(this._x, this._y, this._z, this._order);
  4809. },
  4810. copy: function (euler) {
  4811. this._x = euler._x;
  4812. this._y = euler._y;
  4813. this._z = euler._z;
  4814. this._order = euler._order;
  4815. this._onChangeCallback();
  4816. return this;
  4817. },
  4818. setFromRotationMatrix: function (m, order, update) {
  4819. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4820. var te = m.elements;
  4821. var m11 = te[0],
  4822. m12 = te[4],
  4823. m13 = te[8];
  4824. var m21 = te[1],
  4825. m22 = te[5],
  4826. m23 = te[9];
  4827. var m31 = te[2],
  4828. m32 = te[6],
  4829. m33 = te[10];
  4830. order = order || this._order;
  4831. if (order === 'XYZ') {
  4832. this._y = Math.asin(clamp(m13, -1, 1));
  4833. if (Math.abs(m13) < 0.9999999) {
  4834. this._x = Math.atan2(-m23, m33);
  4835. this._z = Math.atan2(-m12, m11);
  4836. } else {
  4837. this._x = Math.atan2(m32, m22);
  4838. this._z = 0;
  4839. }
  4840. } else if (order === 'YXZ') {
  4841. this._x = Math.asin(-clamp(m23, -1, 1));
  4842. if (Math.abs(m23) < 0.9999999) {
  4843. this._y = Math.atan2(m13, m33);
  4844. this._z = Math.atan2(m21, m22);
  4845. } else {
  4846. this._y = Math.atan2(-m31, m11);
  4847. this._z = 0;
  4848. }
  4849. } else if (order === 'ZXY') {
  4850. this._x = Math.asin(clamp(m32, -1, 1));
  4851. if (Math.abs(m32) < 0.9999999) {
  4852. this._y = Math.atan2(-m31, m33);
  4853. this._z = Math.atan2(-m12, m22);
  4854. } else {
  4855. this._y = 0;
  4856. this._z = Math.atan2(m21, m11);
  4857. }
  4858. } else if (order === 'ZYX') {
  4859. this._y = Math.asin(-clamp(m31, -1, 1));
  4860. if (Math.abs(m31) < 0.9999999) {
  4861. this._x = Math.atan2(m32, m33);
  4862. this._z = Math.atan2(m21, m11);
  4863. } else {
  4864. this._x = 0;
  4865. this._z = Math.atan2(-m12, m22);
  4866. }
  4867. } else if (order === 'YZX') {
  4868. this._z = Math.asin(clamp(m21, -1, 1));
  4869. if (Math.abs(m21) < 0.9999999) {
  4870. this._x = Math.atan2(-m23, m22);
  4871. this._y = Math.atan2(-m31, m11);
  4872. } else {
  4873. this._x = 0;
  4874. this._y = Math.atan2(m13, m33);
  4875. }
  4876. } else if (order === 'XZY') {
  4877. this._z = Math.asin(-clamp(m12, -1, 1));
  4878. if (Math.abs(m12) < 0.9999999) {
  4879. this._x = Math.atan2(m32, m22);
  4880. this._y = Math.atan2(m13, m11);
  4881. } else {
  4882. this._x = Math.atan2(-m23, m33);
  4883. this._y = 0;
  4884. }
  4885. } else {
  4886. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  4887. }
  4888. this._order = order;
  4889. if (update !== false) this._onChangeCallback();
  4890. return this;
  4891. },
  4892. setFromQuaternion: function (q, order, update) {
  4893. _matrix.makeRotationFromQuaternion(q);
  4894. return this.setFromRotationMatrix(_matrix, order, update);
  4895. },
  4896. setFromVector3: function (v, order) {
  4897. return this.set(v.x, v.y, v.z, order || this._order);
  4898. },
  4899. reorder: function (newOrder) {
  4900. // WARNING: this discards revolution information -bhouston
  4901. _quaternion$1.setFromEuler(this);
  4902. return this.setFromQuaternion(_quaternion$1, newOrder);
  4903. },
  4904. equals: function (euler) {
  4905. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4906. },
  4907. fromArray: function (array) {
  4908. this._x = array[0];
  4909. this._y = array[1];
  4910. this._z = array[2];
  4911. if (array[3] !== undefined) this._order = array[3];
  4912. this._onChangeCallback();
  4913. return this;
  4914. },
  4915. toArray: function (array, offset) {
  4916. if (array === undefined) array = [];
  4917. if (offset === undefined) offset = 0;
  4918. array[offset] = this._x;
  4919. array[offset + 1] = this._y;
  4920. array[offset + 2] = this._z;
  4921. array[offset + 3] = this._order;
  4922. return array;
  4923. },
  4924. toVector3: function (optionalResult) {
  4925. if (optionalResult) {
  4926. return optionalResult.set(this._x, this._y, this._z);
  4927. } else {
  4928. return new Vector3(this._x, this._y, this._z);
  4929. }
  4930. },
  4931. _onChange: function (callback) {
  4932. this._onChangeCallback = callback;
  4933. return this;
  4934. },
  4935. _onChangeCallback: function () {}
  4936. });
  4937. /**
  4938. * @author mrdoob / http://mrdoob.com/
  4939. */
  4940. function Layers() {
  4941. this.mask = 1 | 0;
  4942. }
  4943. Object.assign(Layers.prototype, {
  4944. set: function (channel) {
  4945. this.mask = 1 << channel | 0;
  4946. },
  4947. enable: function (channel) {
  4948. this.mask |= 1 << channel | 0;
  4949. },
  4950. enableAll: function () {
  4951. this.mask = 0xffffffff | 0;
  4952. },
  4953. toggle: function (channel) {
  4954. this.mask ^= 1 << channel | 0;
  4955. },
  4956. disable: function (channel) {
  4957. this.mask &= ~(1 << channel | 0);
  4958. },
  4959. disableAll: function () {
  4960. this.mask = 0;
  4961. },
  4962. test: function (layers) {
  4963. return (this.mask & layers.mask) !== 0;
  4964. }
  4965. });
  4966. var _object3DId = 0;
  4967. var _v1$1 = new Vector3();
  4968. var _q1 = new Quaternion();
  4969. var _m1$1 = new Matrix4();
  4970. var _target = new Vector3();
  4971. var _position = new Vector3();
  4972. var _scale = new Vector3();
  4973. var _quaternion$2 = new Quaternion();
  4974. var _xAxis = new Vector3(1, 0, 0);
  4975. var _yAxis = new Vector3(0, 1, 0);
  4976. var _zAxis = new Vector3(0, 0, 1);
  4977. var _addedEvent = {
  4978. type: 'added'
  4979. };
  4980. var _removedEvent = {
  4981. type: 'removed'
  4982. };
  4983. /**
  4984. * @author mrdoob / http://mrdoob.com/
  4985. * @author mikael emtinger / http://gomo.se/
  4986. * @author alteredq / http://alteredqualia.com/
  4987. * @author WestLangley / http://github.com/WestLangley
  4988. * @author elephantatwork / www.elephantatwork.ch
  4989. */
  4990. function Object3D() {
  4991. Object.defineProperty(this, 'id', {
  4992. value: _object3DId++
  4993. });
  4994. this.uuid = _Math.generateUUID();
  4995. this.name = '';
  4996. this.type = 'Object3D';
  4997. this.parent = null;
  4998. this.children = [];
  4999. this.up = Object3D.DefaultUp.clone();
  5000. var position = new Vector3();
  5001. var rotation = new Euler();
  5002. var quaternion = new Quaternion();
  5003. var scale = new Vector3(1, 1, 1);
  5004. function onRotationChange() {
  5005. quaternion.setFromEuler(rotation, false);
  5006. }
  5007. function onQuaternionChange() {
  5008. rotation.setFromQuaternion(quaternion, undefined, false);
  5009. }
  5010. rotation._onChange(onRotationChange);
  5011. quaternion._onChange(onQuaternionChange);
  5012. Object.defineProperties(this, {
  5013. position: {
  5014. configurable: true,
  5015. enumerable: true,
  5016. value: position
  5017. },
  5018. rotation: {
  5019. configurable: true,
  5020. enumerable: true,
  5021. value: rotation
  5022. },
  5023. quaternion: {
  5024. configurable: true,
  5025. enumerable: true,
  5026. value: quaternion
  5027. },
  5028. scale: {
  5029. configurable: true,
  5030. enumerable: true,
  5031. value: scale
  5032. },
  5033. modelViewMatrix: {
  5034. value: new Matrix4()
  5035. },
  5036. normalMatrix: {
  5037. value: new Matrix3()
  5038. }
  5039. });
  5040. this.matrix = new Matrix4();
  5041. this.matrixWorld = new Matrix4();
  5042. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5043. this.matrixWorldNeedsUpdate = false;
  5044. this.layers = new Layers();
  5045. this.visible = true;
  5046. this.castShadow = false;
  5047. this.receiveShadow = false;
  5048. this.frustumCulled = true;
  5049. this.renderOrder = 0;
  5050. this.userData = {};
  5051. }
  5052. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5053. Object3D.DefaultMatrixAutoUpdate = true;
  5054. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5055. constructor: Object3D,
  5056. isObject3D: true,
  5057. onBeforeRender: function () {},
  5058. onAfterRender: function () {},
  5059. applyMatrix: function (matrix) {
  5060. if (this.matrixAutoUpdate) this.updateMatrix();
  5061. this.matrix.premultiply(matrix);
  5062. this.matrix.decompose(this.position, this.quaternion, this.scale);
  5063. },
  5064. applyQuaternion: function (q) {
  5065. this.quaternion.premultiply(q);
  5066. return this;
  5067. },
  5068. setRotationFromAxisAngle: function (axis, angle) {
  5069. // assumes axis is normalized
  5070. this.quaternion.setFromAxisAngle(axis, angle);
  5071. },
  5072. setRotationFromEuler: function (euler) {
  5073. this.quaternion.setFromEuler(euler, true);
  5074. },
  5075. setRotationFromMatrix: function (m) {
  5076. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5077. this.quaternion.setFromRotationMatrix(m);
  5078. },
  5079. setRotationFromQuaternion: function (q) {
  5080. // assumes q is normalized
  5081. this.quaternion.copy(q);
  5082. },
  5083. rotateOnAxis: function (axis, angle) {
  5084. // rotate object on axis in object space
  5085. // axis is assumed to be normalized
  5086. _q1.setFromAxisAngle(axis, angle);
  5087. this.quaternion.multiply(_q1);
  5088. return this;
  5089. },
  5090. rotateOnWorldAxis: function (axis, angle) {
  5091. // rotate object on axis in world space
  5092. // axis is assumed to be normalized
  5093. // method assumes no rotated parent
  5094. _q1.setFromAxisAngle(axis, angle);
  5095. this.quaternion.premultiply(_q1);
  5096. return this;
  5097. },
  5098. rotateX: function (angle) {
  5099. return this.rotateOnAxis(_xAxis, angle);
  5100. },
  5101. rotateY: function (angle) {
  5102. return this.rotateOnAxis(_yAxis, angle);
  5103. },
  5104. rotateZ: function (angle) {
  5105. return this.rotateOnAxis(_zAxis, angle);
  5106. },
  5107. translateOnAxis: function (axis, distance) {
  5108. // translate object by distance along axis in object space
  5109. // axis is assumed to be normalized
  5110. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  5111. this.position.add(_v1$1.multiplyScalar(distance));
  5112. return this;
  5113. },
  5114. translateX: function (distance) {
  5115. return this.translateOnAxis(_xAxis, distance);
  5116. },
  5117. translateY: function (distance) {
  5118. return this.translateOnAxis(_yAxis, distance);
  5119. },
  5120. translateZ: function (distance) {
  5121. return this.translateOnAxis(_zAxis, distance);
  5122. },
  5123. localToWorld: function (vector) {
  5124. return vector.applyMatrix4(this.matrixWorld);
  5125. },
  5126. worldToLocal: function (vector) {
  5127. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  5128. },
  5129. lookAt: function (x, y, z) {
  5130. // This method does not support objects having non-uniformly-scaled parent(s)
  5131. if (x.isVector3) {
  5132. _target.copy(x);
  5133. } else {
  5134. _target.set(x, y, z);
  5135. }
  5136. var parent = this.parent;
  5137. this.updateWorldMatrix(true, false);
  5138. _position.setFromMatrixPosition(this.matrixWorld);
  5139. if (this.isCamera || this.isLight) {
  5140. _m1$1.lookAt(_position, _target, this.up);
  5141. } else {
  5142. _m1$1.lookAt(_target, _position, this.up);
  5143. }
  5144. this.quaternion.setFromRotationMatrix(_m1$1);
  5145. if (parent) {
  5146. _m1$1.extractRotation(parent.matrixWorld);
  5147. _q1.setFromRotationMatrix(_m1$1);
  5148. this.quaternion.premultiply(_q1.inverse());
  5149. }
  5150. },
  5151. add: function (object) {
  5152. if (arguments.length > 1) {
  5153. for (var i = 0; i < arguments.length; i++) {
  5154. this.add(arguments[i]);
  5155. }
  5156. return this;
  5157. }
  5158. if (object === this) {
  5159. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  5160. return this;
  5161. }
  5162. if (object && object.isObject3D) {
  5163. if (object.parent !== null) {
  5164. object.parent.remove(object);
  5165. }
  5166. object.parent = this;
  5167. this.children.push(object);
  5168. object.dispatchEvent(_addedEvent);
  5169. } else {
  5170. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  5171. }
  5172. return this;
  5173. },
  5174. remove: function (object) {
  5175. if (arguments.length > 1) {
  5176. for (var i = 0; i < arguments.length; i++) {
  5177. this.remove(arguments[i]);
  5178. }
  5179. return this;
  5180. }
  5181. var index = this.children.indexOf(object);
  5182. if (index !== -1) {
  5183. object.parent = null;
  5184. this.children.splice(index, 1);
  5185. object.dispatchEvent(_removedEvent);
  5186. }
  5187. return this;
  5188. },
  5189. attach: function (object) {
  5190. // adds object as a child of this, while maintaining the object's world transform
  5191. this.updateWorldMatrix(true, false);
  5192. _m1$1.getInverse(this.matrixWorld);
  5193. if (object.parent !== null) {
  5194. object.parent.updateWorldMatrix(true, false);
  5195. _m1$1.multiply(object.parent.matrixWorld);
  5196. }
  5197. object.applyMatrix(_m1$1);
  5198. object.updateWorldMatrix(false, false);
  5199. this.add(object);
  5200. return this;
  5201. },
  5202. getObjectById: function (id) {
  5203. return this.getObjectByProperty('id', id);
  5204. },
  5205. getObjectByName: function (name) {
  5206. return this.getObjectByProperty('name', name);
  5207. },
  5208. getObjectByProperty: function (name, value) {
  5209. if (this[name] === value) return this;
  5210. for (var i = 0, l = this.children.length; i < l; i++) {
  5211. var child = this.children[i];
  5212. var object = child.getObjectByProperty(name, value);
  5213. if (object !== undefined) {
  5214. return object;
  5215. }
  5216. }
  5217. return undefined;
  5218. },
  5219. getWorldPosition: function (target) {
  5220. if (target === undefined) {
  5221. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  5222. target = new Vector3();
  5223. }
  5224. this.updateMatrixWorld(true);
  5225. return target.setFromMatrixPosition(this.matrixWorld);
  5226. },
  5227. getWorldQuaternion: function (target) {
  5228. if (target === undefined) {
  5229. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  5230. target = new Quaternion();
  5231. }
  5232. this.updateMatrixWorld(true);
  5233. this.matrixWorld.decompose(_position, target, _scale);
  5234. return target;
  5235. },
  5236. getWorldScale: function (target) {
  5237. if (target === undefined) {
  5238. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  5239. target = new Vector3();
  5240. }
  5241. this.updateMatrixWorld(true);
  5242. this.matrixWorld.decompose(_position, _quaternion$2, target);
  5243. return target;
  5244. },
  5245. getWorldDirection: function (target) {
  5246. if (target === undefined) {
  5247. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  5248. target = new Vector3();
  5249. }
  5250. this.updateMatrixWorld(true);
  5251. var e = this.matrixWorld.elements;
  5252. return target.set(e[8], e[9], e[10]).normalize();
  5253. },
  5254. raycast: function () {},
  5255. traverse: function (callback) {
  5256. callback(this);
  5257. var children = this.children;
  5258. for (var i = 0, l = children.length; i < l; i++) {
  5259. children[i].traverse(callback);
  5260. }
  5261. },
  5262. traverseVisible: function (callback) {
  5263. if (this.visible === false) return;
  5264. callback(this);
  5265. var children = this.children;
  5266. for (var i = 0, l = children.length; i < l; i++) {
  5267. children[i].traverseVisible(callback);
  5268. }
  5269. },
  5270. traverseAncestors: function (callback) {
  5271. var parent = this.parent;
  5272. if (parent !== null) {
  5273. callback(parent);
  5274. parent.traverseAncestors(callback);
  5275. }
  5276. },
  5277. updateMatrix: function () {
  5278. this.matrix.compose(this.position, this.quaternion, this.scale);
  5279. this.matrixWorldNeedsUpdate = true;
  5280. },
  5281. updateMatrixWorld: function (force) {
  5282. if (this.matrixAutoUpdate) this.updateMatrix();
  5283. if (this.matrixWorldNeedsUpdate || force) {
  5284. if (this.parent === null) {
  5285. this.matrixWorld.copy(this.matrix);
  5286. } else {
  5287. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5288. }
  5289. this.matrixWorldNeedsUpdate = false;
  5290. force = true;
  5291. } // update children
  5292. var children = this.children;
  5293. for (var i = 0, l = children.length; i < l; i++) {
  5294. children[i].updateMatrixWorld(force);
  5295. }
  5296. },
  5297. updateWorldMatrix: function (updateParents, updateChildren) {
  5298. var parent = this.parent;
  5299. if (updateParents === true && parent !== null) {
  5300. parent.updateWorldMatrix(true, false);
  5301. }
  5302. if (this.matrixAutoUpdate) this.updateMatrix();
  5303. if (this.parent === null) {
  5304. this.matrixWorld.copy(this.matrix);
  5305. } else {
  5306. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5307. } // update children
  5308. if (updateChildren === true) {
  5309. var children = this.children;
  5310. for (var i = 0, l = children.length; i < l; i++) {
  5311. children[i].updateWorldMatrix(false, true);
  5312. }
  5313. }
  5314. },
  5315. toJSON: function (meta) {
  5316. // meta is a string when called from JSON.stringify
  5317. var isRootObject = meta === undefined || typeof meta === 'string';
  5318. var output = {}; // meta is a hash used to collect geometries, materials.
  5319. // not providing it implies that this is the root object
  5320. // being serialized.
  5321. if (isRootObject) {
  5322. // initialize meta obj
  5323. meta = {
  5324. geometries: {},
  5325. materials: {},
  5326. textures: {},
  5327. images: {},
  5328. shapes: {}
  5329. };
  5330. output.metadata = {
  5331. version: 4.5,
  5332. type: 'Object',
  5333. generator: 'Object3D.toJSON'
  5334. };
  5335. } // standard Object3D serialization
  5336. var object = {};
  5337. object.uuid = this.uuid;
  5338. object.type = this.type;
  5339. if (this.name !== '') object.name = this.name;
  5340. if (this.castShadow === true) object.castShadow = true;
  5341. if (this.receiveShadow === true) object.receiveShadow = true;
  5342. if (this.visible === false) object.visible = false;
  5343. if (this.frustumCulled === false) object.frustumCulled = false;
  5344. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5345. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5346. object.layers = this.layers.mask;
  5347. object.matrix = this.matrix.toArray();
  5348. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5349. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  5350. function serialize(library, element) {
  5351. if (library[element.uuid] === undefined) {
  5352. library[element.uuid] = element.toJSON(meta);
  5353. }
  5354. return element.uuid;
  5355. }
  5356. if (this.isMesh || this.isLine || this.isPoints) {
  5357. object.geometry = serialize(meta.geometries, this.geometry);
  5358. var parameters = this.geometry.parameters;
  5359. if (parameters !== undefined && parameters.shapes !== undefined) {
  5360. var shapes = parameters.shapes;
  5361. if (Array.isArray(shapes)) {
  5362. for (var i = 0, l = shapes.length; i < l; i++) {
  5363. var shape = shapes[i];
  5364. serialize(meta.shapes, shape);
  5365. }
  5366. } else {
  5367. serialize(meta.shapes, shapes);
  5368. }
  5369. }
  5370. }
  5371. if (this.material !== undefined) {
  5372. if (Array.isArray(this.material)) {
  5373. var uuids = [];
  5374. for (var i = 0, l = this.material.length; i < l; i++) {
  5375. uuids.push(serialize(meta.materials, this.material[i]));
  5376. }
  5377. object.material = uuids;
  5378. } else {
  5379. object.material = serialize(meta.materials, this.material);
  5380. }
  5381. } //
  5382. if (this.children.length > 0) {
  5383. object.children = [];
  5384. for (var i = 0; i < this.children.length; i++) {
  5385. object.children.push(this.children[i].toJSON(meta).object);
  5386. }
  5387. }
  5388. if (isRootObject) {
  5389. var geometries = extractFromCache(meta.geometries);
  5390. var materials = extractFromCache(meta.materials);
  5391. var textures = extractFromCache(meta.textures);
  5392. var images = extractFromCache(meta.images);
  5393. var shapes = extractFromCache(meta.shapes);
  5394. if (geometries.length > 0) output.geometries = geometries;
  5395. if (materials.length > 0) output.materials = materials;
  5396. if (textures.length > 0) output.textures = textures;
  5397. if (images.length > 0) output.images = images;
  5398. if (shapes.length > 0) output.shapes = shapes;
  5399. }
  5400. output.object = object;
  5401. return output; // extract data from the cache hash
  5402. // remove metadata on each item
  5403. // and return as array
  5404. function extractFromCache(cache) {
  5405. var values = [];
  5406. for (var key in cache) {
  5407. var data = cache[key];
  5408. delete data.metadata;
  5409. values.push(data);
  5410. }
  5411. return values;
  5412. }
  5413. },
  5414. clone: function (recursive) {
  5415. return new this.constructor().copy(this, recursive);
  5416. },
  5417. copy: function (source, recursive) {
  5418. if (recursive === undefined) recursive = true;
  5419. this.name = source.name;
  5420. this.up.copy(source.up);
  5421. this.position.copy(source.position);
  5422. this.quaternion.copy(source.quaternion);
  5423. this.scale.copy(source.scale);
  5424. this.matrix.copy(source.matrix);
  5425. this.matrixWorld.copy(source.matrixWorld);
  5426. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5427. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5428. this.layers.mask = source.layers.mask;
  5429. this.visible = source.visible;
  5430. this.castShadow = source.castShadow;
  5431. this.receiveShadow = source.receiveShadow;
  5432. this.frustumCulled = source.frustumCulled;
  5433. this.renderOrder = source.renderOrder;
  5434. this.userData = JSON.parse(JSON.stringify(source.userData));
  5435. if (recursive === true) {
  5436. for (var i = 0; i < source.children.length; i++) {
  5437. var child = source.children[i];
  5438. this.add(child.clone());
  5439. }
  5440. }
  5441. return this;
  5442. }
  5443. });
  5444. /**
  5445. * @author mrdoob / http://mrdoob.com/
  5446. */
  5447. function Scene() {
  5448. Object3D.call(this);
  5449. this.type = 'Scene';
  5450. this.background = null;
  5451. this.fog = null;
  5452. this.overrideMaterial = null;
  5453. this.autoUpdate = true; // checked by the renderer
  5454. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  5455. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  5456. detail: this
  5457. })); // eslint-disable-line no-undef
  5458. }
  5459. }
  5460. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  5461. constructor: Scene,
  5462. isScene: true,
  5463. copy: function (source, recursive) {
  5464. Object3D.prototype.copy.call(this, source, recursive);
  5465. if (source.background !== null) this.background = source.background.clone();
  5466. if (source.fog !== null) this.fog = source.fog.clone();
  5467. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  5468. this.autoUpdate = source.autoUpdate;
  5469. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5470. return this;
  5471. },
  5472. toJSON: function (meta) {
  5473. var data = Object3D.prototype.toJSON.call(this, meta);
  5474. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  5475. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  5476. return data;
  5477. },
  5478. dispose: function () {
  5479. this.dispatchEvent({
  5480. type: 'dispose'
  5481. });
  5482. }
  5483. });
  5484. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  5485. var _vector$2 = new Vector3(); // triangle centered vertices
  5486. var _v0 = new Vector3();
  5487. var _v1$2 = new Vector3();
  5488. var _v2 = new Vector3(); // triangle edge vectors
  5489. var _f0 = new Vector3();
  5490. var _f1 = new Vector3();
  5491. var _f2 = new Vector3();
  5492. var _center = new Vector3();
  5493. var _extents = new Vector3();
  5494. var _triangleNormal = new Vector3();
  5495. var _testAxis = new Vector3();
  5496. /**
  5497. * @author bhouston / http://clara.io
  5498. * @author WestLangley / http://github.com/WestLangley
  5499. */
  5500. function Box3(min, max) {
  5501. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  5502. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  5503. }
  5504. Object.assign(Box3.prototype, {
  5505. isBox3: true,
  5506. set: function (min, max) {
  5507. this.min.copy(min);
  5508. this.max.copy(max);
  5509. return this;
  5510. },
  5511. setFromArray: function (array) {
  5512. var minX = +Infinity;
  5513. var minY = +Infinity;
  5514. var minZ = +Infinity;
  5515. var maxX = -Infinity;
  5516. var maxY = -Infinity;
  5517. var maxZ = -Infinity;
  5518. for (var i = 0, l = array.length; i < l; i += 3) {
  5519. var x = array[i];
  5520. var y = array[i + 1];
  5521. var z = array[i + 2];
  5522. if (x < minX) minX = x;
  5523. if (y < minY) minY = y;
  5524. if (z < minZ) minZ = z;
  5525. if (x > maxX) maxX = x;
  5526. if (y > maxY) maxY = y;
  5527. if (z > maxZ) maxZ = z;
  5528. }
  5529. this.min.set(minX, minY, minZ);
  5530. this.max.set(maxX, maxY, maxZ);
  5531. return this;
  5532. },
  5533. setFromBufferAttribute: function (attribute) {
  5534. var minX = +Infinity;
  5535. var minY = +Infinity;
  5536. var minZ = +Infinity;
  5537. var maxX = -Infinity;
  5538. var maxY = -Infinity;
  5539. var maxZ = -Infinity;
  5540. for (var i = 0, l = attribute.count; i < l; i++) {
  5541. var x = attribute.getX(i);
  5542. var y = attribute.getY(i);
  5543. var z = attribute.getZ(i);
  5544. if (x < minX) minX = x;
  5545. if (y < minY) minY = y;
  5546. if (z < minZ) minZ = z;
  5547. if (x > maxX) maxX = x;
  5548. if (y > maxY) maxY = y;
  5549. if (z > maxZ) maxZ = z;
  5550. }
  5551. this.min.set(minX, minY, minZ);
  5552. this.max.set(maxX, maxY, maxZ);
  5553. return this;
  5554. },
  5555. setFromPoints: function (points) {
  5556. this.makeEmpty();
  5557. for (var i = 0, il = points.length; i < il; i++) {
  5558. this.expandByPoint(points[i]);
  5559. }
  5560. return this;
  5561. },
  5562. setFromCenterAndSize: function (center, size) {
  5563. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  5564. this.min.copy(center).sub(halfSize);
  5565. this.max.copy(center).add(halfSize);
  5566. return this;
  5567. },
  5568. setFromObject: function (object) {
  5569. this.makeEmpty();
  5570. return this.expandByObject(object);
  5571. },
  5572. clone: function () {
  5573. return new this.constructor().copy(this);
  5574. },
  5575. copy: function (box) {
  5576. this.min.copy(box.min);
  5577. this.max.copy(box.max);
  5578. return this;
  5579. },
  5580. makeEmpty: function () {
  5581. this.min.x = this.min.y = this.min.z = +Infinity;
  5582. this.max.x = this.max.y = this.max.z = -Infinity;
  5583. return this;
  5584. },
  5585. isEmpty: function () {
  5586. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5587. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  5588. },
  5589. getCenter: function (target) {
  5590. if (target === undefined) {
  5591. console.warn('THREE.Box3: .getCenter() target is now required');
  5592. target = new Vector3();
  5593. }
  5594. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  5595. },
  5596. getSize: function (target) {
  5597. if (target === undefined) {
  5598. console.warn('THREE.Box3: .getSize() target is now required');
  5599. target = new Vector3();
  5600. }
  5601. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  5602. },
  5603. expandByPoint: function (point) {
  5604. this.min.min(point);
  5605. this.max.max(point);
  5606. return this;
  5607. },
  5608. expandByVector: function (vector) {
  5609. this.min.sub(vector);
  5610. this.max.add(vector);
  5611. return this;
  5612. },
  5613. expandByScalar: function (scalar) {
  5614. this.min.addScalar(-scalar);
  5615. this.max.addScalar(scalar);
  5616. return this;
  5617. },
  5618. expandByObject: function (object) {
  5619. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  5620. // accounting for both the object's, and children's, world transforms
  5621. object.updateWorldMatrix(false, false);
  5622. var geometry = object.geometry;
  5623. if (geometry !== undefined) {
  5624. if (geometry.isGeometry) {
  5625. var vertices = geometry.vertices;
  5626. for (i = 0, l = vertices.length; i < l; i++) {
  5627. _vector$2.copy(vertices[i]);
  5628. _vector$2.applyMatrix4(object.matrixWorld);
  5629. this.expandByPoint(_vector$2);
  5630. }
  5631. } else if (geometry.isBufferGeometry) {
  5632. var attribute = geometry.attributes.position;
  5633. if (attribute !== undefined) {
  5634. for (i = 0, l = attribute.count; i < l; i++) {
  5635. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  5636. this.expandByPoint(_vector$2);
  5637. }
  5638. }
  5639. }
  5640. } //
  5641. var children = object.children;
  5642. for (i = 0, l = children.length; i < l; i++) {
  5643. this.expandByObject(children[i]);
  5644. }
  5645. return this;
  5646. },
  5647. containsPoint: function (point) {
  5648. 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;
  5649. },
  5650. containsBox: function (box) {
  5651. 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;
  5652. },
  5653. getParameter: function (point, target) {
  5654. // This can potentially have a divide by zero if the box
  5655. // has a size dimension of 0.
  5656. if (target === undefined) {
  5657. console.warn('THREE.Box3: .getParameter() target is now required');
  5658. target = new Vector3();
  5659. }
  5660. 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));
  5661. },
  5662. intersectsBox: function (box) {
  5663. // using 6 splitting planes to rule out intersections.
  5664. 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;
  5665. },
  5666. intersectsSphere: function (sphere) {
  5667. // Find the point on the AABB closest to the sphere center.
  5668. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  5669. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  5670. },
  5671. intersectsPlane: function (plane) {
  5672. // We compute the minimum and maximum dot product values. If those values
  5673. // are on the same side (back or front) of the plane, then there is no intersection.
  5674. var min, max;
  5675. if (plane.normal.x > 0) {
  5676. min = plane.normal.x * this.min.x;
  5677. max = plane.normal.x * this.max.x;
  5678. } else {
  5679. min = plane.normal.x * this.max.x;
  5680. max = plane.normal.x * this.min.x;
  5681. }
  5682. if (plane.normal.y > 0) {
  5683. min += plane.normal.y * this.min.y;
  5684. max += plane.normal.y * this.max.y;
  5685. } else {
  5686. min += plane.normal.y * this.max.y;
  5687. max += plane.normal.y * this.min.y;
  5688. }
  5689. if (plane.normal.z > 0) {
  5690. min += plane.normal.z * this.min.z;
  5691. max += plane.normal.z * this.max.z;
  5692. } else {
  5693. min += plane.normal.z * this.max.z;
  5694. max += plane.normal.z * this.min.z;
  5695. }
  5696. return min <= -plane.constant && max >= -plane.constant;
  5697. },
  5698. intersectsTriangle: function (triangle) {
  5699. if (this.isEmpty()) {
  5700. return false;
  5701. } // compute box center and extents
  5702. this.getCenter(_center);
  5703. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  5704. _v0.subVectors(triangle.a, _center);
  5705. _v1$2.subVectors(triangle.b, _center);
  5706. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  5707. _f0.subVectors(_v1$2, _v0);
  5708. _f1.subVectors(_v2, _v1$2);
  5709. _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
  5710. // 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
  5711. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5712. 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];
  5713. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5714. return false;
  5715. } // test 3 face normals from the aabb
  5716. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  5717. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5718. return false;
  5719. } // finally testing the face normal of the triangle
  5720. // use already existing triangle edge vectors here
  5721. _triangleNormal.crossVectors(_f0, _f1);
  5722. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  5723. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  5724. },
  5725. clampPoint: function (point, target) {
  5726. if (target === undefined) {
  5727. console.warn('THREE.Box3: .clampPoint() target is now required');
  5728. target = new Vector3();
  5729. }
  5730. return target.copy(point).clamp(this.min, this.max);
  5731. },
  5732. distanceToPoint: function (point) {
  5733. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  5734. return clampedPoint.sub(point).length();
  5735. },
  5736. getBoundingSphere: function (target) {
  5737. if (target === undefined) {
  5738. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  5739. }
  5740. this.getCenter(target.center);
  5741. target.radius = this.getSize(_vector$2).length() * 0.5;
  5742. return target;
  5743. },
  5744. intersect: function (box) {
  5745. this.min.max(box.min);
  5746. 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.
  5747. if (this.isEmpty()) this.makeEmpty();
  5748. return this;
  5749. },
  5750. union: function (box) {
  5751. this.min.min(box.min);
  5752. this.max.max(box.max);
  5753. return this;
  5754. },
  5755. applyMatrix4: function (matrix) {
  5756. // transform of empty box is an empty box.
  5757. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5758. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  5759. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  5760. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  5761. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  5762. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  5763. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  5764. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  5765. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  5766. this.setFromPoints(_points);
  5767. return this;
  5768. },
  5769. translate: function (offset) {
  5770. this.min.add(offset);
  5771. this.max.add(offset);
  5772. return this;
  5773. },
  5774. equals: function (box) {
  5775. return box.min.equals(this.min) && box.max.equals(this.max);
  5776. }
  5777. });
  5778. function satForAxes(axes, v0, v1, v2, extents) {
  5779. var i, j;
  5780. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  5781. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  5782. 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
  5783. var p0 = v0.dot(_testAxis);
  5784. var p1 = v1.dot(_testAxis);
  5785. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  5786. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  5787. // points of the projected triangle are outside the projected half-length of the aabb
  5788. // the axis is seperating and we can exit
  5789. return false;
  5790. }
  5791. }
  5792. return true;
  5793. }
  5794. var _box = new Box3();
  5795. /**
  5796. * @author bhouston / http://clara.io
  5797. * @author mrdoob / http://mrdoob.com/
  5798. */
  5799. function Sphere(center, radius) {
  5800. this.center = center !== undefined ? center : new Vector3();
  5801. this.radius = radius !== undefined ? radius : 0;
  5802. }
  5803. Object.assign(Sphere.prototype, {
  5804. set: function (center, radius) {
  5805. this.center.copy(center);
  5806. this.radius = radius;
  5807. return this;
  5808. },
  5809. setFromPoints: function (points, optionalCenter) {
  5810. var center = this.center;
  5811. if (optionalCenter !== undefined) {
  5812. center.copy(optionalCenter);
  5813. } else {
  5814. _box.setFromPoints(points).getCenter(center);
  5815. }
  5816. var maxRadiusSq = 0;
  5817. for (var i = 0, il = points.length; i < il; i++) {
  5818. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  5819. }
  5820. this.radius = Math.sqrt(maxRadiusSq);
  5821. return this;
  5822. },
  5823. clone: function () {
  5824. return new this.constructor().copy(this);
  5825. },
  5826. copy: function (sphere) {
  5827. this.center.copy(sphere.center);
  5828. this.radius = sphere.radius;
  5829. return this;
  5830. },
  5831. empty: function () {
  5832. return this.radius <= 0;
  5833. },
  5834. containsPoint: function (point) {
  5835. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  5836. },
  5837. distanceToPoint: function (point) {
  5838. return point.distanceTo(this.center) - this.radius;
  5839. },
  5840. intersectsSphere: function (sphere) {
  5841. var radiusSum = this.radius + sphere.radius;
  5842. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  5843. },
  5844. intersectsBox: function (box) {
  5845. return box.intersectsSphere(this);
  5846. },
  5847. intersectsPlane: function (plane) {
  5848. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  5849. },
  5850. clampPoint: function (point, target) {
  5851. var deltaLengthSq = this.center.distanceToSquared(point);
  5852. if (target === undefined) {
  5853. console.warn('THREE.Sphere: .clampPoint() target is now required');
  5854. target = new Vector3();
  5855. }
  5856. target.copy(point);
  5857. if (deltaLengthSq > this.radius * this.radius) {
  5858. target.sub(this.center).normalize();
  5859. target.multiplyScalar(this.radius).add(this.center);
  5860. }
  5861. return target;
  5862. },
  5863. getBoundingBox: function (target) {
  5864. if (target === undefined) {
  5865. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  5866. target = new Box3();
  5867. }
  5868. target.set(this.center, this.center);
  5869. target.expandByScalar(this.radius);
  5870. return target;
  5871. },
  5872. applyMatrix4: function (matrix) {
  5873. this.center.applyMatrix4(matrix);
  5874. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5875. return this;
  5876. },
  5877. translate: function (offset) {
  5878. this.center.add(offset);
  5879. return this;
  5880. },
  5881. equals: function (sphere) {
  5882. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  5883. }
  5884. });
  5885. var _vector$3 = new Vector3();
  5886. var _segCenter = new Vector3();
  5887. var _segDir = new Vector3();
  5888. var _diff = new Vector3();
  5889. var _edge1 = new Vector3();
  5890. var _edge2 = new Vector3();
  5891. var _normal = new Vector3();
  5892. /**
  5893. * @author bhouston / http://clara.io
  5894. */
  5895. function Ray(origin, direction) {
  5896. this.origin = origin !== undefined ? origin : new Vector3();
  5897. this.direction = direction !== undefined ? direction : new Vector3();
  5898. }
  5899. Object.assign(Ray.prototype, {
  5900. set: function (origin, direction) {
  5901. this.origin.copy(origin);
  5902. this.direction.copy(direction);
  5903. return this;
  5904. },
  5905. clone: function () {
  5906. return new this.constructor().copy(this);
  5907. },
  5908. copy: function (ray) {
  5909. this.origin.copy(ray.origin);
  5910. this.direction.copy(ray.direction);
  5911. return this;
  5912. },
  5913. at: function (t, target) {
  5914. if (target === undefined) {
  5915. console.warn('THREE.Ray: .at() target is now required');
  5916. target = new Vector3();
  5917. }
  5918. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  5919. },
  5920. lookAt: function (v) {
  5921. this.direction.copy(v).sub(this.origin).normalize();
  5922. return this;
  5923. },
  5924. recast: function (t) {
  5925. this.origin.copy(this.at(t, _vector$3));
  5926. return this;
  5927. },
  5928. closestPointToPoint: function (point, target) {
  5929. if (target === undefined) {
  5930. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  5931. target = new Vector3();
  5932. }
  5933. target.subVectors(point, this.origin);
  5934. var directionDistance = target.dot(this.direction);
  5935. if (directionDistance < 0) {
  5936. return target.copy(this.origin);
  5937. }
  5938. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5939. },
  5940. distanceToPoint: function (point) {
  5941. return Math.sqrt(this.distanceSqToPoint(point));
  5942. },
  5943. distanceSqToPoint: function (point) {
  5944. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  5945. if (directionDistance < 0) {
  5946. return this.origin.distanceToSquared(point);
  5947. }
  5948. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5949. return _vector$3.distanceToSquared(point);
  5950. },
  5951. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  5952. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5953. // It returns the min distance between the ray and the segment
  5954. // defined by v0 and v1
  5955. // It can also set two optional targets :
  5956. // - The closest point on the ray
  5957. // - The closest point on the segment
  5958. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  5959. _segDir.copy(v1).sub(v0).normalize();
  5960. _diff.copy(this.origin).sub(_segCenter);
  5961. var segExtent = v0.distanceTo(v1) * 0.5;
  5962. var a01 = -this.direction.dot(_segDir);
  5963. var b0 = _diff.dot(this.direction);
  5964. var b1 = -_diff.dot(_segDir);
  5965. var c = _diff.lengthSq();
  5966. var det = Math.abs(1 - a01 * a01);
  5967. var s0, s1, sqrDist, extDet;
  5968. if (det > 0) {
  5969. // The ray and segment are not parallel.
  5970. s0 = a01 * b1 - b0;
  5971. s1 = a01 * b0 - b1;
  5972. extDet = segExtent * det;
  5973. if (s0 >= 0) {
  5974. if (s1 >= -extDet) {
  5975. if (s1 <= extDet) {
  5976. // region 0
  5977. // Minimum at interior points of ray and segment.
  5978. var invDet = 1 / det;
  5979. s0 *= invDet;
  5980. s1 *= invDet;
  5981. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  5982. } else {
  5983. // region 1
  5984. s1 = segExtent;
  5985. s0 = Math.max(0, -(a01 * s1 + b0));
  5986. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5987. }
  5988. } else {
  5989. // region 5
  5990. s1 = -segExtent;
  5991. s0 = Math.max(0, -(a01 * s1 + b0));
  5992. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5993. }
  5994. } else {
  5995. if (s1 <= -extDet) {
  5996. // region 4
  5997. s0 = Math.max(0, -(-a01 * segExtent + b0));
  5998. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  5999. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6000. } else if (s1 <= extDet) {
  6001. // region 3
  6002. s0 = 0;
  6003. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  6004. sqrDist = s1 * (s1 + 2 * b1) + c;
  6005. } else {
  6006. // region 2
  6007. s0 = Math.max(0, -(a01 * segExtent + b0));
  6008. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6009. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6010. }
  6011. }
  6012. } else {
  6013. // Ray and segment are parallel.
  6014. s1 = a01 > 0 ? -segExtent : segExtent;
  6015. s0 = Math.max(0, -(a01 * s1 + b0));
  6016. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6017. }
  6018. if (optionalPointOnRay) {
  6019. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  6020. }
  6021. if (optionalPointOnSegment) {
  6022. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  6023. }
  6024. return sqrDist;
  6025. },
  6026. intersectSphere: function (sphere, target) {
  6027. _vector$3.subVectors(sphere.center, this.origin);
  6028. var tca = _vector$3.dot(this.direction);
  6029. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  6030. var radius2 = sphere.radius * sphere.radius;
  6031. if (d2 > radius2) return null;
  6032. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  6033. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  6034. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  6035. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  6036. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6037. // in order to always return an intersect point that is in front of the ray.
  6038. 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
  6039. return this.at(t0, target);
  6040. },
  6041. intersectsSphere: function (sphere) {
  6042. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  6043. },
  6044. distanceToPlane: function (plane) {
  6045. var denominator = plane.normal.dot(this.direction);
  6046. if (denominator === 0) {
  6047. // line is coplanar, return origin
  6048. if (plane.distanceToPoint(this.origin) === 0) {
  6049. return 0;
  6050. } // Null is preferable to undefined since undefined means.... it is undefined
  6051. return null;
  6052. }
  6053. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  6054. return t >= 0 ? t : null;
  6055. },
  6056. intersectPlane: function (plane, target) {
  6057. var t = this.distanceToPlane(plane);
  6058. if (t === null) {
  6059. return null;
  6060. }
  6061. return this.at(t, target);
  6062. },
  6063. intersectsPlane: function (plane) {
  6064. // check if the ray lies on the plane first
  6065. var distToPoint = plane.distanceToPoint(this.origin);
  6066. if (distToPoint === 0) {
  6067. return true;
  6068. }
  6069. var denominator = plane.normal.dot(this.direction);
  6070. if (denominator * distToPoint < 0) {
  6071. return true;
  6072. } // ray origin is behind the plane (and is pointing behind it)
  6073. return false;
  6074. },
  6075. intersectBox: function (box, target) {
  6076. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6077. var invdirx = 1 / this.direction.x,
  6078. invdiry = 1 / this.direction.y,
  6079. invdirz = 1 / this.direction.z;
  6080. var origin = this.origin;
  6081. if (invdirx >= 0) {
  6082. tmin = (box.min.x - origin.x) * invdirx;
  6083. tmax = (box.max.x - origin.x) * invdirx;
  6084. } else {
  6085. tmin = (box.max.x - origin.x) * invdirx;
  6086. tmax = (box.min.x - origin.x) * invdirx;
  6087. }
  6088. if (invdiry >= 0) {
  6089. tymin = (box.min.y - origin.y) * invdiry;
  6090. tymax = (box.max.y - origin.y) * invdiry;
  6091. } else {
  6092. tymin = (box.max.y - origin.y) * invdiry;
  6093. tymax = (box.min.y - origin.y) * invdiry;
  6094. }
  6095. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  6096. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6097. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  6098. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  6099. if (invdirz >= 0) {
  6100. tzmin = (box.min.z - origin.z) * invdirz;
  6101. tzmax = (box.max.z - origin.z) * invdirz;
  6102. } else {
  6103. tzmin = (box.max.z - origin.z) * invdirz;
  6104. tzmax = (box.min.z - origin.z) * invdirz;
  6105. }
  6106. if (tmin > tzmax || tzmin > tmax) return null;
  6107. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  6108. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  6109. if (tmax < 0) return null;
  6110. return this.at(tmin >= 0 ? tmin : tmax, target);
  6111. },
  6112. intersectsBox: function (box) {
  6113. return this.intersectBox(box, _vector$3) !== null;
  6114. },
  6115. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  6116. // Compute the offset origin, edges, and normal.
  6117. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6118. _edge1.subVectors(b, a);
  6119. _edge2.subVectors(c, a);
  6120. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6121. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6122. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6123. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6124. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6125. var DdN = this.direction.dot(_normal);
  6126. var sign;
  6127. if (DdN > 0) {
  6128. if (backfaceCulling) return null;
  6129. sign = 1;
  6130. } else if (DdN < 0) {
  6131. sign = -1;
  6132. DdN = -DdN;
  6133. } else {
  6134. return null;
  6135. }
  6136. _diff.subVectors(this.origin, a);
  6137. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  6138. if (DdQxE2 < 0) {
  6139. return null;
  6140. }
  6141. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  6142. if (DdE1xQ < 0) {
  6143. return null;
  6144. } // b1+b2 > 1, no intersection
  6145. if (DdQxE2 + DdE1xQ > DdN) {
  6146. return null;
  6147. } // Line intersects triangle, check if ray does.
  6148. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  6149. if (QdN < 0) {
  6150. return null;
  6151. } // Ray intersects triangle.
  6152. return this.at(QdN / DdN, target);
  6153. },
  6154. applyMatrix4: function (matrix4) {
  6155. this.origin.applyMatrix4(matrix4);
  6156. this.direction.transformDirection(matrix4);
  6157. return this;
  6158. },
  6159. equals: function (ray) {
  6160. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  6161. }
  6162. });
  6163. /**
  6164. * @author bhouston / http://clara.io
  6165. * @author mrdoob / http://mrdoob.com/
  6166. */
  6167. var _v0$1 = new Vector3();
  6168. var _v1$3 = new Vector3();
  6169. var _v2$1 = new Vector3();
  6170. var _v3 = new Vector3();
  6171. var _vab = new Vector3();
  6172. var _vac = new Vector3();
  6173. var _vbc = new Vector3();
  6174. var _vap = new Vector3();
  6175. var _vbp = new Vector3();
  6176. var _vcp = new Vector3();
  6177. function Triangle(a, b, c) {
  6178. this.a = a !== undefined ? a : new Vector3();
  6179. this.b = b !== undefined ? b : new Vector3();
  6180. this.c = c !== undefined ? c : new Vector3();
  6181. }
  6182. Object.assign(Triangle, {
  6183. getNormal: function (a, b, c, target) {
  6184. if (target === undefined) {
  6185. console.warn('THREE.Triangle: .getNormal() target is now required');
  6186. target = new Vector3();
  6187. }
  6188. target.subVectors(c, b);
  6189. _v0$1.subVectors(a, b);
  6190. target.cross(_v0$1);
  6191. var targetLengthSq = target.lengthSq();
  6192. if (targetLengthSq > 0) {
  6193. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  6194. }
  6195. return target.set(0, 0, 0);
  6196. },
  6197. // static/instance method to calculate barycentric coordinates
  6198. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6199. getBarycoord: function (point, a, b, c, target) {
  6200. _v0$1.subVectors(c, a);
  6201. _v1$3.subVectors(b, a);
  6202. _v2$1.subVectors(point, a);
  6203. var dot00 = _v0$1.dot(_v0$1);
  6204. var dot01 = _v0$1.dot(_v1$3);
  6205. var dot02 = _v0$1.dot(_v2$1);
  6206. var dot11 = _v1$3.dot(_v1$3);
  6207. var dot12 = _v1$3.dot(_v2$1);
  6208. var denom = dot00 * dot11 - dot01 * dot01;
  6209. if (target === undefined) {
  6210. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  6211. target = new Vector3();
  6212. } // collinear or singular triangle
  6213. if (denom === 0) {
  6214. // arbitrary location outside of triangle?
  6215. // not sure if this is the best idea, maybe should be returning undefined
  6216. return target.set(-2, -1, -1);
  6217. }
  6218. var invDenom = 1 / denom;
  6219. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6220. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  6221. return target.set(1 - u - v, v, u);
  6222. },
  6223. containsPoint: function (point, a, b, c) {
  6224. Triangle.getBarycoord(point, a, b, c, _v3);
  6225. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  6226. },
  6227. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  6228. this.getBarycoord(point, p1, p2, p3, _v3);
  6229. target.set(0, 0);
  6230. target.addScaledVector(uv1, _v3.x);
  6231. target.addScaledVector(uv2, _v3.y);
  6232. target.addScaledVector(uv3, _v3.z);
  6233. return target;
  6234. },
  6235. isFrontFacing: function (a, b, c, direction) {
  6236. _v0$1.subVectors(c, b);
  6237. _v1$3.subVectors(a, b); // strictly front facing
  6238. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  6239. }
  6240. });
  6241. Object.assign(Triangle.prototype, {
  6242. set: function (a, b, c) {
  6243. this.a.copy(a);
  6244. this.b.copy(b);
  6245. this.c.copy(c);
  6246. return this;
  6247. },
  6248. setFromPointsAndIndices: function (points, i0, i1, i2) {
  6249. this.a.copy(points[i0]);
  6250. this.b.copy(points[i1]);
  6251. this.c.copy(points[i2]);
  6252. return this;
  6253. },
  6254. clone: function () {
  6255. return new this.constructor().copy(this);
  6256. },
  6257. copy: function (triangle) {
  6258. this.a.copy(triangle.a);
  6259. this.b.copy(triangle.b);
  6260. this.c.copy(triangle.c);
  6261. return this;
  6262. },
  6263. getArea: function () {
  6264. _v0$1.subVectors(this.c, this.b);
  6265. _v1$3.subVectors(this.a, this.b);
  6266. return _v0$1.cross(_v1$3).length() * 0.5;
  6267. },
  6268. getMidpoint: function (target) {
  6269. if (target === undefined) {
  6270. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  6271. target = new Vector3();
  6272. }
  6273. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  6274. },
  6275. getNormal: function (target) {
  6276. return Triangle.getNormal(this.a, this.b, this.c, target);
  6277. },
  6278. getPlane: function (target) {
  6279. if (target === undefined) {
  6280. console.warn('THREE.Triangle: .getPlane() target is now required');
  6281. target = new Vector3();
  6282. }
  6283. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  6284. },
  6285. getBarycoord: function (point, target) {
  6286. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  6287. },
  6288. getUV: function (point, uv1, uv2, uv3, target) {
  6289. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  6290. },
  6291. containsPoint: function (point) {
  6292. return Triangle.containsPoint(point, this.a, this.b, this.c);
  6293. },
  6294. isFrontFacing: function (direction) {
  6295. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  6296. },
  6297. intersectsBox: function (box) {
  6298. return box.intersectsTriangle(this);
  6299. },
  6300. closestPointToPoint: function (p, target) {
  6301. if (target === undefined) {
  6302. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  6303. target = new Vector3();
  6304. }
  6305. var a = this.a,
  6306. b = this.b,
  6307. c = this.c;
  6308. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6309. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6310. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6311. // basically, we're distinguishing which of the voronoi regions of the triangle
  6312. // the point lies in with the minimum amount of redundant computation.
  6313. _vab.subVectors(b, a);
  6314. _vac.subVectors(c, a);
  6315. _vap.subVectors(p, a);
  6316. var d1 = _vab.dot(_vap);
  6317. var d2 = _vac.dot(_vap);
  6318. if (d1 <= 0 && d2 <= 0) {
  6319. // vertex region of A; barycentric coords (1, 0, 0)
  6320. return target.copy(a);
  6321. }
  6322. _vbp.subVectors(p, b);
  6323. var d3 = _vab.dot(_vbp);
  6324. var d4 = _vac.dot(_vbp);
  6325. if (d3 >= 0 && d4 <= d3) {
  6326. // vertex region of B; barycentric coords (0, 1, 0)
  6327. return target.copy(b);
  6328. }
  6329. var vc = d1 * d4 - d3 * d2;
  6330. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  6331. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  6332. return target.copy(a).addScaledVector(_vab, v);
  6333. }
  6334. _vcp.subVectors(p, c);
  6335. var d5 = _vab.dot(_vcp);
  6336. var d6 = _vac.dot(_vcp);
  6337. if (d6 >= 0 && d5 <= d6) {
  6338. // vertex region of C; barycentric coords (0, 0, 1)
  6339. return target.copy(c);
  6340. }
  6341. var vb = d5 * d2 - d1 * d6;
  6342. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  6343. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  6344. return target.copy(a).addScaledVector(_vac, w);
  6345. }
  6346. var va = d3 * d6 - d5 * d4;
  6347. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  6348. _vbc.subVectors(c, b);
  6349. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  6350. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  6351. } // face region
  6352. var denom = 1 / (va + vb + vc); // u = va * denom
  6353. v = vb * denom;
  6354. w = vc * denom;
  6355. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  6356. },
  6357. equals: function (triangle) {
  6358. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  6359. }
  6360. });
  6361. /**
  6362. * @author mrdoob / http://mrdoob.com/
  6363. */
  6364. var _colorKeywords = {
  6365. 'aliceblue': 0xF0F8FF,
  6366. 'antiquewhite': 0xFAEBD7,
  6367. 'aqua': 0x00FFFF,
  6368. 'aquamarine': 0x7FFFD4,
  6369. 'azure': 0xF0FFFF,
  6370. 'beige': 0xF5F5DC,
  6371. 'bisque': 0xFFE4C4,
  6372. 'black': 0x000000,
  6373. 'blanchedalmond': 0xFFEBCD,
  6374. 'blue': 0x0000FF,
  6375. 'blueviolet': 0x8A2BE2,
  6376. 'brown': 0xA52A2A,
  6377. 'burlywood': 0xDEB887,
  6378. 'cadetblue': 0x5F9EA0,
  6379. 'chartreuse': 0x7FFF00,
  6380. 'chocolate': 0xD2691E,
  6381. 'coral': 0xFF7F50,
  6382. 'cornflowerblue': 0x6495ED,
  6383. 'cornsilk': 0xFFF8DC,
  6384. 'crimson': 0xDC143C,
  6385. 'cyan': 0x00FFFF,
  6386. 'darkblue': 0x00008B,
  6387. 'darkcyan': 0x008B8B,
  6388. 'darkgoldenrod': 0xB8860B,
  6389. 'darkgray': 0xA9A9A9,
  6390. 'darkgreen': 0x006400,
  6391. 'darkgrey': 0xA9A9A9,
  6392. 'darkkhaki': 0xBDB76B,
  6393. 'darkmagenta': 0x8B008B,
  6394. 'darkolivegreen': 0x556B2F,
  6395. 'darkorange': 0xFF8C00,
  6396. 'darkorchid': 0x9932CC,
  6397. 'darkred': 0x8B0000,
  6398. 'darksalmon': 0xE9967A,
  6399. 'darkseagreen': 0x8FBC8F,
  6400. 'darkslateblue': 0x483D8B,
  6401. 'darkslategray': 0x2F4F4F,
  6402. 'darkslategrey': 0x2F4F4F,
  6403. 'darkturquoise': 0x00CED1,
  6404. 'darkviolet': 0x9400D3,
  6405. 'deeppink': 0xFF1493,
  6406. 'deepskyblue': 0x00BFFF,
  6407. 'dimgray': 0x696969,
  6408. 'dimgrey': 0x696969,
  6409. 'dodgerblue': 0x1E90FF,
  6410. 'firebrick': 0xB22222,
  6411. 'floralwhite': 0xFFFAF0,
  6412. 'forestgreen': 0x228B22,
  6413. 'fuchsia': 0xFF00FF,
  6414. 'gainsboro': 0xDCDCDC,
  6415. 'ghostwhite': 0xF8F8FF,
  6416. 'gold': 0xFFD700,
  6417. 'goldenrod': 0xDAA520,
  6418. 'gray': 0x808080,
  6419. 'green': 0x008000,
  6420. 'greenyellow': 0xADFF2F,
  6421. 'grey': 0x808080,
  6422. 'honeydew': 0xF0FFF0,
  6423. 'hotpink': 0xFF69B4,
  6424. 'indianred': 0xCD5C5C,
  6425. 'indigo': 0x4B0082,
  6426. 'ivory': 0xFFFFF0,
  6427. 'khaki': 0xF0E68C,
  6428. 'lavender': 0xE6E6FA,
  6429. 'lavenderblush': 0xFFF0F5,
  6430. 'lawngreen': 0x7CFC00,
  6431. 'lemonchiffon': 0xFFFACD,
  6432. 'lightblue': 0xADD8E6,
  6433. 'lightcoral': 0xF08080,
  6434. 'lightcyan': 0xE0FFFF,
  6435. 'lightgoldenrodyellow': 0xFAFAD2,
  6436. 'lightgray': 0xD3D3D3,
  6437. 'lightgreen': 0x90EE90,
  6438. 'lightgrey': 0xD3D3D3,
  6439. 'lightpink': 0xFFB6C1,
  6440. 'lightsalmon': 0xFFA07A,
  6441. 'lightseagreen': 0x20B2AA,
  6442. 'lightskyblue': 0x87CEFA,
  6443. 'lightslategray': 0x778899,
  6444. 'lightslategrey': 0x778899,
  6445. 'lightsteelblue': 0xB0C4DE,
  6446. 'lightyellow': 0xFFFFE0,
  6447. 'lime': 0x00FF00,
  6448. 'limegreen': 0x32CD32,
  6449. 'linen': 0xFAF0E6,
  6450. 'magenta': 0xFF00FF,
  6451. 'maroon': 0x800000,
  6452. 'mediumaquamarine': 0x66CDAA,
  6453. 'mediumblue': 0x0000CD,
  6454. 'mediumorchid': 0xBA55D3,
  6455. 'mediumpurple': 0x9370DB,
  6456. 'mediumseagreen': 0x3CB371,
  6457. 'mediumslateblue': 0x7B68EE,
  6458. 'mediumspringgreen': 0x00FA9A,
  6459. 'mediumturquoise': 0x48D1CC,
  6460. 'mediumvioletred': 0xC71585,
  6461. 'midnightblue': 0x191970,
  6462. 'mintcream': 0xF5FFFA,
  6463. 'mistyrose': 0xFFE4E1,
  6464. 'moccasin': 0xFFE4B5,
  6465. 'navajowhite': 0xFFDEAD,
  6466. 'navy': 0x000080,
  6467. 'oldlace': 0xFDF5E6,
  6468. 'olive': 0x808000,
  6469. 'olivedrab': 0x6B8E23,
  6470. 'orange': 0xFFA500,
  6471. 'orangered': 0xFF4500,
  6472. 'orchid': 0xDA70D6,
  6473. 'palegoldenrod': 0xEEE8AA,
  6474. 'palegreen': 0x98FB98,
  6475. 'paleturquoise': 0xAFEEEE,
  6476. 'palevioletred': 0xDB7093,
  6477. 'papayawhip': 0xFFEFD5,
  6478. 'peachpuff': 0xFFDAB9,
  6479. 'peru': 0xCD853F,
  6480. 'pink': 0xFFC0CB,
  6481. 'plum': 0xDDA0DD,
  6482. 'powderblue': 0xB0E0E6,
  6483. 'purple': 0x800080,
  6484. 'rebeccapurple': 0x663399,
  6485. 'red': 0xFF0000,
  6486. 'rosybrown': 0xBC8F8F,
  6487. 'royalblue': 0x4169E1,
  6488. 'saddlebrown': 0x8B4513,
  6489. 'salmon': 0xFA8072,
  6490. 'sandybrown': 0xF4A460,
  6491. 'seagreen': 0x2E8B57,
  6492. 'seashell': 0xFFF5EE,
  6493. 'sienna': 0xA0522D,
  6494. 'silver': 0xC0C0C0,
  6495. 'skyblue': 0x87CEEB,
  6496. 'slateblue': 0x6A5ACD,
  6497. 'slategray': 0x708090,
  6498. 'slategrey': 0x708090,
  6499. 'snow': 0xFFFAFA,
  6500. 'springgreen': 0x00FF7F,
  6501. 'steelblue': 0x4682B4,
  6502. 'tan': 0xD2B48C,
  6503. 'teal': 0x008080,
  6504. 'thistle': 0xD8BFD8,
  6505. 'tomato': 0xFF6347,
  6506. 'turquoise': 0x40E0D0,
  6507. 'violet': 0xEE82EE,
  6508. 'wheat': 0xF5DEB3,
  6509. 'white': 0xFFFFFF,
  6510. 'whitesmoke': 0xF5F5F5,
  6511. 'yellow': 0xFFFF00,
  6512. 'yellowgreen': 0x9ACD32
  6513. };
  6514. var _hslA = {
  6515. h: 0,
  6516. s: 0,
  6517. l: 0
  6518. };
  6519. var _hslB = {
  6520. h: 0,
  6521. s: 0,
  6522. l: 0
  6523. };
  6524. function Color(r, g, b) {
  6525. if (g === undefined && b === undefined) {
  6526. // r is THREE.Color, hex or string
  6527. return this.set(r);
  6528. }
  6529. return this.setRGB(r, g, b);
  6530. }
  6531. function hue2rgb(p, q, t) {
  6532. if (t < 0) t += 1;
  6533. if (t > 1) t -= 1;
  6534. if (t < 1 / 6) return p + (q - p) * 6 * t;
  6535. if (t < 1 / 2) return q;
  6536. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  6537. return p;
  6538. }
  6539. function SRGBToLinear(c) {
  6540. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  6541. }
  6542. function LinearToSRGB(c) {
  6543. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  6544. }
  6545. Object.assign(Color.prototype, {
  6546. isColor: true,
  6547. r: 1,
  6548. g: 1,
  6549. b: 1,
  6550. set: function (value) {
  6551. if (value && value.isColor) {
  6552. this.copy(value);
  6553. } else if (typeof value === 'number') {
  6554. this.setHex(value);
  6555. } else if (typeof value === 'string') {
  6556. this.setStyle(value);
  6557. }
  6558. return this;
  6559. },
  6560. setScalar: function (scalar) {
  6561. this.r = scalar;
  6562. this.g = scalar;
  6563. this.b = scalar;
  6564. return this;
  6565. },
  6566. setHex: function (hex) {
  6567. hex = Math.floor(hex);
  6568. this.r = (hex >> 16 & 255) / 255;
  6569. this.g = (hex >> 8 & 255) / 255;
  6570. this.b = (hex & 255) / 255;
  6571. return this;
  6572. },
  6573. setRGB: function (r, g, b) {
  6574. this.r = r;
  6575. this.g = g;
  6576. this.b = b;
  6577. return this;
  6578. },
  6579. setHSL: function (h, s, l) {
  6580. // h,s,l ranges are in 0.0 - 1.0
  6581. h = _Math.euclideanModulo(h, 1);
  6582. s = _Math.clamp(s, 0, 1);
  6583. l = _Math.clamp(l, 0, 1);
  6584. if (s === 0) {
  6585. this.r = this.g = this.b = l;
  6586. } else {
  6587. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  6588. var q = 2 * l - p;
  6589. this.r = hue2rgb(q, p, h + 1 / 3);
  6590. this.g = hue2rgb(q, p, h);
  6591. this.b = hue2rgb(q, p, h - 1 / 3);
  6592. }
  6593. return this;
  6594. },
  6595. setStyle: function (style) {
  6596. function handleAlpha(string) {
  6597. if (string === undefined) return;
  6598. if (parseFloat(string) < 1) {
  6599. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  6600. }
  6601. }
  6602. var m;
  6603. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  6604. // rgb / hsl
  6605. var color;
  6606. var name = m[1];
  6607. var components = m[2];
  6608. switch (name) {
  6609. case 'rgb':
  6610. case 'rgba':
  6611. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6612. // rgb(255,0,0) rgba(255,0,0,0.5)
  6613. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  6614. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  6615. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  6616. handleAlpha(color[5]);
  6617. return this;
  6618. }
  6619. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6620. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6621. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  6622. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  6623. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  6624. handleAlpha(color[5]);
  6625. return this;
  6626. }
  6627. break;
  6628. case 'hsl':
  6629. case 'hsla':
  6630. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6631. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6632. var h = parseFloat(color[1]) / 360;
  6633. var s = parseInt(color[2], 10) / 100;
  6634. var l = parseInt(color[3], 10) / 100;
  6635. handleAlpha(color[5]);
  6636. return this.setHSL(h, s, l);
  6637. }
  6638. break;
  6639. }
  6640. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  6641. // hex color
  6642. var hex = m[1];
  6643. var size = hex.length;
  6644. if (size === 3) {
  6645. // #ff0
  6646. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  6647. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  6648. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  6649. return this;
  6650. } else if (size === 6) {
  6651. // #ff0000
  6652. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  6653. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  6654. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  6655. return this;
  6656. }
  6657. }
  6658. if (style && style.length > 0) {
  6659. // color keywords
  6660. var hex = _colorKeywords[style];
  6661. if (hex !== undefined) {
  6662. // red
  6663. this.setHex(hex);
  6664. } else {
  6665. // unknown color
  6666. console.warn('THREE.Color: Unknown color ' + style);
  6667. }
  6668. }
  6669. return this;
  6670. },
  6671. clone: function () {
  6672. return new this.constructor(this.r, this.g, this.b);
  6673. },
  6674. copy: function (color) {
  6675. this.r = color.r;
  6676. this.g = color.g;
  6677. this.b = color.b;
  6678. return this;
  6679. },
  6680. copyGammaToLinear: function (color, gammaFactor) {
  6681. if (gammaFactor === undefined) gammaFactor = 2.0;
  6682. this.r = Math.pow(color.r, gammaFactor);
  6683. this.g = Math.pow(color.g, gammaFactor);
  6684. this.b = Math.pow(color.b, gammaFactor);
  6685. return this;
  6686. },
  6687. copyLinearToGamma: function (color, gammaFactor) {
  6688. if (gammaFactor === undefined) gammaFactor = 2.0;
  6689. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  6690. this.r = Math.pow(color.r, safeInverse);
  6691. this.g = Math.pow(color.g, safeInverse);
  6692. this.b = Math.pow(color.b, safeInverse);
  6693. return this;
  6694. },
  6695. convertGammaToLinear: function (gammaFactor) {
  6696. this.copyGammaToLinear(this, gammaFactor);
  6697. return this;
  6698. },
  6699. convertLinearToGamma: function (gammaFactor) {
  6700. this.copyLinearToGamma(this, gammaFactor);
  6701. return this;
  6702. },
  6703. copySRGBToLinear: function (color) {
  6704. this.r = SRGBToLinear(color.r);
  6705. this.g = SRGBToLinear(color.g);
  6706. this.b = SRGBToLinear(color.b);
  6707. return this;
  6708. },
  6709. copyLinearToSRGB: function (color) {
  6710. this.r = LinearToSRGB(color.r);
  6711. this.g = LinearToSRGB(color.g);
  6712. this.b = LinearToSRGB(color.b);
  6713. return this;
  6714. },
  6715. convertSRGBToLinear: function () {
  6716. this.copySRGBToLinear(this);
  6717. return this;
  6718. },
  6719. convertLinearToSRGB: function () {
  6720. this.copyLinearToSRGB(this);
  6721. return this;
  6722. },
  6723. getHex: function () {
  6724. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  6725. },
  6726. getHexString: function () {
  6727. return ('000000' + this.getHex().toString(16)).slice(-6);
  6728. },
  6729. getHSL: function (target) {
  6730. // h,s,l ranges are in 0.0 - 1.0
  6731. if (target === undefined) {
  6732. console.warn('THREE.Color: .getHSL() target is now required');
  6733. target = {
  6734. h: 0,
  6735. s: 0,
  6736. l: 0
  6737. };
  6738. }
  6739. var r = this.r,
  6740. g = this.g,
  6741. b = this.b;
  6742. var max = Math.max(r, g, b);
  6743. var min = Math.min(r, g, b);
  6744. var hue, saturation;
  6745. var lightness = (min + max) / 2.0;
  6746. if (min === max) {
  6747. hue = 0;
  6748. saturation = 0;
  6749. } else {
  6750. var delta = max - min;
  6751. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  6752. switch (max) {
  6753. case r:
  6754. hue = (g - b) / delta + (g < b ? 6 : 0);
  6755. break;
  6756. case g:
  6757. hue = (b - r) / delta + 2;
  6758. break;
  6759. case b:
  6760. hue = (r - g) / delta + 4;
  6761. break;
  6762. }
  6763. hue /= 6;
  6764. }
  6765. target.h = hue;
  6766. target.s = saturation;
  6767. target.l = lightness;
  6768. return target;
  6769. },
  6770. getStyle: function () {
  6771. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  6772. },
  6773. offsetHSL: function (h, s, l) {
  6774. this.getHSL(_hslA);
  6775. _hslA.h += h;
  6776. _hslA.s += s;
  6777. _hslA.l += l;
  6778. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  6779. return this;
  6780. },
  6781. add: function (color) {
  6782. this.r += color.r;
  6783. this.g += color.g;
  6784. this.b += color.b;
  6785. return this;
  6786. },
  6787. addColors: function (color1, color2) {
  6788. this.r = color1.r + color2.r;
  6789. this.g = color1.g + color2.g;
  6790. this.b = color1.b + color2.b;
  6791. return this;
  6792. },
  6793. addScalar: function (s) {
  6794. this.r += s;
  6795. this.g += s;
  6796. this.b += s;
  6797. return this;
  6798. },
  6799. sub: function (color) {
  6800. this.r = Math.max(0, this.r - color.r);
  6801. this.g = Math.max(0, this.g - color.g);
  6802. this.b = Math.max(0, this.b - color.b);
  6803. return this;
  6804. },
  6805. multiply: function (color) {
  6806. this.r *= color.r;
  6807. this.g *= color.g;
  6808. this.b *= color.b;
  6809. return this;
  6810. },
  6811. multiplyScalar: function (s) {
  6812. this.r *= s;
  6813. this.g *= s;
  6814. this.b *= s;
  6815. return this;
  6816. },
  6817. lerp: function (color, alpha) {
  6818. this.r += (color.r - this.r) * alpha;
  6819. this.g += (color.g - this.g) * alpha;
  6820. this.b += (color.b - this.b) * alpha;
  6821. return this;
  6822. },
  6823. lerpHSL: function (color, alpha) {
  6824. this.getHSL(_hslA);
  6825. color.getHSL(_hslB);
  6826. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  6827. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  6828. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  6829. this.setHSL(h, s, l);
  6830. return this;
  6831. },
  6832. equals: function (c) {
  6833. return c.r === this.r && c.g === this.g && c.b === this.b;
  6834. },
  6835. fromArray: function (array, offset) {
  6836. if (offset === undefined) offset = 0;
  6837. this.r = array[offset];
  6838. this.g = array[offset + 1];
  6839. this.b = array[offset + 2];
  6840. return this;
  6841. },
  6842. toArray: function (array, offset) {
  6843. if (array === undefined) array = [];
  6844. if (offset === undefined) offset = 0;
  6845. array[offset] = this.r;
  6846. array[offset + 1] = this.g;
  6847. array[offset + 2] = this.b;
  6848. return array;
  6849. },
  6850. toJSON: function () {
  6851. return this.getHex();
  6852. }
  6853. });
  6854. /**
  6855. * @author mrdoob / http://mrdoob.com/
  6856. * @author alteredq / http://alteredqualia.com/
  6857. */
  6858. function Face3(a, b, c, normal, color, materialIndex) {
  6859. this.a = a;
  6860. this.b = b;
  6861. this.c = c;
  6862. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  6863. this.vertexNormals = Array.isArray(normal) ? normal : [];
  6864. this.color = color && color.isColor ? color : new Color();
  6865. this.vertexColors = Array.isArray(color) ? color : [];
  6866. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6867. }
  6868. Object.assign(Face3.prototype, {
  6869. clone: function () {
  6870. return new this.constructor().copy(this);
  6871. },
  6872. copy: function (source) {
  6873. this.a = source.a;
  6874. this.b = source.b;
  6875. this.c = source.c;
  6876. this.normal.copy(source.normal);
  6877. this.color.copy(source.color);
  6878. this.materialIndex = source.materialIndex;
  6879. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  6880. this.vertexNormals[i] = source.vertexNormals[i].clone();
  6881. }
  6882. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  6883. this.vertexColors[i] = source.vertexColors[i].clone();
  6884. }
  6885. return this;
  6886. }
  6887. });
  6888. /**
  6889. * @author mrdoob / http://mrdoob.com/
  6890. * @author alteredq / http://alteredqualia.com/
  6891. */
  6892. var materialId = 0;
  6893. function Material() {
  6894. Object.defineProperty(this, 'id', {
  6895. value: materialId++
  6896. });
  6897. this.uuid = _Math.generateUUID();
  6898. this.name = '';
  6899. this.type = 'Material';
  6900. this.fog = true;
  6901. this.blending = NormalBlending;
  6902. this.side = FrontSide;
  6903. this.flatShading = false;
  6904. this.vertexTangents = false;
  6905. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6906. this.opacity = 1;
  6907. this.transparent = false;
  6908. this.blendSrc = SrcAlphaFactor;
  6909. this.blendDst = OneMinusSrcAlphaFactor;
  6910. this.blendEquation = AddEquation;
  6911. this.blendSrcAlpha = null;
  6912. this.blendDstAlpha = null;
  6913. this.blendEquationAlpha = null;
  6914. this.depthFunc = LessEqualDepth;
  6915. this.depthTest = true;
  6916. this.depthWrite = true;
  6917. this.stencilWriteMask = 0xff;
  6918. this.stencilFunc = AlwaysStencilFunc;
  6919. this.stencilRef = 0;
  6920. this.stencilFuncMask = 0xff;
  6921. this.stencilFail = KeepStencilOp;
  6922. this.stencilZFail = KeepStencilOp;
  6923. this.stencilZPass = KeepStencilOp;
  6924. this.stencilWrite = false;
  6925. this.clippingPlanes = null;
  6926. this.clipIntersection = false;
  6927. this.clipShadows = false;
  6928. this.shadowSide = null;
  6929. this.colorWrite = true;
  6930. this.precision = null; // override the renderer's default precision for this material
  6931. this.polygonOffset = false;
  6932. this.polygonOffsetFactor = 0;
  6933. this.polygonOffsetUnits = 0;
  6934. this.dithering = false;
  6935. this.alphaTest = 0;
  6936. this.premultipliedAlpha = false;
  6937. this.visible = true;
  6938. this.toneMapped = true;
  6939. this.userData = {};
  6940. this.needsUpdate = true;
  6941. }
  6942. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6943. constructor: Material,
  6944. isMaterial: true,
  6945. onBeforeCompile: function () {},
  6946. setValues: function (values) {
  6947. if (values === undefined) return;
  6948. for (var key in values) {
  6949. var newValue = values[key];
  6950. if (newValue === undefined) {
  6951. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6952. continue;
  6953. } // for backward compatability if shading is set in the constructor
  6954. if (key === 'shading') {
  6955. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6956. this.flatShading = newValue === FlatShading ? true : false;
  6957. continue;
  6958. }
  6959. var currentValue = this[key];
  6960. if (currentValue === undefined) {
  6961. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6962. continue;
  6963. }
  6964. if (currentValue && currentValue.isColor) {
  6965. currentValue.set(newValue);
  6966. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6967. currentValue.copy(newValue);
  6968. } else {
  6969. this[key] = newValue;
  6970. }
  6971. }
  6972. },
  6973. toJSON: function (meta) {
  6974. var isRoot = meta === undefined || typeof meta === 'string';
  6975. if (isRoot) {
  6976. meta = {
  6977. textures: {},
  6978. images: {}
  6979. };
  6980. }
  6981. var data = {
  6982. metadata: {
  6983. version: 4.5,
  6984. type: 'Material',
  6985. generator: 'Material.toJSON'
  6986. }
  6987. }; // standard Material serialization
  6988. data.uuid = this.uuid;
  6989. data.type = this.type;
  6990. if (this.name !== '') data.name = this.name;
  6991. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6992. if (this.roughness !== undefined) data.roughness = this.roughness;
  6993. if (this.metalness !== undefined) data.metalness = this.metalness;
  6994. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6995. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6996. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6997. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6998. if (this.shininess !== undefined) data.shininess = this.shininess;
  6999. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  7000. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  7001. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  7002. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  7003. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7004. }
  7005. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  7006. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  7007. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  7008. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  7009. if (this.aoMap && this.aoMap.isTexture) {
  7010. data.aoMap = this.aoMap.toJSON(meta).uuid;
  7011. data.aoMapIntensity = this.aoMapIntensity;
  7012. }
  7013. if (this.bumpMap && this.bumpMap.isTexture) {
  7014. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  7015. data.bumpScale = this.bumpScale;
  7016. }
  7017. if (this.normalMap && this.normalMap.isTexture) {
  7018. data.normalMap = this.normalMap.toJSON(meta).uuid;
  7019. data.normalMapType = this.normalMapType;
  7020. data.normalScale = this.normalScale.toArray();
  7021. }
  7022. if (this.displacementMap && this.displacementMap.isTexture) {
  7023. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  7024. data.displacementScale = this.displacementScale;
  7025. data.displacementBias = this.displacementBias;
  7026. }
  7027. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  7028. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  7029. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  7030. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  7031. if (this.envMap && this.envMap.isTexture) {
  7032. data.envMap = this.envMap.toJSON(meta).uuid;
  7033. data.reflectivity = this.reflectivity; // Scale behind envMap
  7034. data.refractionRatio = this.refractionRatio;
  7035. if (this.combine !== undefined) data.combine = this.combine;
  7036. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  7037. }
  7038. if (this.gradientMap && this.gradientMap.isTexture) {
  7039. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  7040. }
  7041. if (this.size !== undefined) data.size = this.size;
  7042. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  7043. if (this.blending !== NormalBlending) data.blending = this.blending;
  7044. if (this.flatShading === true) data.flatShading = this.flatShading;
  7045. if (this.side !== FrontSide) data.side = this.side;
  7046. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  7047. if (this.opacity < 1) data.opacity = this.opacity;
  7048. if (this.transparent === true) data.transparent = this.transparent;
  7049. data.depthFunc = this.depthFunc;
  7050. data.depthTest = this.depthTest;
  7051. data.depthWrite = this.depthWrite;
  7052. data.stencilWrite = this.stencilWrite;
  7053. data.stencilWriteMask = this.stencilWriteMask;
  7054. data.stencilFunc = this.stencilFunc;
  7055. data.stencilRef = this.stencilRef;
  7056. data.stencilFuncMask = this.stencilFuncMask;
  7057. data.stencilFail = this.stencilFail;
  7058. data.stencilZFail = this.stencilZFail;
  7059. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  7060. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  7061. if (this.polygonOffset === true) data.polygonOffset = true;
  7062. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7063. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7064. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  7065. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  7066. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  7067. if (this.scale !== undefined) data.scale = this.scale;
  7068. if (this.dithering === true) data.dithering = true;
  7069. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  7070. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  7071. if (this.wireframe === true) data.wireframe = this.wireframe;
  7072. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  7073. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  7074. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  7075. if (this.morphTargets === true) data.morphTargets = true;
  7076. if (this.morphNormals === true) data.morphNormals = true;
  7077. if (this.skinning === true) data.skinning = true;
  7078. if (this.visible === false) data.visible = false;
  7079. if (this.toneMapped === false) data.toneMapped = false;
  7080. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  7081. function extractFromCache(cache) {
  7082. var values = [];
  7083. for (var key in cache) {
  7084. var data = cache[key];
  7085. delete data.metadata;
  7086. values.push(data);
  7087. }
  7088. return values;
  7089. }
  7090. if (isRoot) {
  7091. var textures = extractFromCache(meta.textures);
  7092. var images = extractFromCache(meta.images);
  7093. if (textures.length > 0) data.textures = textures;
  7094. if (images.length > 0) data.images = images;
  7095. }
  7096. return data;
  7097. },
  7098. clone: function () {
  7099. return new this.constructor().copy(this);
  7100. },
  7101. copy: function (source) {
  7102. this.name = source.name;
  7103. this.fog = source.fog;
  7104. this.blending = source.blending;
  7105. this.side = source.side;
  7106. this.flatShading = source.flatShading;
  7107. this.vertexColors = source.vertexColors;
  7108. this.opacity = source.opacity;
  7109. this.transparent = source.transparent;
  7110. this.blendSrc = source.blendSrc;
  7111. this.blendDst = source.blendDst;
  7112. this.blendEquation = source.blendEquation;
  7113. this.blendSrcAlpha = source.blendSrcAlpha;
  7114. this.blendDstAlpha = source.blendDstAlpha;
  7115. this.blendEquationAlpha = source.blendEquationAlpha;
  7116. this.depthFunc = source.depthFunc;
  7117. this.depthTest = source.depthTest;
  7118. this.depthWrite = source.depthWrite;
  7119. this.stencilWrite = source.stencilWrite;
  7120. this.stencilWriteMask = source.stencilWriteMask;
  7121. this.stencilFunc = source.stencilFunc;
  7122. this.stencilRef = source.stencilRef;
  7123. this.stencilFuncMask = source.stencilFuncMask;
  7124. this.stencilFail = source.stencilFail;
  7125. this.stencilZFail = source.stencilZFail;
  7126. this.stencilZPass = source.stencilZPass;
  7127. this.colorWrite = source.colorWrite;
  7128. this.precision = source.precision;
  7129. this.polygonOffset = source.polygonOffset;
  7130. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7131. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7132. this.dithering = source.dithering;
  7133. this.alphaTest = source.alphaTest;
  7134. this.premultipliedAlpha = source.premultipliedAlpha;
  7135. this.visible = source.visible;
  7136. this.toneMapped = source.toneMapped;
  7137. this.userData = JSON.parse(JSON.stringify(source.userData));
  7138. this.clipShadows = source.clipShadows;
  7139. this.clipIntersection = source.clipIntersection;
  7140. var srcPlanes = source.clippingPlanes,
  7141. dstPlanes = null;
  7142. if (srcPlanes !== null) {
  7143. var n = srcPlanes.length;
  7144. dstPlanes = new Array(n);
  7145. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  7146. }
  7147. this.clippingPlanes = dstPlanes;
  7148. this.shadowSide = source.shadowSide;
  7149. return this;
  7150. },
  7151. dispose: function () {
  7152. this.dispatchEvent({
  7153. type: 'dispose'
  7154. });
  7155. }
  7156. });
  7157. /**
  7158. * @author mrdoob / http://mrdoob.com/
  7159. * @author alteredq / http://alteredqualia.com/
  7160. *
  7161. * parameters = {
  7162. * color: <hex>,
  7163. * opacity: <float>,
  7164. * map: new THREE.Texture( <Image> ),
  7165. *
  7166. * lightMap: new THREE.Texture( <Image> ),
  7167. * lightMapIntensity: <float>
  7168. *
  7169. * aoMap: new THREE.Texture( <Image> ),
  7170. * aoMapIntensity: <float>
  7171. *
  7172. * specularMap: new THREE.Texture( <Image> ),
  7173. *
  7174. * alphaMap: new THREE.Texture( <Image> ),
  7175. *
  7176. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  7177. * combine: THREE.Multiply,
  7178. * reflectivity: <float>,
  7179. * refractionRatio: <float>,
  7180. *
  7181. * depthTest: <bool>,
  7182. * depthWrite: <bool>,
  7183. *
  7184. * wireframe: <boolean>,
  7185. * wireframeLinewidth: <float>,
  7186. *
  7187. * skinning: <bool>,
  7188. * morphTargets: <bool>
  7189. * }
  7190. */
  7191. function MeshBasicMaterial(parameters) {
  7192. Material.call(this);
  7193. this.type = 'MeshBasicMaterial';
  7194. this.color = new Color(0xffffff); // emissive
  7195. this.map = null;
  7196. this.lightMap = null;
  7197. this.lightMapIntensity = 1.0;
  7198. this.aoMap = null;
  7199. this.aoMapIntensity = 1.0;
  7200. this.specularMap = null;
  7201. this.alphaMap = null;
  7202. this.envMap = null;
  7203. this.combine = MultiplyOperation;
  7204. this.reflectivity = 1;
  7205. this.refractionRatio = 0.98;
  7206. this.wireframe = false;
  7207. this.wireframeLinewidth = 1;
  7208. this.wireframeLinecap = 'round';
  7209. this.wireframeLinejoin = 'round';
  7210. this.skinning = false;
  7211. this.morphTargets = false;
  7212. this.setValues(parameters);
  7213. }
  7214. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  7215. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7216. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7217. MeshBasicMaterial.prototype.copy = function (source) {
  7218. Material.prototype.copy.call(this, source);
  7219. this.color.copy(source.color);
  7220. this.map = source.map;
  7221. this.lightMap = source.lightMap;
  7222. this.lightMapIntensity = source.lightMapIntensity;
  7223. this.aoMap = source.aoMap;
  7224. this.aoMapIntensity = source.aoMapIntensity;
  7225. this.specularMap = source.specularMap;
  7226. this.alphaMap = source.alphaMap;
  7227. this.envMap = source.envMap;
  7228. this.combine = source.combine;
  7229. this.reflectivity = source.reflectivity;
  7230. this.refractionRatio = source.refractionRatio;
  7231. this.wireframe = source.wireframe;
  7232. this.wireframeLinewidth = source.wireframeLinewidth;
  7233. this.wireframeLinecap = source.wireframeLinecap;
  7234. this.wireframeLinejoin = source.wireframeLinejoin;
  7235. this.skinning = source.skinning;
  7236. this.morphTargets = source.morphTargets;
  7237. return this;
  7238. };
  7239. /**
  7240. * @author mrdoob / http://mrdoob.com/
  7241. */
  7242. function BufferAttribute(array, itemSize, normalized) {
  7243. if (Array.isArray(array)) {
  7244. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  7245. }
  7246. this.name = '';
  7247. this.array = array;
  7248. this.itemSize = itemSize;
  7249. this.count = array !== undefined ? array.length / itemSize : 0;
  7250. this.normalized = normalized === true;
  7251. this.dynamic = false;
  7252. this.updateRange = {
  7253. offset: 0,
  7254. count: -1
  7255. };
  7256. this.version = 0;
  7257. }
  7258. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  7259. set: function (value) {
  7260. if (value === true) this.version++;
  7261. }
  7262. });
  7263. Object.assign(BufferAttribute.prototype, {
  7264. isBufferAttribute: true,
  7265. onUploadCallback: function () {},
  7266. setDynamic: function (value) {
  7267. this.dynamic = value;
  7268. return this;
  7269. },
  7270. copy: function (source) {
  7271. this.name = source.name;
  7272. this.array = new source.array.constructor(source.array);
  7273. this.itemSize = source.itemSize;
  7274. this.count = source.count;
  7275. this.normalized = source.normalized;
  7276. this.dynamic = source.dynamic;
  7277. return this;
  7278. },
  7279. copyAt: function (index1, attribute, index2) {
  7280. index1 *= this.itemSize;
  7281. index2 *= attribute.itemSize;
  7282. for (var i = 0, l = this.itemSize; i < l; i++) {
  7283. this.array[index1 + i] = attribute.array[index2 + i];
  7284. }
  7285. return this;
  7286. },
  7287. copyArray: function (array) {
  7288. this.array.set(array);
  7289. return this;
  7290. },
  7291. copyColorsArray: function (colors) {
  7292. var array = this.array,
  7293. offset = 0;
  7294. for (var i = 0, l = colors.length; i < l; i++) {
  7295. var color = colors[i];
  7296. if (color === undefined) {
  7297. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  7298. color = new Color();
  7299. }
  7300. array[offset++] = color.r;
  7301. array[offset++] = color.g;
  7302. array[offset++] = color.b;
  7303. }
  7304. return this;
  7305. },
  7306. copyVector2sArray: function (vectors) {
  7307. var array = this.array,
  7308. offset = 0;
  7309. for (var i = 0, l = vectors.length; i < l; i++) {
  7310. var vector = vectors[i];
  7311. if (vector === undefined) {
  7312. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  7313. vector = new Vector2();
  7314. }
  7315. array[offset++] = vector.x;
  7316. array[offset++] = vector.y;
  7317. }
  7318. return this;
  7319. },
  7320. copyVector3sArray: function (vectors) {
  7321. var array = this.array,
  7322. offset = 0;
  7323. for (var i = 0, l = vectors.length; i < l; i++) {
  7324. var vector = vectors[i];
  7325. if (vector === undefined) {
  7326. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  7327. vector = new Vector3();
  7328. }
  7329. array[offset++] = vector.x;
  7330. array[offset++] = vector.y;
  7331. array[offset++] = vector.z;
  7332. }
  7333. return this;
  7334. },
  7335. copyVector4sArray: function (vectors) {
  7336. var array = this.array,
  7337. offset = 0;
  7338. for (var i = 0, l = vectors.length; i < l; i++) {
  7339. var vector = vectors[i];
  7340. if (vector === undefined) {
  7341. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  7342. vector = new Vector4();
  7343. }
  7344. array[offset++] = vector.x;
  7345. array[offset++] = vector.y;
  7346. array[offset++] = vector.z;
  7347. array[offset++] = vector.w;
  7348. }
  7349. return this;
  7350. },
  7351. set: function (value, offset) {
  7352. if (offset === undefined) offset = 0;
  7353. this.array.set(value, offset);
  7354. return this;
  7355. },
  7356. getX: function (index) {
  7357. return this.array[index * this.itemSize];
  7358. },
  7359. setX: function (index, x) {
  7360. this.array[index * this.itemSize] = x;
  7361. return this;
  7362. },
  7363. getY: function (index) {
  7364. return this.array[index * this.itemSize + 1];
  7365. },
  7366. setY: function (index, y) {
  7367. this.array[index * this.itemSize + 1] = y;
  7368. return this;
  7369. },
  7370. getZ: function (index) {
  7371. return this.array[index * this.itemSize + 2];
  7372. },
  7373. setZ: function (index, z) {
  7374. this.array[index * this.itemSize + 2] = z;
  7375. return this;
  7376. },
  7377. getW: function (index) {
  7378. return this.array[index * this.itemSize + 3];
  7379. },
  7380. setW: function (index, w) {
  7381. this.array[index * this.itemSize + 3] = w;
  7382. return this;
  7383. },
  7384. setXY: function (index, x, y) {
  7385. index *= this.itemSize;
  7386. this.array[index + 0] = x;
  7387. this.array[index + 1] = y;
  7388. return this;
  7389. },
  7390. setXYZ: function (index, x, y, z) {
  7391. index *= this.itemSize;
  7392. this.array[index + 0] = x;
  7393. this.array[index + 1] = y;
  7394. this.array[index + 2] = z;
  7395. return this;
  7396. },
  7397. setXYZW: function (index, x, y, z, w) {
  7398. index *= this.itemSize;
  7399. this.array[index + 0] = x;
  7400. this.array[index + 1] = y;
  7401. this.array[index + 2] = z;
  7402. this.array[index + 3] = w;
  7403. return this;
  7404. },
  7405. onUpload: function (callback) {
  7406. this.onUploadCallback = callback;
  7407. return this;
  7408. },
  7409. clone: function () {
  7410. return new this.constructor(this.array, this.itemSize).copy(this);
  7411. },
  7412. toJSON: function () {
  7413. return {
  7414. itemSize: this.itemSize,
  7415. type: this.array.constructor.name,
  7416. array: Array.prototype.slice.call(this.array),
  7417. normalized: this.normalized
  7418. };
  7419. }
  7420. }); //
  7421. function Int8BufferAttribute(array, itemSize, normalized) {
  7422. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  7423. }
  7424. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7425. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7426. function Uint8BufferAttribute(array, itemSize, normalized) {
  7427. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  7428. }
  7429. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7430. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7431. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  7432. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  7433. }
  7434. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7435. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7436. function Int16BufferAttribute(array, itemSize, normalized) {
  7437. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  7438. }
  7439. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7440. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7441. function Uint16BufferAttribute(array, itemSize, normalized) {
  7442. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  7443. }
  7444. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7445. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7446. function Int32BufferAttribute(array, itemSize, normalized) {
  7447. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  7448. }
  7449. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7450. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7451. function Uint32BufferAttribute(array, itemSize, normalized) {
  7452. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  7453. }
  7454. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7455. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7456. function Float32BufferAttribute(array, itemSize, normalized) {
  7457. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  7458. }
  7459. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7460. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7461. function Float64BufferAttribute(array, itemSize, normalized) {
  7462. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  7463. }
  7464. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7465. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7466. /**
  7467. * @author mrdoob / http://mrdoob.com/
  7468. */
  7469. function DirectGeometry() {
  7470. this.vertices = [];
  7471. this.normals = [];
  7472. this.colors = [];
  7473. this.uvs = [];
  7474. this.uvs2 = [];
  7475. this.groups = [];
  7476. this.morphTargets = {};
  7477. this.skinWeights = [];
  7478. this.skinIndices = []; // this.lineDistances = [];
  7479. this.boundingBox = null;
  7480. this.boundingSphere = null; // update flags
  7481. this.verticesNeedUpdate = false;
  7482. this.normalsNeedUpdate = false;
  7483. this.colorsNeedUpdate = false;
  7484. this.uvsNeedUpdate = false;
  7485. this.groupsNeedUpdate = false;
  7486. }
  7487. Object.assign(DirectGeometry.prototype, {
  7488. computeGroups: function (geometry) {
  7489. var group;
  7490. var groups = [];
  7491. var materialIndex = undefined;
  7492. var faces = geometry.faces;
  7493. for (var i = 0; i < faces.length; i++) {
  7494. var face = faces[i]; // materials
  7495. if (face.materialIndex !== materialIndex) {
  7496. materialIndex = face.materialIndex;
  7497. if (group !== undefined) {
  7498. group.count = i * 3 - group.start;
  7499. groups.push(group);
  7500. }
  7501. group = {
  7502. start: i * 3,
  7503. materialIndex: materialIndex
  7504. };
  7505. }
  7506. }
  7507. if (group !== undefined) {
  7508. group.count = i * 3 - group.start;
  7509. groups.push(group);
  7510. }
  7511. this.groups = groups;
  7512. },
  7513. fromGeometry: function (geometry) {
  7514. var faces = geometry.faces;
  7515. var vertices = geometry.vertices;
  7516. var faceVertexUvs = geometry.faceVertexUvs;
  7517. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  7518. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  7519. var morphTargets = geometry.morphTargets;
  7520. var morphTargetsLength = morphTargets.length;
  7521. var morphTargetsPosition;
  7522. if (morphTargetsLength > 0) {
  7523. morphTargetsPosition = [];
  7524. for (var i = 0; i < morphTargetsLength; i++) {
  7525. morphTargetsPosition[i] = {
  7526. name: morphTargets[i].name,
  7527. data: []
  7528. };
  7529. }
  7530. this.morphTargets.position = morphTargetsPosition;
  7531. }
  7532. var morphNormals = geometry.morphNormals;
  7533. var morphNormalsLength = morphNormals.length;
  7534. var morphTargetsNormal;
  7535. if (morphNormalsLength > 0) {
  7536. morphTargetsNormal = [];
  7537. for (var i = 0; i < morphNormalsLength; i++) {
  7538. morphTargetsNormal[i] = {
  7539. name: morphNormals[i].name,
  7540. data: []
  7541. };
  7542. }
  7543. this.morphTargets.normal = morphTargetsNormal;
  7544. } // skins
  7545. var skinIndices = geometry.skinIndices;
  7546. var skinWeights = geometry.skinWeights;
  7547. var hasSkinIndices = skinIndices.length === vertices.length;
  7548. var hasSkinWeights = skinWeights.length === vertices.length; //
  7549. if (vertices.length > 0 && faces.length === 0) {
  7550. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  7551. }
  7552. for (var i = 0; i < faces.length; i++) {
  7553. var face = faces[i];
  7554. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  7555. var vertexNormals = face.vertexNormals;
  7556. if (vertexNormals.length === 3) {
  7557. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  7558. } else {
  7559. var normal = face.normal;
  7560. this.normals.push(normal, normal, normal);
  7561. }
  7562. var vertexColors = face.vertexColors;
  7563. if (vertexColors.length === 3) {
  7564. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  7565. } else {
  7566. var color = face.color;
  7567. this.colors.push(color, color, color);
  7568. }
  7569. if (hasFaceVertexUv === true) {
  7570. var vertexUvs = faceVertexUvs[0][i];
  7571. if (vertexUvs !== undefined) {
  7572. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7573. } else {
  7574. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  7575. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  7576. }
  7577. }
  7578. if (hasFaceVertexUv2 === true) {
  7579. var vertexUvs = faceVertexUvs[1][i];
  7580. if (vertexUvs !== undefined) {
  7581. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7582. } else {
  7583. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  7584. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  7585. }
  7586. } // morphs
  7587. for (var j = 0; j < morphTargetsLength; j++) {
  7588. var morphTarget = morphTargets[j].vertices;
  7589. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  7590. }
  7591. for (var j = 0; j < morphNormalsLength; j++) {
  7592. var morphNormal = morphNormals[j].vertexNormals[i];
  7593. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  7594. } // skins
  7595. if (hasSkinIndices) {
  7596. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  7597. }
  7598. if (hasSkinWeights) {
  7599. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  7600. }
  7601. }
  7602. this.computeGroups(geometry);
  7603. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7604. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7605. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7606. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7607. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7608. if (geometry.boundingSphere !== null) {
  7609. this.boundingSphere = geometry.boundingSphere.clone();
  7610. }
  7611. if (geometry.boundingBox !== null) {
  7612. this.boundingBox = geometry.boundingBox.clone();
  7613. }
  7614. return this;
  7615. }
  7616. });
  7617. /**
  7618. * @author mrdoob / http://mrdoob.com/
  7619. */
  7620. function arrayMax(array) {
  7621. if (array.length === 0) return -Infinity;
  7622. var max = array[0];
  7623. for (var i = 1, l = array.length; i < l; ++i) {
  7624. if (array[i] > max) max = array[i];
  7625. }
  7626. return max;
  7627. }
  7628. /**
  7629. * @author alteredq / http://alteredqualia.com/
  7630. * @author mrdoob / http://mrdoob.com/
  7631. */
  7632. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  7633. var _m1$2 = new Matrix4();
  7634. var _obj = new Object3D();
  7635. var _offset = new Vector3();
  7636. var _box$1 = new Box3();
  7637. var _boxMorphTargets = new Box3();
  7638. var _vector$4 = new Vector3();
  7639. function BufferGeometry() {
  7640. Object.defineProperty(this, 'id', {
  7641. value: _bufferGeometryId += 2
  7642. });
  7643. this.uuid = _Math.generateUUID();
  7644. this.name = '';
  7645. this.type = 'BufferGeometry';
  7646. this.index = null;
  7647. this.attributes = {};
  7648. this.morphAttributes = {};
  7649. this.groups = [];
  7650. this.boundingBox = null;
  7651. this.boundingSphere = null;
  7652. this.drawRange = {
  7653. start: 0,
  7654. count: Infinity
  7655. };
  7656. this.userData = {};
  7657. }
  7658. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7659. constructor: BufferGeometry,
  7660. isBufferGeometry: true,
  7661. getIndex: function () {
  7662. return this.index;
  7663. },
  7664. setIndex: function (index) {
  7665. if (Array.isArray(index)) {
  7666. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  7667. } else {
  7668. this.index = index;
  7669. }
  7670. },
  7671. addAttribute: function (name, attribute) {
  7672. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  7673. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  7674. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  7675. }
  7676. if (name === 'index') {
  7677. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  7678. this.setIndex(attribute);
  7679. return this;
  7680. }
  7681. return this.setAttribute(name, attribute);
  7682. },
  7683. getAttribute: function (name) {
  7684. return this.attributes[name];
  7685. },
  7686. setAttribute: function (name, attribute) {
  7687. this.attributes[name] = attribute;
  7688. return this;
  7689. },
  7690. removeAttribute: function (name) {
  7691. delete this.attributes[name];
  7692. return this;
  7693. },
  7694. addGroup: function (start, count, materialIndex) {
  7695. this.groups.push({
  7696. start: start,
  7697. count: count,
  7698. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7699. });
  7700. },
  7701. clearGroups: function () {
  7702. this.groups = [];
  7703. },
  7704. setDrawRange: function (start, count) {
  7705. this.drawRange.start = start;
  7706. this.drawRange.count = count;
  7707. },
  7708. applyMatrix: function (matrix) {
  7709. var position = this.attributes.position;
  7710. if (position !== undefined) {
  7711. matrix.applyToBufferAttribute(position);
  7712. position.needsUpdate = true;
  7713. }
  7714. var normal = this.attributes.normal;
  7715. if (normal !== undefined) {
  7716. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7717. normalMatrix.applyToBufferAttribute(normal);
  7718. normal.needsUpdate = true;
  7719. }
  7720. var tangent = this.attributes.tangent;
  7721. if (tangent !== undefined) {
  7722. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  7723. normalMatrix.applyToBufferAttribute(tangent);
  7724. tangent.needsUpdate = true;
  7725. }
  7726. if (this.boundingBox !== null) {
  7727. this.computeBoundingBox();
  7728. }
  7729. if (this.boundingSphere !== null) {
  7730. this.computeBoundingSphere();
  7731. }
  7732. return this;
  7733. },
  7734. rotateX: function (angle) {
  7735. // rotate geometry around world x-axis
  7736. _m1$2.makeRotationX(angle);
  7737. this.applyMatrix(_m1$2);
  7738. return this;
  7739. },
  7740. rotateY: function (angle) {
  7741. // rotate geometry around world y-axis
  7742. _m1$2.makeRotationY(angle);
  7743. this.applyMatrix(_m1$2);
  7744. return this;
  7745. },
  7746. rotateZ: function (angle) {
  7747. // rotate geometry around world z-axis
  7748. _m1$2.makeRotationZ(angle);
  7749. this.applyMatrix(_m1$2);
  7750. return this;
  7751. },
  7752. translate: function (x, y, z) {
  7753. // translate geometry
  7754. _m1$2.makeTranslation(x, y, z);
  7755. this.applyMatrix(_m1$2);
  7756. return this;
  7757. },
  7758. scale: function (x, y, z) {
  7759. // scale geometry
  7760. _m1$2.makeScale(x, y, z);
  7761. this.applyMatrix(_m1$2);
  7762. return this;
  7763. },
  7764. lookAt: function (vector) {
  7765. _obj.lookAt(vector);
  7766. _obj.updateMatrix();
  7767. this.applyMatrix(_obj.matrix);
  7768. return this;
  7769. },
  7770. center: function () {
  7771. this.computeBoundingBox();
  7772. this.boundingBox.getCenter(_offset).negate();
  7773. this.translate(_offset.x, _offset.y, _offset.z);
  7774. return this;
  7775. },
  7776. setFromObject: function (object) {
  7777. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7778. var geometry = object.geometry;
  7779. if (object.isPoints || object.isLine) {
  7780. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  7781. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  7782. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  7783. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  7784. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  7785. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  7786. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  7787. }
  7788. if (geometry.boundingSphere !== null) {
  7789. this.boundingSphere = geometry.boundingSphere.clone();
  7790. }
  7791. if (geometry.boundingBox !== null) {
  7792. this.boundingBox = geometry.boundingBox.clone();
  7793. }
  7794. } else if (object.isMesh) {
  7795. if (geometry && geometry.isGeometry) {
  7796. this.fromGeometry(geometry);
  7797. }
  7798. }
  7799. return this;
  7800. },
  7801. setFromPoints: function (points) {
  7802. var position = [];
  7803. for (var i = 0, l = points.length; i < l; i++) {
  7804. var point = points[i];
  7805. position.push(point.x, point.y, point.z || 0);
  7806. }
  7807. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  7808. return this;
  7809. },
  7810. updateFromObject: function (object) {
  7811. var geometry = object.geometry;
  7812. if (object.isMesh) {
  7813. var direct = geometry.__directGeometry;
  7814. if (geometry.elementsNeedUpdate === true) {
  7815. direct = undefined;
  7816. geometry.elementsNeedUpdate = false;
  7817. }
  7818. if (direct === undefined) {
  7819. return this.fromGeometry(geometry);
  7820. }
  7821. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7822. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7823. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7824. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7825. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7826. geometry.verticesNeedUpdate = false;
  7827. geometry.normalsNeedUpdate = false;
  7828. geometry.colorsNeedUpdate = false;
  7829. geometry.uvsNeedUpdate = false;
  7830. geometry.groupsNeedUpdate = false;
  7831. geometry = direct;
  7832. }
  7833. var attribute;
  7834. if (geometry.verticesNeedUpdate === true) {
  7835. attribute = this.attributes.position;
  7836. if (attribute !== undefined) {
  7837. attribute.copyVector3sArray(geometry.vertices);
  7838. attribute.needsUpdate = true;
  7839. }
  7840. geometry.verticesNeedUpdate = false;
  7841. }
  7842. if (geometry.normalsNeedUpdate === true) {
  7843. attribute = this.attributes.normal;
  7844. if (attribute !== undefined) {
  7845. attribute.copyVector3sArray(geometry.normals);
  7846. attribute.needsUpdate = true;
  7847. }
  7848. geometry.normalsNeedUpdate = false;
  7849. }
  7850. if (geometry.colorsNeedUpdate === true) {
  7851. attribute = this.attributes.color;
  7852. if (attribute !== undefined) {
  7853. attribute.copyColorsArray(geometry.colors);
  7854. attribute.needsUpdate = true;
  7855. }
  7856. geometry.colorsNeedUpdate = false;
  7857. }
  7858. if (geometry.uvsNeedUpdate) {
  7859. attribute = this.attributes.uv;
  7860. if (attribute !== undefined) {
  7861. attribute.copyVector2sArray(geometry.uvs);
  7862. attribute.needsUpdate = true;
  7863. }
  7864. geometry.uvsNeedUpdate = false;
  7865. }
  7866. if (geometry.lineDistancesNeedUpdate) {
  7867. attribute = this.attributes.lineDistance;
  7868. if (attribute !== undefined) {
  7869. attribute.copyArray(geometry.lineDistances);
  7870. attribute.needsUpdate = true;
  7871. }
  7872. geometry.lineDistancesNeedUpdate = false;
  7873. }
  7874. if (geometry.groupsNeedUpdate) {
  7875. geometry.computeGroups(object.geometry);
  7876. this.groups = geometry.groups;
  7877. geometry.groupsNeedUpdate = false;
  7878. }
  7879. return this;
  7880. },
  7881. fromGeometry: function (geometry) {
  7882. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7883. return this.fromDirectGeometry(geometry.__directGeometry);
  7884. },
  7885. fromDirectGeometry: function (geometry) {
  7886. var positions = new Float32Array(geometry.vertices.length * 3);
  7887. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7888. if (geometry.normals.length > 0) {
  7889. var normals = new Float32Array(geometry.normals.length * 3);
  7890. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7891. }
  7892. if (geometry.colors.length > 0) {
  7893. var colors = new Float32Array(geometry.colors.length * 3);
  7894. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7895. }
  7896. if (geometry.uvs.length > 0) {
  7897. var uvs = new Float32Array(geometry.uvs.length * 2);
  7898. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7899. }
  7900. if (geometry.uvs2.length > 0) {
  7901. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7902. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7903. } // groups
  7904. this.groups = geometry.groups; // morphs
  7905. for (var name in geometry.morphTargets) {
  7906. var array = [];
  7907. var morphTargets = geometry.morphTargets[name];
  7908. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7909. var morphTarget = morphTargets[i];
  7910. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7911. attribute.name = morphTarget.name;
  7912. array.push(attribute.copyVector3sArray(morphTarget.data));
  7913. }
  7914. this.morphAttributes[name] = array;
  7915. } // skinning
  7916. if (geometry.skinIndices.length > 0) {
  7917. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7918. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7919. }
  7920. if (geometry.skinWeights.length > 0) {
  7921. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7922. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7923. } //
  7924. if (geometry.boundingSphere !== null) {
  7925. this.boundingSphere = geometry.boundingSphere.clone();
  7926. }
  7927. if (geometry.boundingBox !== null) {
  7928. this.boundingBox = geometry.boundingBox.clone();
  7929. }
  7930. return this;
  7931. },
  7932. computeBoundingBox: function () {
  7933. if (this.boundingBox === null) {
  7934. this.boundingBox = new Box3();
  7935. }
  7936. var position = this.attributes.position;
  7937. var morphAttributesPosition = this.morphAttributes.position;
  7938. if (position !== undefined) {
  7939. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7940. if (morphAttributesPosition) {
  7941. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7942. var morphAttribute = morphAttributesPosition[i];
  7943. _box$1.setFromBufferAttribute(morphAttribute);
  7944. this.boundingBox.expandByPoint(_box$1.min);
  7945. this.boundingBox.expandByPoint(_box$1.max);
  7946. }
  7947. }
  7948. } else {
  7949. this.boundingBox.makeEmpty();
  7950. }
  7951. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7952. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7953. }
  7954. },
  7955. computeBoundingSphere: function () {
  7956. if (this.boundingSphere === null) {
  7957. this.boundingSphere = new Sphere();
  7958. }
  7959. var position = this.attributes.position;
  7960. var morphAttributesPosition = this.morphAttributes.position;
  7961. if (position) {
  7962. // first, find the center of the bounding sphere
  7963. var center = this.boundingSphere.center;
  7964. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  7965. if (morphAttributesPosition) {
  7966. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7967. var morphAttribute = morphAttributesPosition[i];
  7968. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7969. _box$1.expandByPoint(_boxMorphTargets.min);
  7970. _box$1.expandByPoint(_boxMorphTargets.max);
  7971. }
  7972. }
  7973. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7974. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7975. var maxRadiusSq = 0;
  7976. for (var i = 0, il = position.count; i < il; i++) {
  7977. _vector$4.fromBufferAttribute(position, i);
  7978. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7979. } // process morph attributes if present
  7980. if (morphAttributesPosition) {
  7981. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7982. var morphAttribute = morphAttributesPosition[i];
  7983. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7984. _vector$4.fromBufferAttribute(morphAttribute, j);
  7985. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7986. }
  7987. }
  7988. }
  7989. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7990. if (isNaN(this.boundingSphere.radius)) {
  7991. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7992. }
  7993. }
  7994. },
  7995. computeFaceNormals: function () {// backwards compatibility
  7996. },
  7997. computeVertexNormals: function () {
  7998. var index = this.index;
  7999. var attributes = this.attributes;
  8000. if (attributes.position) {
  8001. var positions = attributes.position.array;
  8002. if (attributes.normal === undefined) {
  8003. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  8004. } else {
  8005. // reset existing normals to zero
  8006. var array = attributes.normal.array;
  8007. for (var i = 0, il = array.length; i < il; i++) {
  8008. array[i] = 0;
  8009. }
  8010. }
  8011. var normals = attributes.normal.array;
  8012. var vA, vB, vC;
  8013. var pA = new Vector3(),
  8014. pB = new Vector3(),
  8015. pC = new Vector3();
  8016. var cb = new Vector3(),
  8017. ab = new Vector3(); // indexed elements
  8018. if (index) {
  8019. var indices = index.array;
  8020. for (var i = 0, il = index.count; i < il; i += 3) {
  8021. vA = indices[i + 0] * 3;
  8022. vB = indices[i + 1] * 3;
  8023. vC = indices[i + 2] * 3;
  8024. pA.fromArray(positions, vA);
  8025. pB.fromArray(positions, vB);
  8026. pC.fromArray(positions, vC);
  8027. cb.subVectors(pC, pB);
  8028. ab.subVectors(pA, pB);
  8029. cb.cross(ab);
  8030. normals[vA] += cb.x;
  8031. normals[vA + 1] += cb.y;
  8032. normals[vA + 2] += cb.z;
  8033. normals[vB] += cb.x;
  8034. normals[vB + 1] += cb.y;
  8035. normals[vB + 2] += cb.z;
  8036. normals[vC] += cb.x;
  8037. normals[vC + 1] += cb.y;
  8038. normals[vC + 2] += cb.z;
  8039. }
  8040. } else {
  8041. // non-indexed elements (unconnected triangle soup)
  8042. for (var i = 0, il = positions.length; i < il; i += 9) {
  8043. pA.fromArray(positions, i);
  8044. pB.fromArray(positions, i + 3);
  8045. pC.fromArray(positions, i + 6);
  8046. cb.subVectors(pC, pB);
  8047. ab.subVectors(pA, pB);
  8048. cb.cross(ab);
  8049. normals[i] = cb.x;
  8050. normals[i + 1] = cb.y;
  8051. normals[i + 2] = cb.z;
  8052. normals[i + 3] = cb.x;
  8053. normals[i + 4] = cb.y;
  8054. normals[i + 5] = cb.z;
  8055. normals[i + 6] = cb.x;
  8056. normals[i + 7] = cb.y;
  8057. normals[i + 8] = cb.z;
  8058. }
  8059. }
  8060. this.normalizeNormals();
  8061. attributes.normal.needsUpdate = true;
  8062. }
  8063. },
  8064. merge: function (geometry, offset) {
  8065. if (!(geometry && geometry.isBufferGeometry)) {
  8066. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  8067. return;
  8068. }
  8069. if (offset === undefined) {
  8070. offset = 0;
  8071. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  8072. }
  8073. var attributes = this.attributes;
  8074. for (var key in attributes) {
  8075. if (geometry.attributes[key] === undefined) continue;
  8076. var attribute1 = attributes[key];
  8077. var attributeArray1 = attribute1.array;
  8078. var attribute2 = geometry.attributes[key];
  8079. var attributeArray2 = attribute2.array;
  8080. var attributeOffset = attribute2.itemSize * offset;
  8081. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  8082. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  8083. attributeArray1[j] = attributeArray2[i];
  8084. }
  8085. }
  8086. return this;
  8087. },
  8088. normalizeNormals: function () {
  8089. var normals = this.attributes.normal;
  8090. for (var i = 0, il = normals.count; i < il; i++) {
  8091. _vector$4.x = normals.getX(i);
  8092. _vector$4.y = normals.getY(i);
  8093. _vector$4.z = normals.getZ(i);
  8094. _vector$4.normalize();
  8095. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  8096. }
  8097. },
  8098. toNonIndexed: function () {
  8099. function convertBufferAttribute(attribute, indices) {
  8100. var array = attribute.array;
  8101. var itemSize = attribute.itemSize;
  8102. var array2 = new array.constructor(indices.length * itemSize);
  8103. var index = 0,
  8104. index2 = 0;
  8105. for (var i = 0, l = indices.length; i < l; i++) {
  8106. index = indices[i] * itemSize;
  8107. for (var j = 0; j < itemSize; j++) {
  8108. array2[index2++] = array[index++];
  8109. }
  8110. }
  8111. return new BufferAttribute(array2, itemSize);
  8112. } //
  8113. if (this.index === null) {
  8114. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  8115. return this;
  8116. }
  8117. var geometry2 = new BufferGeometry();
  8118. var indices = this.index.array;
  8119. var attributes = this.attributes; // attributes
  8120. for (var name in attributes) {
  8121. var attribute = attributes[name];
  8122. var newAttribute = convertBufferAttribute(attribute, indices);
  8123. geometry2.addAttribute(name, newAttribute);
  8124. } // morph attributes
  8125. var morphAttributes = this.morphAttributes;
  8126. for (name in morphAttributes) {
  8127. var morphArray = [];
  8128. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8129. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  8130. var attribute = morphAttribute[i];
  8131. var newAttribute = convertBufferAttribute(attribute, indices);
  8132. morphArray.push(newAttribute);
  8133. }
  8134. geometry2.morphAttributes[name] = morphArray;
  8135. } // groups
  8136. var groups = this.groups;
  8137. for (var i = 0, l = groups.length; i < l; i++) {
  8138. var group = groups[i];
  8139. geometry2.addGroup(group.start, group.count, group.materialIndex);
  8140. }
  8141. return geometry2;
  8142. },
  8143. toJSON: function () {
  8144. var data = {
  8145. metadata: {
  8146. version: 4.5,
  8147. type: 'BufferGeometry',
  8148. generator: 'BufferGeometry.toJSON'
  8149. }
  8150. }; // standard BufferGeometry serialization
  8151. data.uuid = this.uuid;
  8152. data.type = this.type;
  8153. if (this.name !== '') data.name = this.name;
  8154. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  8155. if (this.parameters !== undefined) {
  8156. var parameters = this.parameters;
  8157. for (var key in parameters) {
  8158. if (parameters[key] !== undefined) data[key] = parameters[key];
  8159. }
  8160. return data;
  8161. }
  8162. data.data = {
  8163. attributes: {}
  8164. };
  8165. var index = this.index;
  8166. if (index !== null) {
  8167. data.data.index = {
  8168. type: index.array.constructor.name,
  8169. array: Array.prototype.slice.call(index.array)
  8170. };
  8171. }
  8172. var attributes = this.attributes;
  8173. for (var key in attributes) {
  8174. var attribute = attributes[key];
  8175. var attributeData = attribute.toJSON();
  8176. if (attribute.name !== '') attributeData.name = attribute.name;
  8177. data.data.attributes[key] = attributeData;
  8178. }
  8179. var morphAttributes = {};
  8180. var hasMorphAttributes = false;
  8181. for (var key in this.morphAttributes) {
  8182. var attributeArray = this.morphAttributes[key];
  8183. var array = [];
  8184. for (var i = 0, il = attributeArray.length; i < il; i++) {
  8185. var attribute = attributeArray[i];
  8186. var attributeData = attribute.toJSON();
  8187. if (attribute.name !== '') attributeData.name = attribute.name;
  8188. array.push(attributeData);
  8189. }
  8190. if (array.length > 0) {
  8191. morphAttributes[key] = array;
  8192. hasMorphAttributes = true;
  8193. }
  8194. }
  8195. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  8196. var groups = this.groups;
  8197. if (groups.length > 0) {
  8198. data.data.groups = JSON.parse(JSON.stringify(groups));
  8199. }
  8200. var boundingSphere = this.boundingSphere;
  8201. if (boundingSphere !== null) {
  8202. data.data.boundingSphere = {
  8203. center: boundingSphere.center.toArray(),
  8204. radius: boundingSphere.radius
  8205. };
  8206. }
  8207. return data;
  8208. },
  8209. clone: function () {
  8210. /*
  8211. // Handle primitives
  8212. var parameters = this.parameters;
  8213. if ( parameters !== undefined ) {
  8214. var values = [];
  8215. for ( var key in parameters ) {
  8216. values.push( parameters[ key ] );
  8217. }
  8218. var geometry = Object.create( this.constructor.prototype );
  8219. this.constructor.apply( geometry, values );
  8220. return geometry;
  8221. }
  8222. return new this.constructor().copy( this );
  8223. */
  8224. return new BufferGeometry().copy(this);
  8225. },
  8226. copy: function (source) {
  8227. var name, i, l; // reset
  8228. this.index = null;
  8229. this.attributes = {};
  8230. this.morphAttributes = {};
  8231. this.groups = [];
  8232. this.boundingBox = null;
  8233. this.boundingSphere = null; // name
  8234. this.name = source.name; // index
  8235. var index = source.index;
  8236. if (index !== null) {
  8237. this.setIndex(index.clone());
  8238. } // attributes
  8239. var attributes = source.attributes;
  8240. for (name in attributes) {
  8241. var attribute = attributes[name];
  8242. this.addAttribute(name, attribute.clone());
  8243. } // morph attributes
  8244. var morphAttributes = source.morphAttributes;
  8245. for (name in morphAttributes) {
  8246. var array = [];
  8247. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8248. for (i = 0, l = morphAttribute.length; i < l; i++) {
  8249. array.push(morphAttribute[i].clone());
  8250. }
  8251. this.morphAttributes[name] = array;
  8252. } // groups
  8253. var groups = source.groups;
  8254. for (i = 0, l = groups.length; i < l; i++) {
  8255. var group = groups[i];
  8256. this.addGroup(group.start, group.count, group.materialIndex);
  8257. } // bounding box
  8258. var boundingBox = source.boundingBox;
  8259. if (boundingBox !== null) {
  8260. this.boundingBox = boundingBox.clone();
  8261. } // bounding sphere
  8262. var boundingSphere = source.boundingSphere;
  8263. if (boundingSphere !== null) {
  8264. this.boundingSphere = boundingSphere.clone();
  8265. } // draw range
  8266. this.drawRange.start = source.drawRange.start;
  8267. this.drawRange.count = source.drawRange.count; // user data
  8268. this.userData = source.userData;
  8269. return this;
  8270. },
  8271. dispose: function () {
  8272. this.dispatchEvent({
  8273. type: 'dispose'
  8274. });
  8275. }
  8276. });
  8277. /**
  8278. * @author mrdoob / http://mrdoob.com/
  8279. * @author alteredq / http://alteredqualia.com/
  8280. * @author mikael emtinger / http://gomo.se/
  8281. * @author jonobr1 / http://jonobr1.com/
  8282. */
  8283. var _inverseMatrix = new Matrix4();
  8284. var _ray = new Ray();
  8285. var _sphere = new Sphere();
  8286. var _vA = new Vector3();
  8287. var _vB = new Vector3();
  8288. var _vC = new Vector3();
  8289. var _tempA = new Vector3();
  8290. var _tempB = new Vector3();
  8291. var _tempC = new Vector3();
  8292. var _morphA = new Vector3();
  8293. var _morphB = new Vector3();
  8294. var _morphC = new Vector3();
  8295. var _uvA = new Vector2();
  8296. var _uvB = new Vector2();
  8297. var _uvC = new Vector2();
  8298. var _intersectionPoint = new Vector3();
  8299. var _intersectionPointWorld = new Vector3();
  8300. function Mesh(geometry, material) {
  8301. Object3D.call(this);
  8302. this.type = 'Mesh';
  8303. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8304. this.material = material !== undefined ? material : new MeshBasicMaterial({
  8305. color: Math.random() * 0xffffff
  8306. });
  8307. this.drawMode = TrianglesDrawMode;
  8308. this.updateMorphTargets();
  8309. }
  8310. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  8311. constructor: Mesh,
  8312. isMesh: true,
  8313. setDrawMode: function (value) {
  8314. this.drawMode = value;
  8315. },
  8316. copy: function (source) {
  8317. Object3D.prototype.copy.call(this, source);
  8318. this.drawMode = source.drawMode;
  8319. if (source.morphTargetInfluences !== undefined) {
  8320. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8321. }
  8322. if (source.morphTargetDictionary !== undefined) {
  8323. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  8324. }
  8325. return this;
  8326. },
  8327. updateMorphTargets: function () {
  8328. var geometry = this.geometry;
  8329. var m, ml, name;
  8330. if (geometry.isBufferGeometry) {
  8331. var morphAttributes = geometry.morphAttributes;
  8332. var keys = Object.keys(morphAttributes);
  8333. if (keys.length > 0) {
  8334. var morphAttribute = morphAttributes[keys[0]];
  8335. if (morphAttribute !== undefined) {
  8336. this.morphTargetInfluences = [];
  8337. this.morphTargetDictionary = {};
  8338. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  8339. name = morphAttribute[m].name || String(m);
  8340. this.morphTargetInfluences.push(0);
  8341. this.morphTargetDictionary[name] = m;
  8342. }
  8343. }
  8344. }
  8345. } else {
  8346. var morphTargets = geometry.morphTargets;
  8347. if (morphTargets !== undefined && morphTargets.length > 0) {
  8348. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  8349. }
  8350. }
  8351. },
  8352. raycast: function (raycaster, intersects) {
  8353. var geometry = this.geometry;
  8354. var material = this.material;
  8355. var matrixWorld = this.matrixWorld;
  8356. if (material === undefined) return; // Checking boundingSphere distance to ray
  8357. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8358. _sphere.copy(geometry.boundingSphere);
  8359. _sphere.applyMatrix4(matrixWorld);
  8360. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  8361. _inverseMatrix.getInverse(matrixWorld);
  8362. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  8363. if (geometry.boundingBox !== null) {
  8364. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  8365. }
  8366. var intersection;
  8367. if (geometry.isBufferGeometry) {
  8368. var a, b, c;
  8369. var index = geometry.index;
  8370. var position = geometry.attributes.position;
  8371. var morphPosition = geometry.morphAttributes.position;
  8372. var uv = geometry.attributes.uv;
  8373. var uv2 = geometry.attributes.uv2;
  8374. var groups = geometry.groups;
  8375. var drawRange = geometry.drawRange;
  8376. var i, j, il, jl;
  8377. var group, groupMaterial;
  8378. var start, end;
  8379. if (index !== null) {
  8380. // indexed buffer geometry
  8381. if (Array.isArray(material)) {
  8382. for (i = 0, il = groups.length; i < il; i++) {
  8383. group = groups[i];
  8384. groupMaterial = material[group.materialIndex];
  8385. start = Math.max(group.start, drawRange.start);
  8386. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8387. for (j = start, jl = end; j < jl; j += 3) {
  8388. a = index.getX(j);
  8389. b = index.getX(j + 1);
  8390. c = index.getX(j + 2);
  8391. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8392. if (intersection) {
  8393. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  8394. intersection.face.materialIndex = group.materialIndex;
  8395. intersects.push(intersection);
  8396. }
  8397. }
  8398. }
  8399. } else {
  8400. start = Math.max(0, drawRange.start);
  8401. end = Math.min(index.count, drawRange.start + drawRange.count);
  8402. for (i = start, il = end; i < il; i += 3) {
  8403. a = index.getX(i);
  8404. b = index.getX(i + 1);
  8405. c = index.getX(i + 2);
  8406. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8407. if (intersection) {
  8408. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  8409. intersects.push(intersection);
  8410. }
  8411. }
  8412. }
  8413. } else if (position !== undefined) {
  8414. // non-indexed buffer geometry
  8415. if (Array.isArray(material)) {
  8416. for (i = 0, il = groups.length; i < il; i++) {
  8417. group = groups[i];
  8418. groupMaterial = material[group.materialIndex];
  8419. start = Math.max(group.start, drawRange.start);
  8420. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8421. for (j = start, jl = end; j < jl; j += 3) {
  8422. a = j;
  8423. b = j + 1;
  8424. c = j + 2;
  8425. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8426. if (intersection) {
  8427. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  8428. intersection.face.materialIndex = group.materialIndex;
  8429. intersects.push(intersection);
  8430. }
  8431. }
  8432. }
  8433. } else {
  8434. start = Math.max(0, drawRange.start);
  8435. end = Math.min(position.count, drawRange.start + drawRange.count);
  8436. for (i = start, il = end; i < il; i += 3) {
  8437. a = i;
  8438. b = i + 1;
  8439. c = i + 2;
  8440. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8441. if (intersection) {
  8442. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  8443. intersects.push(intersection);
  8444. }
  8445. }
  8446. }
  8447. }
  8448. } else if (geometry.isGeometry) {
  8449. var fvA, fvB, fvC;
  8450. var isMultiMaterial = Array.isArray(material);
  8451. var vertices = geometry.vertices;
  8452. var faces = geometry.faces;
  8453. var uvs;
  8454. var faceVertexUvs = geometry.faceVertexUvs[0];
  8455. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  8456. for (var f = 0, fl = faces.length; f < fl; f++) {
  8457. var face = faces[f];
  8458. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  8459. if (faceMaterial === undefined) continue;
  8460. fvA = vertices[face.a];
  8461. fvB = vertices[face.b];
  8462. fvC = vertices[face.c];
  8463. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  8464. if (intersection) {
  8465. if (uvs && uvs[f]) {
  8466. var uvs_f = uvs[f];
  8467. _uvA.copy(uvs_f[0]);
  8468. _uvB.copy(uvs_f[1]);
  8469. _uvC.copy(uvs_f[2]);
  8470. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  8471. }
  8472. intersection.face = face;
  8473. intersection.faceIndex = f;
  8474. intersects.push(intersection);
  8475. }
  8476. }
  8477. }
  8478. },
  8479. clone: function () {
  8480. return new this.constructor(this.geometry, this.material).copy(this);
  8481. }
  8482. });
  8483. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  8484. var intersect;
  8485. if (material.side === BackSide) {
  8486. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  8487. } else {
  8488. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  8489. }
  8490. if (intersect === null) return null;
  8491. _intersectionPointWorld.copy(point);
  8492. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  8493. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  8494. if (distance < raycaster.near || distance > raycaster.far) return null;
  8495. return {
  8496. distance: distance,
  8497. point: _intersectionPointWorld.clone(),
  8498. object: object
  8499. };
  8500. }
  8501. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  8502. _vA.fromBufferAttribute(position, a);
  8503. _vB.fromBufferAttribute(position, b);
  8504. _vC.fromBufferAttribute(position, c);
  8505. var morphInfluences = object.morphTargetInfluences;
  8506. if (material.morphTargets && morphPosition && morphInfluences) {
  8507. _morphA.set(0, 0, 0);
  8508. _morphB.set(0, 0, 0);
  8509. _morphC.set(0, 0, 0);
  8510. for (var i = 0, il = morphPosition.length; i < il; i++) {
  8511. var influence = morphInfluences[i];
  8512. var morphAttribute = morphPosition[i];
  8513. if (influence === 0) continue;
  8514. _tempA.fromBufferAttribute(morphAttribute, a);
  8515. _tempB.fromBufferAttribute(morphAttribute, b);
  8516. _tempC.fromBufferAttribute(morphAttribute, c);
  8517. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  8518. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  8519. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  8520. }
  8521. _vA.add(_morphA);
  8522. _vB.add(_morphB);
  8523. _vC.add(_morphC);
  8524. }
  8525. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  8526. if (intersection) {
  8527. if (uv) {
  8528. _uvA.fromBufferAttribute(uv, a);
  8529. _uvB.fromBufferAttribute(uv, b);
  8530. _uvC.fromBufferAttribute(uv, c);
  8531. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8532. }
  8533. if (uv2) {
  8534. _uvA.fromBufferAttribute(uv2, a);
  8535. _uvB.fromBufferAttribute(uv2, b);
  8536. _uvC.fromBufferAttribute(uv2, c);
  8537. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8538. }
  8539. var face = new Face3(a, b, c);
  8540. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  8541. intersection.face = face;
  8542. }
  8543. return intersection;
  8544. }
  8545. /**
  8546. * @author mrdoob / http://mrdoob.com/
  8547. * @author kile / http://kile.stravaganza.org/
  8548. * @author alteredq / http://alteredqualia.com/
  8549. * @author mikael emtinger / http://gomo.se/
  8550. * @author zz85 / http://www.lab4games.net/zz85/blog
  8551. * @author bhouston / http://clara.io
  8552. */
  8553. var _geometryId = 0; // Geometry uses even numbers as Id
  8554. var _m1$3 = new Matrix4();
  8555. var _obj$1 = new Object3D();
  8556. var _offset$1 = new Vector3();
  8557. function Geometry() {
  8558. Object.defineProperty(this, 'id', {
  8559. value: _geometryId += 2
  8560. });
  8561. this.uuid = _Math.generateUUID();
  8562. this.name = '';
  8563. this.type = 'Geometry';
  8564. this.vertices = [];
  8565. this.colors = [];
  8566. this.faces = [];
  8567. this.faceVertexUvs = [[]];
  8568. this.morphTargets = [];
  8569. this.morphNormals = [];
  8570. this.skinWeights = [];
  8571. this.skinIndices = [];
  8572. this.lineDistances = [];
  8573. this.boundingBox = null;
  8574. this.boundingSphere = null; // update flags
  8575. this.elementsNeedUpdate = false;
  8576. this.verticesNeedUpdate = false;
  8577. this.uvsNeedUpdate = false;
  8578. this.normalsNeedUpdate = false;
  8579. this.colorsNeedUpdate = false;
  8580. this.lineDistancesNeedUpdate = false;
  8581. this.groupsNeedUpdate = false;
  8582. }
  8583. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  8584. constructor: Geometry,
  8585. isGeometry: true,
  8586. applyMatrix: function (matrix) {
  8587. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8588. for (var i = 0, il = this.vertices.length; i < il; i++) {
  8589. var vertex = this.vertices[i];
  8590. vertex.applyMatrix4(matrix);
  8591. }
  8592. for (var i = 0, il = this.faces.length; i < il; i++) {
  8593. var face = this.faces[i];
  8594. face.normal.applyMatrix3(normalMatrix).normalize();
  8595. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  8596. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  8597. }
  8598. }
  8599. if (this.boundingBox !== null) {
  8600. this.computeBoundingBox();
  8601. }
  8602. if (this.boundingSphere !== null) {
  8603. this.computeBoundingSphere();
  8604. }
  8605. this.verticesNeedUpdate = true;
  8606. this.normalsNeedUpdate = true;
  8607. return this;
  8608. },
  8609. rotateX: function (angle) {
  8610. // rotate geometry around world x-axis
  8611. _m1$3.makeRotationX(angle);
  8612. this.applyMatrix(_m1$3);
  8613. return this;
  8614. },
  8615. rotateY: function (angle) {
  8616. // rotate geometry around world y-axis
  8617. _m1$3.makeRotationY(angle);
  8618. this.applyMatrix(_m1$3);
  8619. return this;
  8620. },
  8621. rotateZ: function (angle) {
  8622. // rotate geometry around world z-axis
  8623. _m1$3.makeRotationZ(angle);
  8624. this.applyMatrix(_m1$3);
  8625. return this;
  8626. },
  8627. translate: function (x, y, z) {
  8628. // translate geometry
  8629. _m1$3.makeTranslation(x, y, z);
  8630. this.applyMatrix(_m1$3);
  8631. return this;
  8632. },
  8633. scale: function (x, y, z) {
  8634. // scale geometry
  8635. _m1$3.makeScale(x, y, z);
  8636. this.applyMatrix(_m1$3);
  8637. return this;
  8638. },
  8639. lookAt: function (vector) {
  8640. _obj$1.lookAt(vector);
  8641. _obj$1.updateMatrix();
  8642. this.applyMatrix(_obj$1.matrix);
  8643. return this;
  8644. },
  8645. fromBufferGeometry: function (geometry) {
  8646. var scope = this;
  8647. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8648. var attributes = geometry.attributes;
  8649. if (attributes.position === undefined) {
  8650. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  8651. return this;
  8652. }
  8653. var positions = attributes.position.array;
  8654. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8655. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8656. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8657. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8658. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  8659. for (var i = 0; i < positions.length; i += 3) {
  8660. scope.vertices.push(new Vector3().fromArray(positions, i));
  8661. if (colors !== undefined) {
  8662. scope.colors.push(new Color().fromArray(colors, i));
  8663. }
  8664. }
  8665. function addFace(a, b, c, materialIndex) {
  8666. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  8667. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  8668. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  8669. scope.faces.push(face);
  8670. if (uvs !== undefined) {
  8671. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  8672. }
  8673. if (uvs2 !== undefined) {
  8674. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  8675. }
  8676. }
  8677. var groups = geometry.groups;
  8678. if (groups.length > 0) {
  8679. for (var i = 0; i < groups.length; i++) {
  8680. var group = groups[i];
  8681. var start = group.start;
  8682. var count = group.count;
  8683. for (var j = start, jl = start + count; j < jl; j += 3) {
  8684. if (indices !== undefined) {
  8685. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  8686. } else {
  8687. addFace(j, j + 1, j + 2, group.materialIndex);
  8688. }
  8689. }
  8690. }
  8691. } else {
  8692. if (indices !== undefined) {
  8693. for (var i = 0; i < indices.length; i += 3) {
  8694. addFace(indices[i], indices[i + 1], indices[i + 2]);
  8695. }
  8696. } else {
  8697. for (var i = 0; i < positions.length / 3; i += 3) {
  8698. addFace(i, i + 1, i + 2);
  8699. }
  8700. }
  8701. }
  8702. this.computeFaceNormals();
  8703. if (geometry.boundingBox !== null) {
  8704. this.boundingBox = geometry.boundingBox.clone();
  8705. }
  8706. if (geometry.boundingSphere !== null) {
  8707. this.boundingSphere = geometry.boundingSphere.clone();
  8708. }
  8709. return this;
  8710. },
  8711. center: function () {
  8712. this.computeBoundingBox();
  8713. this.boundingBox.getCenter(_offset$1).negate();
  8714. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  8715. return this;
  8716. },
  8717. normalize: function () {
  8718. this.computeBoundingSphere();
  8719. var center = this.boundingSphere.center;
  8720. var radius = this.boundingSphere.radius;
  8721. var s = radius === 0 ? 1 : 1.0 / radius;
  8722. var matrix = new Matrix4();
  8723. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  8724. this.applyMatrix(matrix);
  8725. return this;
  8726. },
  8727. computeFaceNormals: function () {
  8728. var cb = new Vector3(),
  8729. ab = new Vector3();
  8730. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  8731. var face = this.faces[f];
  8732. var vA = this.vertices[face.a];
  8733. var vB = this.vertices[face.b];
  8734. var vC = this.vertices[face.c];
  8735. cb.subVectors(vC, vB);
  8736. ab.subVectors(vA, vB);
  8737. cb.cross(ab);
  8738. cb.normalize();
  8739. face.normal.copy(cb);
  8740. }
  8741. },
  8742. computeVertexNormals: function (areaWeighted) {
  8743. if (areaWeighted === undefined) areaWeighted = true;
  8744. var v, vl, f, fl, face, vertices;
  8745. vertices = new Array(this.vertices.length);
  8746. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8747. vertices[v] = new Vector3();
  8748. }
  8749. if (areaWeighted) {
  8750. // vertex normals weighted by triangle areas
  8751. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8752. var vA, vB, vC;
  8753. var cb = new Vector3(),
  8754. ab = new Vector3();
  8755. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8756. face = this.faces[f];
  8757. vA = this.vertices[face.a];
  8758. vB = this.vertices[face.b];
  8759. vC = this.vertices[face.c];
  8760. cb.subVectors(vC, vB);
  8761. ab.subVectors(vA, vB);
  8762. cb.cross(ab);
  8763. vertices[face.a].add(cb);
  8764. vertices[face.b].add(cb);
  8765. vertices[face.c].add(cb);
  8766. }
  8767. } else {
  8768. this.computeFaceNormals();
  8769. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8770. face = this.faces[f];
  8771. vertices[face.a].add(face.normal);
  8772. vertices[face.b].add(face.normal);
  8773. vertices[face.c].add(face.normal);
  8774. }
  8775. }
  8776. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8777. vertices[v].normalize();
  8778. }
  8779. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8780. face = this.faces[f];
  8781. var vertexNormals = face.vertexNormals;
  8782. if (vertexNormals.length === 3) {
  8783. vertexNormals[0].copy(vertices[face.a]);
  8784. vertexNormals[1].copy(vertices[face.b]);
  8785. vertexNormals[2].copy(vertices[face.c]);
  8786. } else {
  8787. vertexNormals[0] = vertices[face.a].clone();
  8788. vertexNormals[1] = vertices[face.b].clone();
  8789. vertexNormals[2] = vertices[face.c].clone();
  8790. }
  8791. }
  8792. if (this.faces.length > 0) {
  8793. this.normalsNeedUpdate = true;
  8794. }
  8795. },
  8796. computeFlatVertexNormals: function () {
  8797. var f, fl, face;
  8798. this.computeFaceNormals();
  8799. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8800. face = this.faces[f];
  8801. var vertexNormals = face.vertexNormals;
  8802. if (vertexNormals.length === 3) {
  8803. vertexNormals[0].copy(face.normal);
  8804. vertexNormals[1].copy(face.normal);
  8805. vertexNormals[2].copy(face.normal);
  8806. } else {
  8807. vertexNormals[0] = face.normal.clone();
  8808. vertexNormals[1] = face.normal.clone();
  8809. vertexNormals[2] = face.normal.clone();
  8810. }
  8811. }
  8812. if (this.faces.length > 0) {
  8813. this.normalsNeedUpdate = true;
  8814. }
  8815. },
  8816. computeMorphNormals: function () {
  8817. var i, il, f, fl, face; // save original normals
  8818. // - create temp variables on first access
  8819. // otherwise just copy (for faster repeated calls)
  8820. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8821. face = this.faces[f];
  8822. if (!face.__originalFaceNormal) {
  8823. face.__originalFaceNormal = face.normal.clone();
  8824. } else {
  8825. face.__originalFaceNormal.copy(face.normal);
  8826. }
  8827. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  8828. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  8829. if (!face.__originalVertexNormals[i]) {
  8830. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  8831. } else {
  8832. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  8833. }
  8834. }
  8835. } // use temp geometry to compute face and vertex normals for each morph
  8836. var tmpGeo = new Geometry();
  8837. tmpGeo.faces = this.faces;
  8838. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8839. // create on first access
  8840. if (!this.morphNormals[i]) {
  8841. this.morphNormals[i] = {};
  8842. this.morphNormals[i].faceNormals = [];
  8843. this.morphNormals[i].vertexNormals = [];
  8844. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8845. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8846. var faceNormal, vertexNormals;
  8847. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8848. faceNormal = new Vector3();
  8849. vertexNormals = {
  8850. a: new Vector3(),
  8851. b: new Vector3(),
  8852. c: new Vector3()
  8853. };
  8854. dstNormalsFace.push(faceNormal);
  8855. dstNormalsVertex.push(vertexNormals);
  8856. }
  8857. }
  8858. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8859. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8860. tmpGeo.computeFaceNormals();
  8861. tmpGeo.computeVertexNormals(); // store morph normals
  8862. var faceNormal, vertexNormals;
  8863. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8864. face = this.faces[f];
  8865. faceNormal = morphNormals.faceNormals[f];
  8866. vertexNormals = morphNormals.vertexNormals[f];
  8867. faceNormal.copy(face.normal);
  8868. vertexNormals.a.copy(face.vertexNormals[0]);
  8869. vertexNormals.b.copy(face.vertexNormals[1]);
  8870. vertexNormals.c.copy(face.vertexNormals[2]);
  8871. }
  8872. } // restore original normals
  8873. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8874. face = this.faces[f];
  8875. face.normal = face.__originalFaceNormal;
  8876. face.vertexNormals = face.__originalVertexNormals;
  8877. }
  8878. },
  8879. computeBoundingBox: function () {
  8880. if (this.boundingBox === null) {
  8881. this.boundingBox = new Box3();
  8882. }
  8883. this.boundingBox.setFromPoints(this.vertices);
  8884. },
  8885. computeBoundingSphere: function () {
  8886. if (this.boundingSphere === null) {
  8887. this.boundingSphere = new Sphere();
  8888. }
  8889. this.boundingSphere.setFromPoints(this.vertices);
  8890. },
  8891. merge: function (geometry, matrix, materialIndexOffset) {
  8892. if (!(geometry && geometry.isGeometry)) {
  8893. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8894. return;
  8895. }
  8896. var normalMatrix,
  8897. vertexOffset = this.vertices.length,
  8898. vertices1 = this.vertices,
  8899. vertices2 = geometry.vertices,
  8900. faces1 = this.faces,
  8901. faces2 = geometry.faces,
  8902. colors1 = this.colors,
  8903. colors2 = geometry.colors;
  8904. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8905. if (matrix !== undefined) {
  8906. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8907. } // vertices
  8908. for (var i = 0, il = vertices2.length; i < il; i++) {
  8909. var vertex = vertices2[i];
  8910. var vertexCopy = vertex.clone();
  8911. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8912. vertices1.push(vertexCopy);
  8913. } // colors
  8914. for (var i = 0, il = colors2.length; i < il; i++) {
  8915. colors1.push(colors2[i].clone());
  8916. } // faces
  8917. for (i = 0, il = faces2.length; i < il; i++) {
  8918. var face = faces2[i],
  8919. faceCopy,
  8920. normal,
  8921. color,
  8922. faceVertexNormals = face.vertexNormals,
  8923. faceVertexColors = face.vertexColors;
  8924. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8925. faceCopy.normal.copy(face.normal);
  8926. if (normalMatrix !== undefined) {
  8927. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8928. }
  8929. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8930. normal = faceVertexNormals[j].clone();
  8931. if (normalMatrix !== undefined) {
  8932. normal.applyMatrix3(normalMatrix).normalize();
  8933. }
  8934. faceCopy.vertexNormals.push(normal);
  8935. }
  8936. faceCopy.color.copy(face.color);
  8937. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8938. color = faceVertexColors[j];
  8939. faceCopy.vertexColors.push(color.clone());
  8940. }
  8941. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8942. faces1.push(faceCopy);
  8943. } // uvs
  8944. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8945. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8946. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8947. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8948. var uvs2 = faceVertexUvs2[j],
  8949. uvsCopy = [];
  8950. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8951. uvsCopy.push(uvs2[k].clone());
  8952. }
  8953. this.faceVertexUvs[i].push(uvsCopy);
  8954. }
  8955. }
  8956. },
  8957. mergeMesh: function (mesh) {
  8958. if (!(mesh && mesh.isMesh)) {
  8959. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8960. return;
  8961. }
  8962. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8963. this.merge(mesh.geometry, mesh.matrix);
  8964. },
  8965. /*
  8966. * Checks for duplicate vertices with hashmap.
  8967. * Duplicated vertices are removed
  8968. * and faces' vertices are updated.
  8969. */
  8970. mergeVertices: function () {
  8971. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8972. var unique = [],
  8973. changes = [];
  8974. var v, key;
  8975. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8976. var precision = Math.pow(10, precisionPoints);
  8977. var i, il, face;
  8978. var indices, j, jl;
  8979. for (i = 0, il = this.vertices.length; i < il; i++) {
  8980. v = this.vertices[i];
  8981. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8982. if (verticesMap[key] === undefined) {
  8983. verticesMap[key] = i;
  8984. unique.push(this.vertices[i]);
  8985. changes[i] = unique.length - 1;
  8986. } else {
  8987. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8988. changes[i] = changes[verticesMap[key]];
  8989. }
  8990. } // if faces are completely degenerate after merging vertices, we
  8991. // have to remove them from the geometry.
  8992. var faceIndicesToRemove = [];
  8993. for (i = 0, il = this.faces.length; i < il; i++) {
  8994. face = this.faces[i];
  8995. face.a = changes[face.a];
  8996. face.b = changes[face.b];
  8997. face.c = changes[face.c];
  8998. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8999. // we have to remove the face as nothing can be saved
  9000. for (var n = 0; n < 3; n++) {
  9001. if (indices[n] === indices[(n + 1) % 3]) {
  9002. faceIndicesToRemove.push(i);
  9003. break;
  9004. }
  9005. }
  9006. }
  9007. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  9008. var idx = faceIndicesToRemove[i];
  9009. this.faces.splice(idx, 1);
  9010. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  9011. this.faceVertexUvs[j].splice(idx, 1);
  9012. }
  9013. } // Use unique set of vertices
  9014. var diff = this.vertices.length - unique.length;
  9015. this.vertices = unique;
  9016. return diff;
  9017. },
  9018. setFromPoints: function (points) {
  9019. this.vertices = [];
  9020. for (var i = 0, l = points.length; i < l; i++) {
  9021. var point = points[i];
  9022. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  9023. }
  9024. return this;
  9025. },
  9026. sortFacesByMaterialIndex: function () {
  9027. var faces = this.faces;
  9028. var length = faces.length; // tag faces
  9029. for (var i = 0; i < length; i++) {
  9030. faces[i]._id = i;
  9031. } // sort faces
  9032. function materialIndexSort(a, b) {
  9033. return a.materialIndex - b.materialIndex;
  9034. }
  9035. faces.sort(materialIndexSort); // sort uvs
  9036. var uvs1 = this.faceVertexUvs[0];
  9037. var uvs2 = this.faceVertexUvs[1];
  9038. var newUvs1, newUvs2;
  9039. if (uvs1 && uvs1.length === length) newUvs1 = [];
  9040. if (uvs2 && uvs2.length === length) newUvs2 = [];
  9041. for (var i = 0; i < length; i++) {
  9042. var id = faces[i]._id;
  9043. if (newUvs1) newUvs1.push(uvs1[id]);
  9044. if (newUvs2) newUvs2.push(uvs2[id]);
  9045. }
  9046. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  9047. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  9048. },
  9049. toJSON: function () {
  9050. var data = {
  9051. metadata: {
  9052. version: 4.5,
  9053. type: 'Geometry',
  9054. generator: 'Geometry.toJSON'
  9055. }
  9056. }; // standard Geometry serialization
  9057. data.uuid = this.uuid;
  9058. data.type = this.type;
  9059. if (this.name !== '') data.name = this.name;
  9060. if (this.parameters !== undefined) {
  9061. var parameters = this.parameters;
  9062. for (var key in parameters) {
  9063. if (parameters[key] !== undefined) data[key] = parameters[key];
  9064. }
  9065. return data;
  9066. }
  9067. var vertices = [];
  9068. for (var i = 0; i < this.vertices.length; i++) {
  9069. var vertex = this.vertices[i];
  9070. vertices.push(vertex.x, vertex.y, vertex.z);
  9071. }
  9072. var faces = [];
  9073. var normals = [];
  9074. var normalsHash = {};
  9075. var colors = [];
  9076. var colorsHash = {};
  9077. var uvs = [];
  9078. var uvsHash = {};
  9079. for (var i = 0; i < this.faces.length; i++) {
  9080. var face = this.faces[i];
  9081. var hasMaterial = true;
  9082. var hasFaceUv = false; // deprecated
  9083. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  9084. var hasFaceNormal = face.normal.length() > 0;
  9085. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9086. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9087. var hasFaceVertexColor = face.vertexColors.length > 0;
  9088. var faceType = 0;
  9089. faceType = setBit(faceType, 0, 0); // isQuad
  9090. faceType = setBit(faceType, 1, hasMaterial);
  9091. faceType = setBit(faceType, 2, hasFaceUv);
  9092. faceType = setBit(faceType, 3, hasFaceVertexUv);
  9093. faceType = setBit(faceType, 4, hasFaceNormal);
  9094. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  9095. faceType = setBit(faceType, 6, hasFaceColor);
  9096. faceType = setBit(faceType, 7, hasFaceVertexColor);
  9097. faces.push(faceType);
  9098. faces.push(face.a, face.b, face.c);
  9099. faces.push(face.materialIndex);
  9100. if (hasFaceVertexUv) {
  9101. var faceVertexUvs = this.faceVertexUvs[0][i];
  9102. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  9103. }
  9104. if (hasFaceNormal) {
  9105. faces.push(getNormalIndex(face.normal));
  9106. }
  9107. if (hasFaceVertexNormal) {
  9108. var vertexNormals = face.vertexNormals;
  9109. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  9110. }
  9111. if (hasFaceColor) {
  9112. faces.push(getColorIndex(face.color));
  9113. }
  9114. if (hasFaceVertexColor) {
  9115. var vertexColors = face.vertexColors;
  9116. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  9117. }
  9118. }
  9119. function setBit(value, position, enabled) {
  9120. return enabled ? value | 1 << position : value & ~(1 << position);
  9121. }
  9122. function getNormalIndex(normal) {
  9123. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9124. if (normalsHash[hash] !== undefined) {
  9125. return normalsHash[hash];
  9126. }
  9127. normalsHash[hash] = normals.length / 3;
  9128. normals.push(normal.x, normal.y, normal.z);
  9129. return normalsHash[hash];
  9130. }
  9131. function getColorIndex(color) {
  9132. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9133. if (colorsHash[hash] !== undefined) {
  9134. return colorsHash[hash];
  9135. }
  9136. colorsHash[hash] = colors.length;
  9137. colors.push(color.getHex());
  9138. return colorsHash[hash];
  9139. }
  9140. function getUvIndex(uv) {
  9141. var hash = uv.x.toString() + uv.y.toString();
  9142. if (uvsHash[hash] !== undefined) {
  9143. return uvsHash[hash];
  9144. }
  9145. uvsHash[hash] = uvs.length / 2;
  9146. uvs.push(uv.x, uv.y);
  9147. return uvsHash[hash];
  9148. }
  9149. data.data = {};
  9150. data.data.vertices = vertices;
  9151. data.data.normals = normals;
  9152. if (colors.length > 0) data.data.colors = colors;
  9153. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  9154. data.data.faces = faces;
  9155. return data;
  9156. },
  9157. clone: function () {
  9158. /*
  9159. // Handle primitives
  9160. var parameters = this.parameters;
  9161. if ( parameters !== undefined ) {
  9162. var values = [];
  9163. for ( var key in parameters ) {
  9164. values.push( parameters[ key ] );
  9165. }
  9166. var geometry = Object.create( this.constructor.prototype );
  9167. this.constructor.apply( geometry, values );
  9168. return geometry;
  9169. }
  9170. return new this.constructor().copy( this );
  9171. */
  9172. return new Geometry().copy(this);
  9173. },
  9174. copy: function (source) {
  9175. var i, il, j, jl, k, kl; // reset
  9176. this.vertices = [];
  9177. this.colors = [];
  9178. this.faces = [];
  9179. this.faceVertexUvs = [[]];
  9180. this.morphTargets = [];
  9181. this.morphNormals = [];
  9182. this.skinWeights = [];
  9183. this.skinIndices = [];
  9184. this.lineDistances = [];
  9185. this.boundingBox = null;
  9186. this.boundingSphere = null; // name
  9187. this.name = source.name; // vertices
  9188. var vertices = source.vertices;
  9189. for (i = 0, il = vertices.length; i < il; i++) {
  9190. this.vertices.push(vertices[i].clone());
  9191. } // colors
  9192. var colors = source.colors;
  9193. for (i = 0, il = colors.length; i < il; i++) {
  9194. this.colors.push(colors[i].clone());
  9195. } // faces
  9196. var faces = source.faces;
  9197. for (i = 0, il = faces.length; i < il; i++) {
  9198. this.faces.push(faces[i].clone());
  9199. } // face vertex uvs
  9200. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  9201. var faceVertexUvs = source.faceVertexUvs[i];
  9202. if (this.faceVertexUvs[i] === undefined) {
  9203. this.faceVertexUvs[i] = [];
  9204. }
  9205. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  9206. var uvs = faceVertexUvs[j],
  9207. uvsCopy = [];
  9208. for (k = 0, kl = uvs.length; k < kl; k++) {
  9209. var uv = uvs[k];
  9210. uvsCopy.push(uv.clone());
  9211. }
  9212. this.faceVertexUvs[i].push(uvsCopy);
  9213. }
  9214. } // morph targets
  9215. var morphTargets = source.morphTargets;
  9216. for (i = 0, il = morphTargets.length; i < il; i++) {
  9217. var morphTarget = {};
  9218. morphTarget.name = morphTargets[i].name; // vertices
  9219. if (morphTargets[i].vertices !== undefined) {
  9220. morphTarget.vertices = [];
  9221. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  9222. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  9223. }
  9224. } // normals
  9225. if (morphTargets[i].normals !== undefined) {
  9226. morphTarget.normals = [];
  9227. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  9228. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  9229. }
  9230. }
  9231. this.morphTargets.push(morphTarget);
  9232. } // morph normals
  9233. var morphNormals = source.morphNormals;
  9234. for (i = 0, il = morphNormals.length; i < il; i++) {
  9235. var morphNormal = {}; // vertex normals
  9236. if (morphNormals[i].vertexNormals !== undefined) {
  9237. morphNormal.vertexNormals = [];
  9238. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  9239. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  9240. var destVertexNormal = {};
  9241. destVertexNormal.a = srcVertexNormal.a.clone();
  9242. destVertexNormal.b = srcVertexNormal.b.clone();
  9243. destVertexNormal.c = srcVertexNormal.c.clone();
  9244. morphNormal.vertexNormals.push(destVertexNormal);
  9245. }
  9246. } // face normals
  9247. if (morphNormals[i].faceNormals !== undefined) {
  9248. morphNormal.faceNormals = [];
  9249. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  9250. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  9251. }
  9252. }
  9253. this.morphNormals.push(morphNormal);
  9254. } // skin weights
  9255. var skinWeights = source.skinWeights;
  9256. for (i = 0, il = skinWeights.length; i < il; i++) {
  9257. this.skinWeights.push(skinWeights[i].clone());
  9258. } // skin indices
  9259. var skinIndices = source.skinIndices;
  9260. for (i = 0, il = skinIndices.length; i < il; i++) {
  9261. this.skinIndices.push(skinIndices[i].clone());
  9262. } // line distances
  9263. var lineDistances = source.lineDistances;
  9264. for (i = 0, il = lineDistances.length; i < il; i++) {
  9265. this.lineDistances.push(lineDistances[i]);
  9266. } // bounding box
  9267. var boundingBox = source.boundingBox;
  9268. if (boundingBox !== null) {
  9269. this.boundingBox = boundingBox.clone();
  9270. } // bounding sphere
  9271. var boundingSphere = source.boundingSphere;
  9272. if (boundingSphere !== null) {
  9273. this.boundingSphere = boundingSphere.clone();
  9274. } // update flags
  9275. this.elementsNeedUpdate = source.elementsNeedUpdate;
  9276. this.verticesNeedUpdate = source.verticesNeedUpdate;
  9277. this.uvsNeedUpdate = source.uvsNeedUpdate;
  9278. this.normalsNeedUpdate = source.normalsNeedUpdate;
  9279. this.colorsNeedUpdate = source.colorsNeedUpdate;
  9280. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  9281. this.groupsNeedUpdate = source.groupsNeedUpdate;
  9282. return this;
  9283. },
  9284. dispose: function () {
  9285. this.dispatchEvent({
  9286. type: 'dispose'
  9287. });
  9288. }
  9289. });
  9290. /**
  9291. * @author mrdoob / http://mrdoob.com/
  9292. * @author Mugen87 / https://github.com/Mugen87
  9293. */
  9294. // BoxGeometry
  9295. class BoxGeometry extends Geometry {
  9296. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9297. super();
  9298. this.type = 'BoxGeometry';
  9299. this.parameters = {
  9300. width: width,
  9301. height: height,
  9302. depth: depth,
  9303. widthSegments: widthSegments,
  9304. heightSegments: heightSegments,
  9305. depthSegments: depthSegments
  9306. };
  9307. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  9308. this.mergeVertices();
  9309. }
  9310. } // BoxBufferGeometry
  9311. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  9312. class BoxBufferGeometry extends BufferGeometry {
  9313. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9314. super();
  9315. this.type = 'BoxBufferGeometry';
  9316. this.parameters = {
  9317. width: width,
  9318. height: height,
  9319. depth: depth,
  9320. widthSegments: widthSegments,
  9321. heightSegments: heightSegments,
  9322. depthSegments: depthSegments
  9323. };
  9324. var scope = this;
  9325. width = width || 1;
  9326. height = height || 1;
  9327. depth = depth || 1; // segments
  9328. widthSegments = Math.floor(widthSegments) || 1;
  9329. heightSegments = Math.floor(heightSegments) || 1;
  9330. depthSegments = Math.floor(depthSegments) || 1; // buffers
  9331. var indices = [];
  9332. var vertices = [];
  9333. var normals = [];
  9334. var uvs = []; // helper variables
  9335. var numberOfVertices = 0;
  9336. var groupStart = 0; // build each side of the box geometry
  9337. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  9338. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  9339. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  9340. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  9341. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  9342. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  9343. // build geometry
  9344. this.setIndex(indices);
  9345. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9346. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9347. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9348. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  9349. var segmentWidth = width / gridX;
  9350. var segmentHeight = height / gridY;
  9351. var widthHalf = width / 2;
  9352. var heightHalf = height / 2;
  9353. var depthHalf = depth / 2;
  9354. var gridX1 = gridX + 1;
  9355. var gridY1 = gridY + 1;
  9356. var vertexCounter = 0;
  9357. var groupCount = 0;
  9358. var ix, iy;
  9359. var vector = new Vector3(); // generate vertices, normals and uvs
  9360. for (iy = 0; iy < gridY1; iy++) {
  9361. var y = iy * segmentHeight - heightHalf;
  9362. for (ix = 0; ix < gridX1; ix++) {
  9363. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  9364. vector[u] = x * udir;
  9365. vector[v] = y * vdir;
  9366. vector[w] = depthHalf; // now apply vector to vertex buffer
  9367. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  9368. vector[u] = 0;
  9369. vector[v] = 0;
  9370. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  9371. normals.push(vector.x, vector.y, vector.z); // uvs
  9372. uvs.push(ix / gridX);
  9373. uvs.push(1 - iy / gridY); // counters
  9374. vertexCounter += 1;
  9375. }
  9376. } // indices
  9377. // 1. you need three indices to draw a single face
  9378. // 2. a single segment consists of two faces
  9379. // 3. so we need to generate six (2*3) indices per segment
  9380. for (iy = 0; iy < gridY; iy++) {
  9381. for (ix = 0; ix < gridX; ix++) {
  9382. var a = numberOfVertices + ix + gridX1 * iy;
  9383. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  9384. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  9385. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  9386. indices.push(a, b, d);
  9387. indices.push(b, c, d); // increase counter
  9388. groupCount += 6;
  9389. }
  9390. } // add a group to the geometry. this will ensure multi material support
  9391. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  9392. groupStart += groupCount; // update total number of vertices
  9393. numberOfVertices += vertexCounter;
  9394. }
  9395. }
  9396. }
  9397. /**
  9398. * Uniform Utilities
  9399. */
  9400. exports.BoxBufferGeometry = BoxBufferGeometry;
  9401. function cloneUniforms(src) {
  9402. var dst = {};
  9403. for (var u in src) {
  9404. dst[u] = {};
  9405. for (var p in src[u]) {
  9406. var property = src[u][p];
  9407. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  9408. dst[u][p] = property.clone();
  9409. } else if (Array.isArray(property)) {
  9410. dst[u][p] = property.slice();
  9411. } else {
  9412. dst[u][p] = property;
  9413. }
  9414. }
  9415. }
  9416. return dst;
  9417. }
  9418. function mergeUniforms(uniforms) {
  9419. var merged = {};
  9420. for (var u = 0; u < uniforms.length; u++) {
  9421. var tmp = cloneUniforms(uniforms[u]);
  9422. for (var p in tmp) {
  9423. merged[p] = tmp[p];
  9424. }
  9425. }
  9426. return merged;
  9427. } // Legacy
  9428. var UniformsUtils = {
  9429. clone: cloneUniforms,
  9430. merge: mergeUniforms
  9431. };
  9432. exports.UniformsUtils = UniformsUtils;
  9433. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  9434. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  9435. /**
  9436. * @author alteredq / http://alteredqualia.com/
  9437. *
  9438. * parameters = {
  9439. * defines: { "label" : "value" },
  9440. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9441. *
  9442. * fragmentShader: <string>,
  9443. * vertexShader: <string>,
  9444. *
  9445. * wireframe: <boolean>,
  9446. * wireframeLinewidth: <float>,
  9447. *
  9448. * lights: <bool>,
  9449. *
  9450. * skinning: <bool>,
  9451. * morphTargets: <bool>,
  9452. * morphNormals: <bool>
  9453. * }
  9454. */
  9455. function ShaderMaterial(parameters) {
  9456. Material.call(this);
  9457. this.type = 'ShaderMaterial';
  9458. this.defines = {};
  9459. this.uniforms = {};
  9460. this.vertexShader = default_vertex;
  9461. this.fragmentShader = default_fragment;
  9462. this.linewidth = 1;
  9463. this.wireframe = false;
  9464. this.wireframeLinewidth = 1;
  9465. this.fog = false; // set to use scene fog
  9466. this.lights = false; // set to use scene lights
  9467. this.clipping = false; // set to use user-defined clipping planes
  9468. this.skinning = false; // set to use skinning attribute streams
  9469. this.morphTargets = false; // set to use morph targets
  9470. this.morphNormals = false; // set to use morph normals
  9471. this.extensions = {
  9472. derivatives: false,
  9473. // set to use derivatives
  9474. fragDepth: false,
  9475. // set to use fragment depth values
  9476. drawBuffers: false,
  9477. // set to use draw buffers
  9478. shaderTextureLOD: false // set to use shader texture LOD
  9479. }; // When rendered geometry doesn't include these attributes but the material does,
  9480. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9481. this.defaultAttributeValues = {
  9482. 'color': [1, 1, 1],
  9483. 'uv': [0, 0],
  9484. 'uv2': [0, 0]
  9485. };
  9486. this.index0AttributeName = undefined;
  9487. this.uniformsNeedUpdate = false;
  9488. if (parameters !== undefined) {
  9489. if (parameters.attributes !== undefined) {
  9490. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  9491. }
  9492. this.setValues(parameters);
  9493. }
  9494. }
  9495. ShaderMaterial.prototype = Object.create(Material.prototype);
  9496. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9497. ShaderMaterial.prototype.isShaderMaterial = true;
  9498. ShaderMaterial.prototype.copy = function (source) {
  9499. Material.prototype.copy.call(this, source);
  9500. this.fragmentShader = source.fragmentShader;
  9501. this.vertexShader = source.vertexShader;
  9502. this.uniforms = cloneUniforms(source.uniforms);
  9503. this.defines = Object.assign({}, source.defines);
  9504. this.wireframe = source.wireframe;
  9505. this.wireframeLinewidth = source.wireframeLinewidth;
  9506. this.lights = source.lights;
  9507. this.clipping = source.clipping;
  9508. this.skinning = source.skinning;
  9509. this.morphTargets = source.morphTargets;
  9510. this.morphNormals = source.morphNormals;
  9511. this.extensions = source.extensions;
  9512. return this;
  9513. };
  9514. ShaderMaterial.prototype.toJSON = function (meta) {
  9515. var data = Material.prototype.toJSON.call(this, meta);
  9516. data.uniforms = {};
  9517. for (var name in this.uniforms) {
  9518. var uniform = this.uniforms[name];
  9519. var value = uniform.value;
  9520. if (value && value.isTexture) {
  9521. data.uniforms[name] = {
  9522. type: 't',
  9523. value: value.toJSON(meta).uuid
  9524. };
  9525. } else if (value && value.isColor) {
  9526. data.uniforms[name] = {
  9527. type: 'c',
  9528. value: value.getHex()
  9529. };
  9530. } else if (value && value.isVector2) {
  9531. data.uniforms[name] = {
  9532. type: 'v2',
  9533. value: value.toArray()
  9534. };
  9535. } else if (value && value.isVector3) {
  9536. data.uniforms[name] = {
  9537. type: 'v3',
  9538. value: value.toArray()
  9539. };
  9540. } else if (value && value.isVector4) {
  9541. data.uniforms[name] = {
  9542. type: 'v4',
  9543. value: value.toArray()
  9544. };
  9545. } else if (value && value.isMatrix3) {
  9546. data.uniforms[name] = {
  9547. type: 'm3',
  9548. value: value.toArray()
  9549. };
  9550. } else if (value && value.isMatrix4) {
  9551. data.uniforms[name] = {
  9552. type: 'm4',
  9553. value: value.toArray()
  9554. };
  9555. } else {
  9556. data.uniforms[name] = {
  9557. value: value
  9558. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9559. }
  9560. }
  9561. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  9562. data.vertexShader = this.vertexShader;
  9563. data.fragmentShader = this.fragmentShader;
  9564. var extensions = {};
  9565. for (var key in this.extensions) {
  9566. if (this.extensions[key] === true) extensions[key] = true;
  9567. }
  9568. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  9569. return data;
  9570. };
  9571. /**
  9572. * @author mrdoob / http://mrdoob.com/
  9573. * @author mikael emtinger / http://gomo.se/
  9574. * @author WestLangley / http://github.com/WestLangley
  9575. */
  9576. function Camera() {
  9577. Object3D.call(this);
  9578. this.type = 'Camera';
  9579. this.matrixWorldInverse = new Matrix4();
  9580. this.projectionMatrix = new Matrix4();
  9581. this.projectionMatrixInverse = new Matrix4();
  9582. }
  9583. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  9584. constructor: Camera,
  9585. isCamera: true,
  9586. copy: function (source, recursive) {
  9587. Object3D.prototype.copy.call(this, source, recursive);
  9588. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  9589. this.projectionMatrix.copy(source.projectionMatrix);
  9590. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  9591. return this;
  9592. },
  9593. getWorldDirection: function (target) {
  9594. if (target === undefined) {
  9595. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  9596. target = new Vector3();
  9597. }
  9598. this.updateMatrixWorld(true);
  9599. var e = this.matrixWorld.elements;
  9600. return target.set(-e[8], -e[9], -e[10]).normalize();
  9601. },
  9602. updateMatrixWorld: function (force) {
  9603. Object3D.prototype.updateMatrixWorld.call(this, force);
  9604. this.matrixWorldInverse.getInverse(this.matrixWorld);
  9605. },
  9606. clone: function () {
  9607. return new this.constructor().copy(this);
  9608. }
  9609. });
  9610. /**
  9611. * @author mrdoob / http://mrdoob.com/
  9612. * @author greggman / http://games.greggman.com/
  9613. * @author zz85 / http://www.lab4games.net/zz85/blog
  9614. * @author tschw
  9615. */
  9616. function PerspectiveCamera(fov, aspect, near, far) {
  9617. Camera.call(this);
  9618. this.type = 'PerspectiveCamera';
  9619. this.fov = fov !== undefined ? fov : 50;
  9620. this.zoom = 1;
  9621. this.near = near !== undefined ? near : 0.1;
  9622. this.far = far !== undefined ? far : 2000;
  9623. this.focus = 10;
  9624. this.aspect = aspect !== undefined ? aspect : 1;
  9625. this.view = null;
  9626. this.filmGauge = 35; // width of the film (default in millimeters)
  9627. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9628. this.updateProjectionMatrix();
  9629. }
  9630. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  9631. constructor: PerspectiveCamera,
  9632. isPerspectiveCamera: true,
  9633. copy: function (source, recursive) {
  9634. Camera.prototype.copy.call(this, source, recursive);
  9635. this.fov = source.fov;
  9636. this.zoom = source.zoom;
  9637. this.near = source.near;
  9638. this.far = source.far;
  9639. this.focus = source.focus;
  9640. this.aspect = source.aspect;
  9641. this.view = source.view === null ? null : Object.assign({}, source.view);
  9642. this.filmGauge = source.filmGauge;
  9643. this.filmOffset = source.filmOffset;
  9644. return this;
  9645. },
  9646. /**
  9647. * Sets the FOV by focal length in respect to the current .filmGauge.
  9648. *
  9649. * The default film gauge is 35, so that the focal length can be specified for
  9650. * a 35mm (full frame) camera.
  9651. *
  9652. * Values for focal length and film gauge must have the same unit.
  9653. */
  9654. setFocalLength: function (focalLength) {
  9655. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9656. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9657. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  9658. this.updateProjectionMatrix();
  9659. },
  9660. /**
  9661. * Calculates the focal length from the current .fov and .filmGauge.
  9662. */
  9663. getFocalLength: function () {
  9664. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  9665. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9666. },
  9667. getEffectiveFOV: function () {
  9668. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  9669. },
  9670. getFilmWidth: function () {
  9671. // film not completely covered in portrait format (aspect < 1)
  9672. return this.filmGauge * Math.min(this.aspect, 1);
  9673. },
  9674. getFilmHeight: function () {
  9675. // film not completely covered in landscape format (aspect > 1)
  9676. return this.filmGauge / Math.max(this.aspect, 1);
  9677. },
  9678. /**
  9679. * Sets an offset in a larger frustum. This is useful for multi-window or
  9680. * multi-monitor/multi-machine setups.
  9681. *
  9682. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9683. * the monitors are in grid like this
  9684. *
  9685. * +---+---+---+
  9686. * | A | B | C |
  9687. * +---+---+---+
  9688. * | D | E | F |
  9689. * +---+---+---+
  9690. *
  9691. * then for each monitor you would call it like this
  9692. *
  9693. * var w = 1920;
  9694. * var h = 1080;
  9695. * var fullWidth = w * 3;
  9696. * var fullHeight = h * 2;
  9697. *
  9698. * --A--
  9699. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9700. * --B--
  9701. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9702. * --C--
  9703. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9704. * --D--
  9705. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9706. * --E--
  9707. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9708. * --F--
  9709. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9710. *
  9711. * Note there is no reason monitors have to be the same size or in a grid.
  9712. */
  9713. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  9714. this.aspect = fullWidth / fullHeight;
  9715. if (this.view === null) {
  9716. this.view = {
  9717. enabled: true,
  9718. fullWidth: 1,
  9719. fullHeight: 1,
  9720. offsetX: 0,
  9721. offsetY: 0,
  9722. width: 1,
  9723. height: 1
  9724. };
  9725. }
  9726. this.view.enabled = true;
  9727. this.view.fullWidth = fullWidth;
  9728. this.view.fullHeight = fullHeight;
  9729. this.view.offsetX = x;
  9730. this.view.offsetY = y;
  9731. this.view.width = width;
  9732. this.view.height = height;
  9733. this.updateProjectionMatrix();
  9734. },
  9735. clearViewOffset: function () {
  9736. if (this.view !== null) {
  9737. this.view.enabled = false;
  9738. }
  9739. this.updateProjectionMatrix();
  9740. },
  9741. updateProjectionMatrix: function () {
  9742. var near = this.near,
  9743. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  9744. height = 2 * top,
  9745. width = this.aspect * height,
  9746. left = -0.5 * width,
  9747. view = this.view;
  9748. if (this.view !== null && this.view.enabled) {
  9749. var fullWidth = view.fullWidth,
  9750. fullHeight = view.fullHeight;
  9751. left += view.offsetX * width / fullWidth;
  9752. top -= view.offsetY * height / fullHeight;
  9753. width *= view.width / fullWidth;
  9754. height *= view.height / fullHeight;
  9755. }
  9756. var skew = this.filmOffset;
  9757. if (skew !== 0) left += near * skew / this.getFilmWidth();
  9758. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  9759. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  9760. },
  9761. toJSON: function (meta) {
  9762. var data = Object3D.prototype.toJSON.call(this, meta);
  9763. data.object.fov = this.fov;
  9764. data.object.zoom = this.zoom;
  9765. data.object.near = this.near;
  9766. data.object.far = this.far;
  9767. data.object.focus = this.focus;
  9768. data.object.aspect = this.aspect;
  9769. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9770. data.object.filmGauge = this.filmGauge;
  9771. data.object.filmOffset = this.filmOffset;
  9772. return data;
  9773. }
  9774. });
  9775. /**
  9776. * Camera for rendering cube maps
  9777. * - renders scene into axis-aligned cube
  9778. *
  9779. * @author alteredq / http://alteredqualia.com/
  9780. */
  9781. var fov = 90,
  9782. aspect = 1;
  9783. function CubeCamera(near, far, cubeResolution, options) {
  9784. Object3D.call(this);
  9785. this.type = 'CubeCamera';
  9786. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  9787. cameraPX.up.set(0, -1, 0);
  9788. cameraPX.lookAt(new Vector3(1, 0, 0));
  9789. this.add(cameraPX);
  9790. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  9791. cameraNX.up.set(0, -1, 0);
  9792. cameraNX.lookAt(new Vector3(-1, 0, 0));
  9793. this.add(cameraNX);
  9794. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  9795. cameraPY.up.set(0, 0, 1);
  9796. cameraPY.lookAt(new Vector3(0, 1, 0));
  9797. this.add(cameraPY);
  9798. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  9799. cameraNY.up.set(0, 0, -1);
  9800. cameraNY.lookAt(new Vector3(0, -1, 0));
  9801. this.add(cameraNY);
  9802. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  9803. cameraPZ.up.set(0, -1, 0);
  9804. cameraPZ.lookAt(new Vector3(0, 0, 1));
  9805. this.add(cameraPZ);
  9806. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  9807. cameraNZ.up.set(0, -1, 0);
  9808. cameraNZ.lookAt(new Vector3(0, 0, -1));
  9809. this.add(cameraNZ);
  9810. options = options || {
  9811. format: RGBFormat,
  9812. magFilter: LinearFilter,
  9813. minFilter: LinearFilter
  9814. };
  9815. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  9816. this.renderTarget.texture.name = "CubeCamera";
  9817. this.update = function (renderer, scene) {
  9818. if (this.parent === null) this.updateMatrixWorld();
  9819. var currentRenderTarget = renderer.getRenderTarget();
  9820. var renderTarget = this.renderTarget;
  9821. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9822. renderTarget.texture.generateMipmaps = false;
  9823. renderer.setRenderTarget(renderTarget, 0);
  9824. renderer.render(scene, cameraPX);
  9825. renderer.setRenderTarget(renderTarget, 1);
  9826. renderer.render(scene, cameraNX);
  9827. renderer.setRenderTarget(renderTarget, 2);
  9828. renderer.render(scene, cameraPY);
  9829. renderer.setRenderTarget(renderTarget, 3);
  9830. renderer.render(scene, cameraNY);
  9831. renderer.setRenderTarget(renderTarget, 4);
  9832. renderer.render(scene, cameraPZ);
  9833. renderTarget.texture.generateMipmaps = generateMipmaps;
  9834. renderer.setRenderTarget(renderTarget, 5);
  9835. renderer.render(scene, cameraNZ);
  9836. renderer.setRenderTarget(currentRenderTarget);
  9837. };
  9838. this.clear = function (renderer, color, depth, stencil) {
  9839. var currentRenderTarget = renderer.getRenderTarget();
  9840. var renderTarget = this.renderTarget;
  9841. for (var i = 0; i < 6; i++) {
  9842. renderer.setRenderTarget(renderTarget, i);
  9843. renderer.clear(color, depth, stencil);
  9844. }
  9845. renderer.setRenderTarget(currentRenderTarget);
  9846. };
  9847. }
  9848. CubeCamera.prototype = Object.create(Object3D.prototype);
  9849. CubeCamera.prototype.constructor = CubeCamera;
  9850. /**
  9851. * @author alteredq / http://alteredqualia.com
  9852. * @author WestLangley / http://github.com/WestLangley
  9853. */
  9854. function WebGLRenderTargetCube(width, height, options) {
  9855. WebGLRenderTarget.call(this, width, height, options);
  9856. }
  9857. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  9858. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  9859. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  9860. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9861. this.texture.type = texture.type;
  9862. this.texture.format = texture.format;
  9863. this.texture.encoding = texture.encoding;
  9864. var scene = new Scene();
  9865. var shader = {
  9866. uniforms: {
  9867. tEquirect: {
  9868. value: null
  9869. }
  9870. },
  9871. 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'),
  9872. 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')
  9873. };
  9874. var material = new ShaderMaterial({
  9875. type: 'CubemapFromEquirect',
  9876. uniforms: cloneUniforms(shader.uniforms),
  9877. vertexShader: shader.vertexShader,
  9878. fragmentShader: shader.fragmentShader,
  9879. side: BackSide,
  9880. blending: NoBlending
  9881. });
  9882. material.uniforms.tEquirect.value = texture;
  9883. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9884. scene.add(mesh);
  9885. var camera = new CubeCamera(1, 10, 1);
  9886. camera.renderTarget = this;
  9887. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9888. camera.update(renderer, scene);
  9889. mesh.geometry.dispose();
  9890. mesh.material.dispose();
  9891. return this;
  9892. };
  9893. /**
  9894. * @author alteredq / http://alteredqualia.com/
  9895. */
  9896. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9897. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9898. this.image = {
  9899. data: data || null,
  9900. width: width || 1,
  9901. height: height || 1
  9902. };
  9903. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9904. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9905. this.generateMipmaps = false;
  9906. this.flipY = false;
  9907. this.unpackAlignment = 1;
  9908. this.needsUpdate = true;
  9909. }
  9910. DataTexture.prototype = Object.create(Texture.prototype);
  9911. DataTexture.prototype.constructor = DataTexture;
  9912. DataTexture.prototype.isDataTexture = true;
  9913. /**
  9914. * @author bhouston / http://clara.io
  9915. */
  9916. var _vector1 = new Vector3();
  9917. var _vector2 = new Vector3();
  9918. var _normalMatrix = new Matrix3();
  9919. function Plane(normal, constant) {
  9920. // normal is assumed to be normalized
  9921. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  9922. this.constant = constant !== undefined ? constant : 0;
  9923. }
  9924. Object.assign(Plane.prototype, {
  9925. isPlane: true,
  9926. set: function (normal, constant) {
  9927. this.normal.copy(normal);
  9928. this.constant = constant;
  9929. return this;
  9930. },
  9931. setComponents: function (x, y, z, w) {
  9932. this.normal.set(x, y, z);
  9933. this.constant = w;
  9934. return this;
  9935. },
  9936. setFromNormalAndCoplanarPoint: function (normal, point) {
  9937. this.normal.copy(normal);
  9938. this.constant = -point.dot(this.normal);
  9939. return this;
  9940. },
  9941. setFromCoplanarPoints: function (a, b, c) {
  9942. 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)?
  9943. this.setFromNormalAndCoplanarPoint(normal, a);
  9944. return this;
  9945. },
  9946. clone: function () {
  9947. return new this.constructor().copy(this);
  9948. },
  9949. copy: function (plane) {
  9950. this.normal.copy(plane.normal);
  9951. this.constant = plane.constant;
  9952. return this;
  9953. },
  9954. normalize: function () {
  9955. // Note: will lead to a divide by zero if the plane is invalid.
  9956. var inverseNormalLength = 1.0 / this.normal.length();
  9957. this.normal.multiplyScalar(inverseNormalLength);
  9958. this.constant *= inverseNormalLength;
  9959. return this;
  9960. },
  9961. negate: function () {
  9962. this.constant *= -1;
  9963. this.normal.negate();
  9964. return this;
  9965. },
  9966. distanceToPoint: function (point) {
  9967. return this.normal.dot(point) + this.constant;
  9968. },
  9969. distanceToSphere: function (sphere) {
  9970. return this.distanceToPoint(sphere.center) - sphere.radius;
  9971. },
  9972. projectPoint: function (point, target) {
  9973. if (target === undefined) {
  9974. console.warn('THREE.Plane: .projectPoint() target is now required');
  9975. target = new Vector3();
  9976. }
  9977. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  9978. },
  9979. intersectLine: function (line, target) {
  9980. if (target === undefined) {
  9981. console.warn('THREE.Plane: .intersectLine() target is now required');
  9982. target = new Vector3();
  9983. }
  9984. var direction = line.delta(_vector1);
  9985. var denominator = this.normal.dot(direction);
  9986. if (denominator === 0) {
  9987. // line is coplanar, return origin
  9988. if (this.distanceToPoint(line.start) === 0) {
  9989. return target.copy(line.start);
  9990. } // Unsure if this is the correct method to handle this case.
  9991. return undefined;
  9992. }
  9993. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  9994. if (t < 0 || t > 1) {
  9995. return undefined;
  9996. }
  9997. return target.copy(direction).multiplyScalar(t).add(line.start);
  9998. },
  9999. intersectsLine: function (line) {
  10000. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10001. var startSign = this.distanceToPoint(line.start);
  10002. var endSign = this.distanceToPoint(line.end);
  10003. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10004. },
  10005. intersectsBox: function (box) {
  10006. return box.intersectsPlane(this);
  10007. },
  10008. intersectsSphere: function (sphere) {
  10009. return sphere.intersectsPlane(this);
  10010. },
  10011. coplanarPoint: function (target) {
  10012. if (target === undefined) {
  10013. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10014. target = new Vector3();
  10015. }
  10016. return target.copy(this.normal).multiplyScalar(-this.constant);
  10017. },
  10018. applyMatrix4: function (matrix, optionalNormalMatrix) {
  10019. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10020. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10021. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10022. this.constant = -referencePoint.dot(normal);
  10023. return this;
  10024. },
  10025. translate: function (offset) {
  10026. this.constant -= offset.dot(this.normal);
  10027. return this;
  10028. },
  10029. equals: function (plane) {
  10030. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10031. }
  10032. });
  10033. /**
  10034. * @author mrdoob / http://mrdoob.com/
  10035. * @author alteredq / http://alteredqualia.com/
  10036. * @author bhouston / http://clara.io
  10037. */
  10038. var _sphere$1 = new Sphere();
  10039. var _vector$5 = new Vector3();
  10040. function Frustum(p0, p1, p2, p3, p4, p5) {
  10041. 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()];
  10042. }
  10043. Object.assign(Frustum.prototype, {
  10044. set: function (p0, p1, p2, p3, p4, p5) {
  10045. var planes = this.planes;
  10046. planes[0].copy(p0);
  10047. planes[1].copy(p1);
  10048. planes[2].copy(p2);
  10049. planes[3].copy(p3);
  10050. planes[4].copy(p4);
  10051. planes[5].copy(p5);
  10052. return this;
  10053. },
  10054. clone: function () {
  10055. return new this.constructor().copy(this);
  10056. },
  10057. copy: function (frustum) {
  10058. var planes = this.planes;
  10059. for (var i = 0; i < 6; i++) {
  10060. planes[i].copy(frustum.planes[i]);
  10061. }
  10062. return this;
  10063. },
  10064. setFromMatrix: function (m) {
  10065. var planes = this.planes;
  10066. var me = m.elements;
  10067. var me0 = me[0],
  10068. me1 = me[1],
  10069. me2 = me[2],
  10070. me3 = me[3];
  10071. var me4 = me[4],
  10072. me5 = me[5],
  10073. me6 = me[6],
  10074. me7 = me[7];
  10075. var me8 = me[8],
  10076. me9 = me[9],
  10077. me10 = me[10],
  10078. me11 = me[11];
  10079. var me12 = me[12],
  10080. me13 = me[13],
  10081. me14 = me[14],
  10082. me15 = me[15];
  10083. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  10084. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  10085. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  10086. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  10087. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  10088. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  10089. return this;
  10090. },
  10091. intersectsObject: function (object) {
  10092. var geometry = object.geometry;
  10093. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  10094. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  10095. return this.intersectsSphere(_sphere$1);
  10096. },
  10097. intersectsSprite: function (sprite) {
  10098. _sphere$1.center.set(0, 0, 0);
  10099. _sphere$1.radius = 0.7071067811865476;
  10100. _sphere$1.applyMatrix4(sprite.matrixWorld);
  10101. return this.intersectsSphere(_sphere$1);
  10102. },
  10103. intersectsSphere: function (sphere) {
  10104. var planes = this.planes;
  10105. var center = sphere.center;
  10106. var negRadius = -sphere.radius;
  10107. for (var i = 0; i < 6; i++) {
  10108. var distance = planes[i].distanceToPoint(center);
  10109. if (distance < negRadius) {
  10110. return false;
  10111. }
  10112. }
  10113. return true;
  10114. },
  10115. intersectsBox: function (box) {
  10116. var planes = this.planes;
  10117. for (var i = 0; i < 6; i++) {
  10118. var plane = planes[i]; // corner at max distance
  10119. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10120. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10121. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10122. if (plane.distanceToPoint(_vector$5) < 0) {
  10123. return false;
  10124. }
  10125. }
  10126. return true;
  10127. },
  10128. containsPoint: function (point) {
  10129. var planes = this.planes;
  10130. for (var i = 0; i < 6; i++) {
  10131. if (planes[i].distanceToPoint(point) < 0) {
  10132. return false;
  10133. }
  10134. }
  10135. return true;
  10136. }
  10137. });
  10138. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  10139. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  10140. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  10141. 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";
  10142. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  10143. var begin_vertex = "vec3 transformed = vec3( position );";
  10144. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  10145. 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";
  10146. 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";
  10147. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  10148. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  10149. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  10150. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  10151. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  10152. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10153. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10154. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  10155. 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}";
  10156. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif";
  10157. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\ttransformedNormal = mat3( instanceMatrix ) * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  10158. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  10159. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  10160. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  10161. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  10162. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  10163. 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 = min( floor( D ) / 255.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}";
  10164. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, 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_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\tenvColor = envMapTexelToLinear( envColor );\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";
  10165. 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";
  10166. 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";
  10167. 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";
  10168. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\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";
  10169. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  10170. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  10171. 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";
  10172. 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";
  10173. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif";
  10174. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  10175. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  10176. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = 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\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#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\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#endif";
  10177. 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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  10178. 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\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 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\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, 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";
  10179. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  10180. 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\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\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)";
  10181. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 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 = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  10182. 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}";
  10183. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = 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#pragma unroll_loop\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\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\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\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\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\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\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#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\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  10184. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * 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";
  10185. 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";
  10186. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 1.0 ? log2( vFragDepth ) * logDepthBufFC * 0.5 : gl_FragCoord.z;\n#endif";
  10187. 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";
  10188. 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";
  10189. 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";
  10190. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  10191. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  10192. var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif";
  10193. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  10194. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  10195. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  10196. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif";
  10197. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  10198. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  10199. 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#endif\n#endif\nvec3 geometryNormal = normal;";
  10200. 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\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, normalScale, normalMap );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  10201. 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, vec2 normalScale, in sampler2D normalMap ) {\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\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy *= normalScale;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tbool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\t\t\tmapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  10202. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  10203. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = clearcoatNormalScale * mapN.xy;\n\t\tclearcoatNormal = normalize( vTBN * mapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatNormalScale, clearcoatNormalMap );\n\t#endif\n#endif";
  10204. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  10205. 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 encodeHalfRGBA ( vec2 v ) {\n\tvec4 encoded = vec4( 0.0 );\n\tconst vec2 offset = vec2( 1.0 / 255.0, 0.0 );\n\tencoded.xy = vec2( v.x, fract( v.x * 255.0 ) );\n\tencoded.xy = encoded.xy - ( encoded.yy * offset );\n\tencoded.zw = vec2( v.y, fract( v.y * 255.0 ) );\n\tencoded.zw = encoded.zw - ( encoded.ww * offset );\n\treturn encoded;\n}\nvec2 decodeHalfRGBA( 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}";
  10206. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  10207. 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;";
  10208. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  10209. 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";
  10210. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  10211. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  10212. 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 decodeHalfRGBA( 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 texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\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 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\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\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";
  10213. 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";
  10214. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";
  10215. 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\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  10216. 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";
  10217. 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";
  10218. 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";
  10219. 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";
  10220. 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";
  10221. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  10222. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  10223. 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}";
  10224. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  10225. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  10226. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  10227. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  10228. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  10229. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  10230. 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";
  10231. 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}";
  10232. 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}";
  10233. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  10234. 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}";
  10235. 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>\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\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";
  10236. 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>\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}";
  10237. 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}";
  10238. 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}";
  10239. 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}";
  10240. 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}";
  10241. 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10242. 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\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  10243. 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 <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\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10244. 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}";
  10245. 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 <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}";
  10246. 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}";
  10247. 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 <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 <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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10248. 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 <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 <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}";
  10249. 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 <gradientmap_pars_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}";
  10250. 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}";
  10251. 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_normalmap_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}";
  10252. 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}";
  10253. 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}";
  10254. 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 <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}";
  10255. 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10256. 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}";
  10257. 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 <fog_fragment>\n}";
  10258. 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}";
  10259. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_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 <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}";
  10260. 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}";
  10261. var ShaderChunk = {
  10262. alphamap_fragment: alphamap_fragment,
  10263. alphamap_pars_fragment: alphamap_pars_fragment,
  10264. alphatest_fragment: alphatest_fragment,
  10265. aomap_fragment: aomap_fragment,
  10266. aomap_pars_fragment: aomap_pars_fragment,
  10267. begin_vertex: begin_vertex,
  10268. beginnormal_vertex: beginnormal_vertex,
  10269. bsdfs: bsdfs,
  10270. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10271. clipping_planes_fragment: clipping_planes_fragment,
  10272. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10273. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10274. clipping_planes_vertex: clipping_planes_vertex,
  10275. color_fragment: color_fragment,
  10276. color_pars_fragment: color_pars_fragment,
  10277. color_pars_vertex: color_pars_vertex,
  10278. color_vertex: color_vertex,
  10279. common: common,
  10280. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10281. defaultnormal_vertex: defaultnormal_vertex,
  10282. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10283. displacementmap_vertex: displacementmap_vertex,
  10284. emissivemap_fragment: emissivemap_fragment,
  10285. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10286. encodings_fragment: encodings_fragment,
  10287. encodings_pars_fragment: encodings_pars_fragment,
  10288. envmap_fragment: envmap_fragment,
  10289. envmap_common_pars_fragment: envmap_common_pars_fragment,
  10290. envmap_pars_fragment: envmap_pars_fragment,
  10291. envmap_pars_vertex: envmap_pars_vertex,
  10292. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  10293. envmap_vertex: envmap_vertex,
  10294. fog_vertex: fog_vertex,
  10295. fog_pars_vertex: fog_pars_vertex,
  10296. fog_fragment: fog_fragment,
  10297. fog_pars_fragment: fog_pars_fragment,
  10298. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10299. lightmap_fragment: lightmap_fragment,
  10300. lightmap_pars_fragment: lightmap_pars_fragment,
  10301. lights_lambert_vertex: lights_lambert_vertex,
  10302. lights_pars_begin: lights_pars_begin,
  10303. lights_phong_fragment: lights_phong_fragment,
  10304. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10305. lights_physical_fragment: lights_physical_fragment,
  10306. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10307. lights_fragment_begin: lights_fragment_begin,
  10308. lights_fragment_maps: lights_fragment_maps,
  10309. lights_fragment_end: lights_fragment_end,
  10310. logdepthbuf_fragment: logdepthbuf_fragment,
  10311. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10312. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10313. logdepthbuf_vertex: logdepthbuf_vertex,
  10314. map_fragment: map_fragment,
  10315. map_pars_fragment: map_pars_fragment,
  10316. map_particle_fragment: map_particle_fragment,
  10317. map_particle_pars_fragment: map_particle_pars_fragment,
  10318. metalnessmap_fragment: metalnessmap_fragment,
  10319. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10320. morphnormal_vertex: morphnormal_vertex,
  10321. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10322. morphtarget_vertex: morphtarget_vertex,
  10323. normal_fragment_begin: normal_fragment_begin,
  10324. normal_fragment_maps: normal_fragment_maps,
  10325. normalmap_pars_fragment: normalmap_pars_fragment,
  10326. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  10327. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  10328. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  10329. packing: packing,
  10330. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10331. project_vertex: project_vertex,
  10332. dithering_fragment: dithering_fragment,
  10333. dithering_pars_fragment: dithering_pars_fragment,
  10334. roughnessmap_fragment: roughnessmap_fragment,
  10335. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10336. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10337. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10338. shadowmap_vertex: shadowmap_vertex,
  10339. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10340. skinbase_vertex: skinbase_vertex,
  10341. skinning_pars_vertex: skinning_pars_vertex,
  10342. skinning_vertex: skinning_vertex,
  10343. skinnormal_vertex: skinnormal_vertex,
  10344. specularmap_fragment: specularmap_fragment,
  10345. specularmap_pars_fragment: specularmap_pars_fragment,
  10346. tonemapping_fragment: tonemapping_fragment,
  10347. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10348. uv_pars_fragment: uv_pars_fragment,
  10349. uv_pars_vertex: uv_pars_vertex,
  10350. uv_vertex: uv_vertex,
  10351. uv2_pars_fragment: uv2_pars_fragment,
  10352. uv2_pars_vertex: uv2_pars_vertex,
  10353. uv2_vertex: uv2_vertex,
  10354. worldpos_vertex: worldpos_vertex,
  10355. background_frag: background_frag,
  10356. background_vert: background_vert,
  10357. cube_frag: cube_frag,
  10358. cube_vert: cube_vert,
  10359. depth_frag: depth_frag,
  10360. depth_vert: depth_vert,
  10361. distanceRGBA_frag: distanceRGBA_frag,
  10362. distanceRGBA_vert: distanceRGBA_vert,
  10363. equirect_frag: equirect_frag,
  10364. equirect_vert: equirect_vert,
  10365. linedashed_frag: linedashed_frag,
  10366. linedashed_vert: linedashed_vert,
  10367. meshbasic_frag: meshbasic_frag,
  10368. meshbasic_vert: meshbasic_vert,
  10369. meshlambert_frag: meshlambert_frag,
  10370. meshlambert_vert: meshlambert_vert,
  10371. meshmatcap_frag: meshmatcap_frag,
  10372. meshmatcap_vert: meshmatcap_vert,
  10373. meshphong_frag: meshphong_frag,
  10374. meshphong_vert: meshphong_vert,
  10375. meshphysical_frag: meshphysical_frag,
  10376. meshphysical_vert: meshphysical_vert,
  10377. normal_frag: normal_frag,
  10378. normal_vert: normal_vert,
  10379. points_frag: points_frag,
  10380. points_vert: points_vert,
  10381. shadow_frag: shadow_frag,
  10382. shadow_vert: shadow_vert,
  10383. sprite_frag: sprite_frag,
  10384. sprite_vert: sprite_vert
  10385. };
  10386. /**
  10387. * Uniforms library for shared webgl shaders
  10388. */
  10389. exports.ShaderChunk = ShaderChunk;
  10390. var UniformsLib = {
  10391. common: {
  10392. diffuse: {
  10393. value: new Color(0xeeeeee)
  10394. },
  10395. opacity: {
  10396. value: 1.0
  10397. },
  10398. map: {
  10399. value: null
  10400. },
  10401. uvTransform: {
  10402. value: new Matrix3()
  10403. },
  10404. alphaMap: {
  10405. value: null
  10406. }
  10407. },
  10408. specularmap: {
  10409. specularMap: {
  10410. value: null
  10411. }
  10412. },
  10413. envmap: {
  10414. envMap: {
  10415. value: null
  10416. },
  10417. flipEnvMap: {
  10418. value: -1
  10419. },
  10420. reflectivity: {
  10421. value: 1.0
  10422. },
  10423. refractionRatio: {
  10424. value: 0.98
  10425. },
  10426. maxMipLevel: {
  10427. value: 0
  10428. }
  10429. },
  10430. aomap: {
  10431. aoMap: {
  10432. value: null
  10433. },
  10434. aoMapIntensity: {
  10435. value: 1
  10436. }
  10437. },
  10438. lightmap: {
  10439. lightMap: {
  10440. value: null
  10441. },
  10442. lightMapIntensity: {
  10443. value: 1
  10444. }
  10445. },
  10446. emissivemap: {
  10447. emissiveMap: {
  10448. value: null
  10449. }
  10450. },
  10451. bumpmap: {
  10452. bumpMap: {
  10453. value: null
  10454. },
  10455. bumpScale: {
  10456. value: 1
  10457. }
  10458. },
  10459. normalmap: {
  10460. normalMap: {
  10461. value: null
  10462. },
  10463. normalScale: {
  10464. value: new Vector2(1, 1)
  10465. }
  10466. },
  10467. displacementmap: {
  10468. displacementMap: {
  10469. value: null
  10470. },
  10471. displacementScale: {
  10472. value: 1
  10473. },
  10474. displacementBias: {
  10475. value: 0
  10476. }
  10477. },
  10478. roughnessmap: {
  10479. roughnessMap: {
  10480. value: null
  10481. }
  10482. },
  10483. metalnessmap: {
  10484. metalnessMap: {
  10485. value: null
  10486. }
  10487. },
  10488. gradientmap: {
  10489. gradientMap: {
  10490. value: null
  10491. }
  10492. },
  10493. fog: {
  10494. fogDensity: {
  10495. value: 0.00025
  10496. },
  10497. fogNear: {
  10498. value: 1
  10499. },
  10500. fogFar: {
  10501. value: 2000
  10502. },
  10503. fogColor: {
  10504. value: new Color(0xffffff)
  10505. }
  10506. },
  10507. lights: {
  10508. ambientLightColor: {
  10509. value: []
  10510. },
  10511. lightProbe: {
  10512. value: []
  10513. },
  10514. directionalLights: {
  10515. value: [],
  10516. properties: {
  10517. direction: {},
  10518. color: {},
  10519. shadow: {},
  10520. shadowBias: {},
  10521. shadowRadius: {},
  10522. shadowMapSize: {}
  10523. }
  10524. },
  10525. directionalShadowMap: {
  10526. value: []
  10527. },
  10528. directionalShadowMatrix: {
  10529. value: []
  10530. },
  10531. spotLights: {
  10532. value: [],
  10533. properties: {
  10534. color: {},
  10535. position: {},
  10536. direction: {},
  10537. distance: {},
  10538. coneCos: {},
  10539. penumbraCos: {},
  10540. decay: {},
  10541. shadow: {},
  10542. shadowBias: {},
  10543. shadowRadius: {},
  10544. shadowMapSize: {}
  10545. }
  10546. },
  10547. spotShadowMap: {
  10548. value: []
  10549. },
  10550. spotShadowMatrix: {
  10551. value: []
  10552. },
  10553. pointLights: {
  10554. value: [],
  10555. properties: {
  10556. color: {},
  10557. position: {},
  10558. decay: {},
  10559. distance: {},
  10560. shadow: {},
  10561. shadowBias: {},
  10562. shadowRadius: {},
  10563. shadowMapSize: {},
  10564. shadowCameraNear: {},
  10565. shadowCameraFar: {}
  10566. }
  10567. },
  10568. pointShadowMap: {
  10569. value: []
  10570. },
  10571. pointShadowMatrix: {
  10572. value: []
  10573. },
  10574. hemisphereLights: {
  10575. value: [],
  10576. properties: {
  10577. direction: {},
  10578. skyColor: {},
  10579. groundColor: {}
  10580. }
  10581. },
  10582. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10583. rectAreaLights: {
  10584. value: [],
  10585. properties: {
  10586. color: {},
  10587. position: {},
  10588. width: {},
  10589. height: {}
  10590. }
  10591. }
  10592. },
  10593. points: {
  10594. diffuse: {
  10595. value: new Color(0xeeeeee)
  10596. },
  10597. opacity: {
  10598. value: 1.0
  10599. },
  10600. size: {
  10601. value: 1.0
  10602. },
  10603. scale: {
  10604. value: 1.0
  10605. },
  10606. map: {
  10607. value: null
  10608. },
  10609. uvTransform: {
  10610. value: new Matrix3()
  10611. }
  10612. },
  10613. sprite: {
  10614. diffuse: {
  10615. value: new Color(0xeeeeee)
  10616. },
  10617. opacity: {
  10618. value: 1.0
  10619. },
  10620. center: {
  10621. value: new Vector2(0.5, 0.5)
  10622. },
  10623. rotation: {
  10624. value: 0.0
  10625. },
  10626. map: {
  10627. value: null
  10628. },
  10629. uvTransform: {
  10630. value: new Matrix3()
  10631. }
  10632. }
  10633. };
  10634. /**
  10635. * @author alteredq / http://alteredqualia.com/
  10636. * @author mrdoob / http://mrdoob.com/
  10637. * @author mikael emtinger / http://gomo.se/
  10638. */
  10639. exports.UniformsLib = UniformsLib;
  10640. var ShaderLib = {
  10641. basic: {
  10642. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  10643. vertexShader: ShaderChunk.meshbasic_vert,
  10644. fragmentShader: ShaderChunk.meshbasic_frag
  10645. },
  10646. lambert: {
  10647. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  10648. emissive: {
  10649. value: new Color(0x000000)
  10650. }
  10651. }]),
  10652. vertexShader: ShaderChunk.meshlambert_vert,
  10653. fragmentShader: ShaderChunk.meshlambert_frag
  10654. },
  10655. phong: {
  10656. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  10657. emissive: {
  10658. value: new Color(0x000000)
  10659. },
  10660. specular: {
  10661. value: new Color(0x111111)
  10662. },
  10663. shininess: {
  10664. value: 30
  10665. }
  10666. }]),
  10667. vertexShader: ShaderChunk.meshphong_vert,
  10668. fragmentShader: ShaderChunk.meshphong_frag
  10669. },
  10670. standard: {
  10671. 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, {
  10672. emissive: {
  10673. value: new Color(0x000000)
  10674. },
  10675. roughness: {
  10676. value: 0.5
  10677. },
  10678. metalness: {
  10679. value: 0.5
  10680. },
  10681. envMapIntensity: {
  10682. value: 1
  10683. } // temporary
  10684. }]),
  10685. vertexShader: ShaderChunk.meshphysical_vert,
  10686. fragmentShader: ShaderChunk.meshphysical_frag
  10687. },
  10688. matcap: {
  10689. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  10690. matcap: {
  10691. value: null
  10692. }
  10693. }]),
  10694. vertexShader: ShaderChunk.meshmatcap_vert,
  10695. fragmentShader: ShaderChunk.meshmatcap_frag
  10696. },
  10697. points: {
  10698. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  10699. vertexShader: ShaderChunk.points_vert,
  10700. fragmentShader: ShaderChunk.points_frag
  10701. },
  10702. dashed: {
  10703. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  10704. scale: {
  10705. value: 1
  10706. },
  10707. dashSize: {
  10708. value: 1
  10709. },
  10710. totalSize: {
  10711. value: 2
  10712. }
  10713. }]),
  10714. vertexShader: ShaderChunk.linedashed_vert,
  10715. fragmentShader: ShaderChunk.linedashed_frag
  10716. },
  10717. depth: {
  10718. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  10719. vertexShader: ShaderChunk.depth_vert,
  10720. fragmentShader: ShaderChunk.depth_frag
  10721. },
  10722. normal: {
  10723. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10724. opacity: {
  10725. value: 1.0
  10726. }
  10727. }]),
  10728. vertexShader: ShaderChunk.normal_vert,
  10729. fragmentShader: ShaderChunk.normal_frag
  10730. },
  10731. sprite: {
  10732. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10733. vertexShader: ShaderChunk.sprite_vert,
  10734. fragmentShader: ShaderChunk.sprite_frag
  10735. },
  10736. background: {
  10737. uniforms: {
  10738. uvTransform: {
  10739. value: new Matrix3()
  10740. },
  10741. t2D: {
  10742. value: null
  10743. }
  10744. },
  10745. vertexShader: ShaderChunk.background_vert,
  10746. fragmentShader: ShaderChunk.background_frag
  10747. },
  10748. /* -------------------------------------------------------------------------
  10749. // Cube map shader
  10750. ------------------------------------------------------------------------- */
  10751. cube: {
  10752. uniforms: {
  10753. tCube: {
  10754. value: null
  10755. },
  10756. tFlip: {
  10757. value: -1
  10758. },
  10759. opacity: {
  10760. value: 1.0
  10761. }
  10762. },
  10763. vertexShader: ShaderChunk.cube_vert,
  10764. fragmentShader: ShaderChunk.cube_frag
  10765. },
  10766. equirect: {
  10767. uniforms: {
  10768. tEquirect: {
  10769. value: null
  10770. }
  10771. },
  10772. vertexShader: ShaderChunk.equirect_vert,
  10773. fragmentShader: ShaderChunk.equirect_frag
  10774. },
  10775. distanceRGBA: {
  10776. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10777. referencePosition: {
  10778. value: new Vector3()
  10779. },
  10780. nearDistance: {
  10781. value: 1
  10782. },
  10783. farDistance: {
  10784. value: 1000
  10785. }
  10786. }]),
  10787. vertexShader: ShaderChunk.distanceRGBA_vert,
  10788. fragmentShader: ShaderChunk.distanceRGBA_frag
  10789. },
  10790. shadow: {
  10791. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10792. color: {
  10793. value: new Color(0x00000)
  10794. },
  10795. opacity: {
  10796. value: 1.0
  10797. }
  10798. }]),
  10799. vertexShader: ShaderChunk.shadow_vert,
  10800. fragmentShader: ShaderChunk.shadow_frag
  10801. }
  10802. };
  10803. exports.ShaderLib = ShaderLib;
  10804. ShaderLib.physical = {
  10805. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10806. transparency: {
  10807. value: 0
  10808. },
  10809. clearcoat: {
  10810. value: 0
  10811. },
  10812. clearcoatRoughness: {
  10813. value: 0
  10814. },
  10815. sheen: {
  10816. value: new Color(0x000000)
  10817. },
  10818. clearcoatNormalScale: {
  10819. value: new Vector2(1, 1)
  10820. },
  10821. clearcoatNormalMap: {
  10822. value: null
  10823. }
  10824. }]),
  10825. vertexShader: ShaderChunk.meshphysical_vert,
  10826. fragmentShader: ShaderChunk.meshphysical_frag
  10827. };
  10828. /**
  10829. * @author mrdoob / http://mrdoob.com/
  10830. */
  10831. function WebGLAnimation() {
  10832. var context = null;
  10833. var isAnimating = false;
  10834. var animationLoop = null;
  10835. function onAnimationFrame(time, frame) {
  10836. if (isAnimating === false) return;
  10837. animationLoop(time, frame);
  10838. context.requestAnimationFrame(onAnimationFrame);
  10839. }
  10840. return {
  10841. start: function () {
  10842. if (isAnimating === true) return;
  10843. if (animationLoop === null) return;
  10844. context.requestAnimationFrame(onAnimationFrame);
  10845. isAnimating = true;
  10846. },
  10847. stop: function () {
  10848. isAnimating = false;
  10849. },
  10850. setAnimationLoop: function (callback) {
  10851. animationLoop = callback;
  10852. },
  10853. setContext: function (value) {
  10854. context = value;
  10855. }
  10856. };
  10857. }
  10858. /**
  10859. * @author mrdoob / http://mrdoob.com/
  10860. */
  10861. function WebGLAttributes(gl) {
  10862. var buffers = new WeakMap();
  10863. function createBuffer(attribute, bufferType) {
  10864. var array = attribute.array;
  10865. var usage = attribute.dynamic ? 35048 : 35044;
  10866. var buffer = gl.createBuffer();
  10867. gl.bindBuffer(bufferType, buffer);
  10868. gl.bufferData(bufferType, array, usage);
  10869. attribute.onUploadCallback();
  10870. var type = 5126;
  10871. if (array instanceof Float32Array) {
  10872. type = 5126;
  10873. } else if (array instanceof Float64Array) {
  10874. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  10875. } else if (array instanceof Uint16Array) {
  10876. type = 5123;
  10877. } else if (array instanceof Int16Array) {
  10878. type = 5122;
  10879. } else if (array instanceof Uint32Array) {
  10880. type = 5125;
  10881. } else if (array instanceof Int32Array) {
  10882. type = 5124;
  10883. } else if (array instanceof Int8Array) {
  10884. type = 5120;
  10885. } else if (array instanceof Uint8Array) {
  10886. type = 5121;
  10887. }
  10888. return {
  10889. buffer: buffer,
  10890. type: type,
  10891. bytesPerElement: array.BYTES_PER_ELEMENT,
  10892. version: attribute.version
  10893. };
  10894. }
  10895. function updateBuffer(buffer, attribute, bufferType) {
  10896. var array = attribute.array;
  10897. var updateRange = attribute.updateRange;
  10898. gl.bindBuffer(bufferType, buffer);
  10899. if (attribute.dynamic === false) {
  10900. gl.bufferData(bufferType, array, 35044);
  10901. } else if (updateRange.count === -1) {
  10902. // Not using update ranges
  10903. gl.bufferSubData(bufferType, 0, array);
  10904. } else if (updateRange.count === 0) {
  10905. console.error('THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.');
  10906. } else {
  10907. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  10908. updateRange.count = -1; // reset range
  10909. }
  10910. } //
  10911. function get(attribute) {
  10912. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10913. return buffers.get(attribute);
  10914. }
  10915. function remove(attribute) {
  10916. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10917. var data = buffers.get(attribute);
  10918. if (data) {
  10919. gl.deleteBuffer(data.buffer);
  10920. buffers.delete(attribute);
  10921. }
  10922. }
  10923. function update(attribute, bufferType) {
  10924. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10925. var data = buffers.get(attribute);
  10926. if (data === undefined) {
  10927. buffers.set(attribute, createBuffer(attribute, bufferType));
  10928. } else if (data.version < attribute.version) {
  10929. updateBuffer(data.buffer, attribute, bufferType);
  10930. data.version = attribute.version;
  10931. }
  10932. }
  10933. return {
  10934. get: get,
  10935. remove: remove,
  10936. update: update
  10937. };
  10938. }
  10939. /**
  10940. * @author mrdoob / http://mrdoob.com/
  10941. * @author Mugen87 / https://github.com/Mugen87
  10942. */
  10943. // PlaneGeometry
  10944. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  10945. Geometry.call(this);
  10946. this.type = 'PlaneGeometry';
  10947. this.parameters = {
  10948. width: width,
  10949. height: height,
  10950. widthSegments: widthSegments,
  10951. heightSegments: heightSegments
  10952. };
  10953. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  10954. this.mergeVertices();
  10955. }
  10956. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  10957. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  10958. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  10959. BufferGeometry.call(this);
  10960. this.type = 'PlaneBufferGeometry';
  10961. this.parameters = {
  10962. width: width,
  10963. height: height,
  10964. widthSegments: widthSegments,
  10965. heightSegments: heightSegments
  10966. };
  10967. width = width || 1;
  10968. height = height || 1;
  10969. var width_half = width / 2;
  10970. var height_half = height / 2;
  10971. var gridX = Math.floor(widthSegments) || 1;
  10972. var gridY = Math.floor(heightSegments) || 1;
  10973. var gridX1 = gridX + 1;
  10974. var gridY1 = gridY + 1;
  10975. var segment_width = width / gridX;
  10976. var segment_height = height / gridY;
  10977. var ix, iy; // buffers
  10978. var indices = [];
  10979. var vertices = [];
  10980. var normals = [];
  10981. var uvs = []; // generate vertices, normals and uvs
  10982. for (iy = 0; iy < gridY1; iy++) {
  10983. var y = iy * segment_height - height_half;
  10984. for (ix = 0; ix < gridX1; ix++) {
  10985. var x = ix * segment_width - width_half;
  10986. vertices.push(x, -y, 0);
  10987. normals.push(0, 0, 1);
  10988. uvs.push(ix / gridX);
  10989. uvs.push(1 - iy / gridY);
  10990. }
  10991. } // indices
  10992. for (iy = 0; iy < gridY; iy++) {
  10993. for (ix = 0; ix < gridX; ix++) {
  10994. var a = ix + gridX1 * iy;
  10995. var b = ix + gridX1 * (iy + 1);
  10996. var c = ix + 1 + gridX1 * (iy + 1);
  10997. var d = ix + 1 + gridX1 * iy; // faces
  10998. indices.push(a, b, d);
  10999. indices.push(b, c, d);
  11000. }
  11001. } // build geometry
  11002. this.setIndex(indices);
  11003. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  11004. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  11005. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  11006. }
  11007. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  11008. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11009. /**
  11010. * @author mrdoob / http://mrdoob.com/
  11011. */
  11012. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  11013. var clearColor = new Color(0x000000);
  11014. var clearAlpha = 0;
  11015. var planeMesh;
  11016. var boxMesh; // Store the current background texture and its `version`
  11017. // so we can recompile the material accordingly.
  11018. var currentBackground = null;
  11019. var currentBackgroundVersion = 0;
  11020. function render(renderList, scene, camera, forceClear) {
  11021. var background = scene.background; // Ignore background in AR
  11022. // TODO: Reconsider this.
  11023. var vr = renderer.vr;
  11024. var session = vr.getSession && vr.getSession();
  11025. if (session && session.environmentBlendMode === 'additive') {
  11026. background = null;
  11027. }
  11028. if (background === null) {
  11029. setClear(clearColor, clearAlpha);
  11030. currentBackground = null;
  11031. currentBackgroundVersion = 0;
  11032. } else if (background && background.isColor) {
  11033. setClear(background, 1);
  11034. forceClear = true;
  11035. currentBackground = null;
  11036. currentBackgroundVersion = 0;
  11037. }
  11038. if (renderer.autoClear || forceClear) {
  11039. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  11040. }
  11041. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  11042. if (boxMesh === undefined) {
  11043. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  11044. type: 'BackgroundCubeMaterial',
  11045. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  11046. vertexShader: ShaderLib.cube.vertexShader,
  11047. fragmentShader: ShaderLib.cube.fragmentShader,
  11048. side: BackSide,
  11049. depthTest: false,
  11050. depthWrite: false,
  11051. fog: false
  11052. }));
  11053. boxMesh.geometry.removeAttribute('normal');
  11054. boxMesh.geometry.removeAttribute('uv');
  11055. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  11056. this.matrixWorld.copyPosition(camera.matrixWorld);
  11057. }; // enable code injection for non-built-in material
  11058. Object.defineProperty(boxMesh.material, 'map', {
  11059. get: function () {
  11060. return this.uniforms.tCube.value;
  11061. }
  11062. });
  11063. objects.update(boxMesh);
  11064. }
  11065. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  11066. boxMesh.material.uniforms.tCube.value = texture;
  11067. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  11068. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  11069. boxMesh.material.needsUpdate = true;
  11070. currentBackground = background;
  11071. currentBackgroundVersion = texture.version;
  11072. } // push to the pre-sorted opaque render list
  11073. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  11074. } else if (background && background.isTexture) {
  11075. if (planeMesh === undefined) {
  11076. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  11077. type: 'BackgroundMaterial',
  11078. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  11079. vertexShader: ShaderLib.background.vertexShader,
  11080. fragmentShader: ShaderLib.background.fragmentShader,
  11081. side: FrontSide,
  11082. depthTest: false,
  11083. depthWrite: false,
  11084. fog: false
  11085. }));
  11086. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  11087. Object.defineProperty(planeMesh.material, 'map', {
  11088. get: function () {
  11089. return this.uniforms.t2D.value;
  11090. }
  11091. });
  11092. objects.update(planeMesh);
  11093. }
  11094. planeMesh.material.uniforms.t2D.value = background;
  11095. if (background.matrixAutoUpdate === true) {
  11096. background.updateMatrix();
  11097. }
  11098. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  11099. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  11100. planeMesh.material.needsUpdate = true;
  11101. currentBackground = background;
  11102. currentBackgroundVersion = background.version;
  11103. } // push to the pre-sorted opaque render list
  11104. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  11105. }
  11106. }
  11107. function setClear(color, alpha) {
  11108. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  11109. }
  11110. return {
  11111. getClearColor: function () {
  11112. return clearColor;
  11113. },
  11114. setClearColor: function (color, alpha) {
  11115. clearColor.set(color);
  11116. clearAlpha = alpha !== undefined ? alpha : 1;
  11117. setClear(clearColor, clearAlpha);
  11118. },
  11119. getClearAlpha: function () {
  11120. return clearAlpha;
  11121. },
  11122. setClearAlpha: function (alpha) {
  11123. clearAlpha = alpha;
  11124. setClear(clearColor, clearAlpha);
  11125. },
  11126. render: render
  11127. };
  11128. }
  11129. /**
  11130. * @author mrdoob / http://mrdoob.com/
  11131. */
  11132. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  11133. var mode;
  11134. function setMode(value) {
  11135. mode = value;
  11136. }
  11137. function render(start, count) {
  11138. gl.drawArrays(mode, start, count);
  11139. info.update(count, mode);
  11140. }
  11141. function renderInstances(geometry, start, count, primcount) {
  11142. if (primcount === 0) return;
  11143. var extension, methodName;
  11144. if (capabilities.isWebGL2) {
  11145. extension = gl;
  11146. methodName = 'drawArraysInstanced';
  11147. } else {
  11148. extension = extensions.get('ANGLE_instanced_arrays');
  11149. methodName = 'drawArraysInstancedANGLE';
  11150. if (extension === null) {
  11151. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11152. return;
  11153. }
  11154. }
  11155. extension[methodName](mode, start, count, primcount);
  11156. info.update(count, mode, primcount);
  11157. } //
  11158. this.setMode = setMode;
  11159. this.render = render;
  11160. this.renderInstances = renderInstances;
  11161. }
  11162. /**
  11163. * @author mrdoob / http://mrdoob.com/
  11164. */
  11165. function WebGLCapabilities(gl, extensions, parameters) {
  11166. var maxAnisotropy;
  11167. function getMaxAnisotropy() {
  11168. if (maxAnisotropy !== undefined) return maxAnisotropy;
  11169. var extension = extensions.get('EXT_texture_filter_anisotropic');
  11170. if (extension !== null) {
  11171. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  11172. } else {
  11173. maxAnisotropy = 0;
  11174. }
  11175. return maxAnisotropy;
  11176. }
  11177. function getMaxPrecision(precision) {
  11178. if (precision === 'highp') {
  11179. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  11180. return 'highp';
  11181. }
  11182. precision = 'mediump';
  11183. }
  11184. if (precision === 'mediump') {
  11185. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  11186. return 'mediump';
  11187. }
  11188. }
  11189. return 'lowp';
  11190. }
  11191. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  11192. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11193. var maxPrecision = getMaxPrecision(precision);
  11194. if (maxPrecision !== precision) {
  11195. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  11196. precision = maxPrecision;
  11197. }
  11198. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  11199. var maxTextures = gl.getParameter(34930);
  11200. var maxVertexTextures = gl.getParameter(35660);
  11201. var maxTextureSize = gl.getParameter(3379);
  11202. var maxCubemapSize = gl.getParameter(34076);
  11203. var maxAttributes = gl.getParameter(34921);
  11204. var maxVertexUniforms = gl.getParameter(36347);
  11205. var maxVaryings = gl.getParameter(36348);
  11206. var maxFragmentUniforms = gl.getParameter(36349);
  11207. var vertexTextures = maxVertexTextures > 0;
  11208. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  11209. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11210. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  11211. return {
  11212. isWebGL2: isWebGL2,
  11213. getMaxAnisotropy: getMaxAnisotropy,
  11214. getMaxPrecision: getMaxPrecision,
  11215. precision: precision,
  11216. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11217. maxTextures: maxTextures,
  11218. maxVertexTextures: maxVertexTextures,
  11219. maxTextureSize: maxTextureSize,
  11220. maxCubemapSize: maxCubemapSize,
  11221. maxAttributes: maxAttributes,
  11222. maxVertexUniforms: maxVertexUniforms,
  11223. maxVaryings: maxVaryings,
  11224. maxFragmentUniforms: maxFragmentUniforms,
  11225. vertexTextures: vertexTextures,
  11226. floatFragmentTextures: floatFragmentTextures,
  11227. floatVertexTextures: floatVertexTextures,
  11228. maxSamples: maxSamples
  11229. };
  11230. }
  11231. /**
  11232. * @author tschw
  11233. */
  11234. function WebGLClipping() {
  11235. var scope = this,
  11236. globalState = null,
  11237. numGlobalPlanes = 0,
  11238. localClippingEnabled = false,
  11239. renderingShadows = false,
  11240. plane = new Plane(),
  11241. viewNormalMatrix = new Matrix3(),
  11242. uniform = {
  11243. value: null,
  11244. needsUpdate: false
  11245. };
  11246. this.uniform = uniform;
  11247. this.numPlanes = 0;
  11248. this.numIntersection = 0;
  11249. this.init = function (planes, enableLocalClipping, camera) {
  11250. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  11251. // run another frame in order to reset the state:
  11252. numGlobalPlanes !== 0 || localClippingEnabled;
  11253. localClippingEnabled = enableLocalClipping;
  11254. globalState = projectPlanes(planes, camera, 0);
  11255. numGlobalPlanes = planes.length;
  11256. return enabled;
  11257. };
  11258. this.beginShadows = function () {
  11259. renderingShadows = true;
  11260. projectPlanes(null);
  11261. };
  11262. this.endShadows = function () {
  11263. renderingShadows = false;
  11264. resetGlobalState();
  11265. };
  11266. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  11267. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  11268. // there's no local clipping
  11269. if (renderingShadows) {
  11270. // there's no global clipping
  11271. projectPlanes(null);
  11272. } else {
  11273. resetGlobalState();
  11274. }
  11275. } else {
  11276. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11277. lGlobal = nGlobal * 4,
  11278. dstArray = cache.clippingState || null;
  11279. uniform.value = dstArray; // ensure unique state
  11280. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  11281. for (var i = 0; i !== lGlobal; ++i) {
  11282. dstArray[i] = globalState[i];
  11283. }
  11284. cache.clippingState = dstArray;
  11285. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11286. this.numPlanes += nGlobal;
  11287. }
  11288. };
  11289. function resetGlobalState() {
  11290. if (uniform.value !== globalState) {
  11291. uniform.value = globalState;
  11292. uniform.needsUpdate = numGlobalPlanes > 0;
  11293. }
  11294. scope.numPlanes = numGlobalPlanes;
  11295. scope.numIntersection = 0;
  11296. }
  11297. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  11298. var nPlanes = planes !== null ? planes.length : 0,
  11299. dstArray = null;
  11300. if (nPlanes !== 0) {
  11301. dstArray = uniform.value;
  11302. if (skipTransform !== true || dstArray === null) {
  11303. var flatSize = dstOffset + nPlanes * 4,
  11304. viewMatrix = camera.matrixWorldInverse;
  11305. viewNormalMatrix.getNormalMatrix(viewMatrix);
  11306. if (dstArray === null || dstArray.length < flatSize) {
  11307. dstArray = new Float32Array(flatSize);
  11308. }
  11309. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  11310. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  11311. plane.normal.toArray(dstArray, i4);
  11312. dstArray[i4 + 3] = plane.constant;
  11313. }
  11314. }
  11315. uniform.value = dstArray;
  11316. uniform.needsUpdate = true;
  11317. }
  11318. scope.numPlanes = nPlanes;
  11319. return dstArray;
  11320. }
  11321. }
  11322. /**
  11323. * @author mrdoob / http://mrdoob.com/
  11324. */
  11325. function WebGLExtensions(gl) {
  11326. var extensions = {};
  11327. return {
  11328. get: function (name) {
  11329. if (extensions[name] !== undefined) {
  11330. return extensions[name];
  11331. }
  11332. var extension;
  11333. switch (name) {
  11334. case 'WEBGL_depth_texture':
  11335. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  11336. break;
  11337. case 'EXT_texture_filter_anisotropic':
  11338. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  11339. break;
  11340. case 'WEBGL_compressed_texture_s3tc':
  11341. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11342. break;
  11343. case 'WEBGL_compressed_texture_pvrtc':
  11344. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11345. break;
  11346. default:
  11347. extension = gl.getExtension(name);
  11348. }
  11349. if (extension === null) {
  11350. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  11351. }
  11352. extensions[name] = extension;
  11353. return extension;
  11354. }
  11355. };
  11356. }
  11357. /**
  11358. * @author mrdoob / http://mrdoob.com/
  11359. */
  11360. function WebGLGeometries(gl, attributes, info) {
  11361. var geometries = new WeakMap();
  11362. var wireframeAttributes = new WeakMap();
  11363. function onGeometryDispose(event) {
  11364. var geometry = event.target;
  11365. var buffergeometry = geometries.get(geometry);
  11366. if (buffergeometry.index !== null) {
  11367. attributes.remove(buffergeometry.index);
  11368. }
  11369. for (var name in buffergeometry.attributes) {
  11370. attributes.remove(buffergeometry.attributes[name]);
  11371. }
  11372. geometry.removeEventListener('dispose', onGeometryDispose);
  11373. geometries.delete(geometry);
  11374. var attribute = wireframeAttributes.get(buffergeometry);
  11375. if (attribute) {
  11376. attributes.remove(attribute);
  11377. wireframeAttributes.delete(buffergeometry);
  11378. } //
  11379. info.memory.geometries--;
  11380. }
  11381. function get(object, geometry) {
  11382. var buffergeometry = geometries.get(geometry);
  11383. if (buffergeometry) return buffergeometry;
  11384. geometry.addEventListener('dispose', onGeometryDispose);
  11385. if (geometry.isBufferGeometry) {
  11386. buffergeometry = geometry;
  11387. } else if (geometry.isGeometry) {
  11388. if (geometry._bufferGeometry === undefined) {
  11389. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  11390. }
  11391. buffergeometry = geometry._bufferGeometry;
  11392. }
  11393. geometries.set(geometry, buffergeometry);
  11394. info.memory.geometries++;
  11395. return buffergeometry;
  11396. }
  11397. function update(geometry) {
  11398. var index = geometry.index;
  11399. var geometryAttributes = geometry.attributes;
  11400. if (index !== null) {
  11401. attributes.update(index, 34963);
  11402. }
  11403. for (var name in geometryAttributes) {
  11404. attributes.update(geometryAttributes[name], 34962);
  11405. } // morph targets
  11406. var morphAttributes = geometry.morphAttributes;
  11407. for (var name in morphAttributes) {
  11408. var array = morphAttributes[name];
  11409. for (var i = 0, l = array.length; i < l; i++) {
  11410. attributes.update(array[i], 34962);
  11411. }
  11412. }
  11413. }
  11414. function updateWireframeAttribute(geometry) {
  11415. var indices = [];
  11416. var geometryIndex = geometry.index;
  11417. var geometryPosition = geometry.attributes.position;
  11418. var version = 0;
  11419. if (geometryIndex !== null) {
  11420. var array = geometryIndex.array;
  11421. version = geometryIndex.version;
  11422. for (var i = 0, l = array.length; i < l; i += 3) {
  11423. var a = array[i + 0];
  11424. var b = array[i + 1];
  11425. var c = array[i + 2];
  11426. indices.push(a, b, b, c, c, a);
  11427. }
  11428. } else {
  11429. var array = geometryPosition.array;
  11430. version = geometryPosition.version;
  11431. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  11432. var a = i + 0;
  11433. var b = i + 1;
  11434. var c = i + 2;
  11435. indices.push(a, b, b, c, c, a);
  11436. }
  11437. }
  11438. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  11439. attribute.version = version;
  11440. attributes.update(attribute, 34963); //
  11441. var previousAttribute = wireframeAttributes.get(geometry);
  11442. if (previousAttribute) attributes.remove(previousAttribute); //
  11443. wireframeAttributes.set(geometry, attribute);
  11444. }
  11445. function getWireframeAttribute(geometry) {
  11446. var currentAttribute = wireframeAttributes.get(geometry);
  11447. if (currentAttribute) {
  11448. var geometryIndex = geometry.index;
  11449. if (geometryIndex !== null) {
  11450. // if the attribute is obsolete, create a new one
  11451. if (currentAttribute.version < geometryIndex.version) {
  11452. updateWireframeAttribute(geometry);
  11453. }
  11454. }
  11455. } else {
  11456. updateWireframeAttribute(geometry);
  11457. }
  11458. return wireframeAttributes.get(geometry);
  11459. }
  11460. return {
  11461. get: get,
  11462. update: update,
  11463. getWireframeAttribute: getWireframeAttribute
  11464. };
  11465. }
  11466. /**
  11467. * @author mrdoob / http://mrdoob.com/
  11468. */
  11469. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  11470. var mode;
  11471. function setMode(value) {
  11472. mode = value;
  11473. }
  11474. var type, bytesPerElement;
  11475. function setIndex(value) {
  11476. type = value.type;
  11477. bytesPerElement = value.bytesPerElement;
  11478. }
  11479. function render(start, count) {
  11480. gl.drawElements(mode, count, type, start * bytesPerElement);
  11481. info.update(count, mode);
  11482. }
  11483. function renderInstances(geometry, start, count, primcount) {
  11484. if (primcount === 0) return;
  11485. var extension, methodName;
  11486. if (capabilities.isWebGL2) {
  11487. extension = gl;
  11488. methodName = 'drawElementsInstanced';
  11489. } else {
  11490. extension = extensions.get('ANGLE_instanced_arrays');
  11491. methodName = 'drawElementsInstancedANGLE';
  11492. if (extension === null) {
  11493. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11494. return;
  11495. }
  11496. }
  11497. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  11498. info.update(count, mode, primcount);
  11499. } //
  11500. this.setMode = setMode;
  11501. this.setIndex = setIndex;
  11502. this.render = render;
  11503. this.renderInstances = renderInstances;
  11504. }
  11505. /**
  11506. * @author Mugen87 / https://github.com/Mugen87
  11507. */
  11508. function WebGLInfo(gl) {
  11509. var memory = {
  11510. geometries: 0,
  11511. textures: 0
  11512. };
  11513. var render = {
  11514. frame: 0,
  11515. calls: 0,
  11516. triangles: 0,
  11517. points: 0,
  11518. lines: 0
  11519. };
  11520. function update(count, mode, instanceCount) {
  11521. instanceCount = instanceCount || 1;
  11522. render.calls++;
  11523. switch (mode) {
  11524. case 4:
  11525. render.triangles += instanceCount * (count / 3);
  11526. break;
  11527. case 5:
  11528. case 6:
  11529. render.triangles += instanceCount * (count - 2);
  11530. break;
  11531. case 1:
  11532. render.lines += instanceCount * (count / 2);
  11533. break;
  11534. case 3:
  11535. render.lines += instanceCount * (count - 1);
  11536. break;
  11537. case 2:
  11538. render.lines += instanceCount * count;
  11539. break;
  11540. case 0:
  11541. render.points += instanceCount * count;
  11542. break;
  11543. default:
  11544. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  11545. break;
  11546. }
  11547. }
  11548. function reset() {
  11549. render.frame++;
  11550. render.calls = 0;
  11551. render.triangles = 0;
  11552. render.points = 0;
  11553. render.lines = 0;
  11554. }
  11555. return {
  11556. memory: memory,
  11557. render: render,
  11558. programs: null,
  11559. autoReset: true,
  11560. reset: reset,
  11561. update: update
  11562. };
  11563. }
  11564. /**
  11565. * @author mrdoob / http://mrdoob.com/
  11566. */
  11567. function absNumericalSort(a, b) {
  11568. return Math.abs(b[1]) - Math.abs(a[1]);
  11569. }
  11570. function WebGLMorphtargets(gl) {
  11571. var influencesList = {};
  11572. var morphInfluences = new Float32Array(8);
  11573. function update(object, geometry, material, program) {
  11574. var objectInfluences = object.morphTargetInfluences;
  11575. var length = objectInfluences.length;
  11576. var influences = influencesList[geometry.id];
  11577. if (influences === undefined) {
  11578. // initialise list
  11579. influences = [];
  11580. for (var i = 0; i < length; i++) {
  11581. influences[i] = [i, 0];
  11582. }
  11583. influencesList[geometry.id] = influences;
  11584. }
  11585. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  11586. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  11587. for (var i = 0; i < length; i++) {
  11588. var influence = influences[i];
  11589. if (influence[1] !== 0) {
  11590. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  11591. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  11592. }
  11593. } // Collect influences
  11594. for (var i = 0; i < length; i++) {
  11595. var influence = influences[i];
  11596. influence[0] = i;
  11597. influence[1] = objectInfluences[i];
  11598. }
  11599. influences.sort(absNumericalSort); // Add morphAttributes
  11600. for (var i = 0; i < 8; i++) {
  11601. var influence = influences[i];
  11602. if (influence) {
  11603. var index = influence[0];
  11604. var value = influence[1];
  11605. if (value) {
  11606. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  11607. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  11608. morphInfluences[i] = value;
  11609. continue;
  11610. }
  11611. }
  11612. morphInfluences[i] = 0;
  11613. }
  11614. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  11615. }
  11616. return {
  11617. update: update
  11618. };
  11619. }
  11620. /**
  11621. * @author mrdoob / http://mrdoob.com/
  11622. */
  11623. function WebGLObjects(gl, geometries, attributes, info) {
  11624. var updateList = {};
  11625. function update(object) {
  11626. var frame = info.render.frame;
  11627. var geometry = object.geometry;
  11628. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  11629. if (updateList[buffergeometry.id] !== frame) {
  11630. if (geometry.isGeometry) {
  11631. buffergeometry.updateFromObject(object);
  11632. }
  11633. geometries.update(buffergeometry);
  11634. updateList[buffergeometry.id] = frame;
  11635. }
  11636. if (object.isInstancedMesh) {
  11637. attributes.update(object.instanceMatrix, 34962);
  11638. }
  11639. return buffergeometry;
  11640. }
  11641. function dispose() {
  11642. updateList = {};
  11643. }
  11644. return {
  11645. update: update,
  11646. dispose: dispose
  11647. };
  11648. }
  11649. /**
  11650. * @author mrdoob / http://mrdoob.com/
  11651. */
  11652. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  11653. images = images !== undefined ? images : [];
  11654. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  11655. format = format !== undefined ? format : RGBFormat;
  11656. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  11657. this.flipY = false;
  11658. }
  11659. CubeTexture.prototype = Object.create(Texture.prototype);
  11660. CubeTexture.prototype.constructor = CubeTexture;
  11661. CubeTexture.prototype.isCubeTexture = true;
  11662. Object.defineProperty(CubeTexture.prototype, 'images', {
  11663. get: function () {
  11664. return this.image;
  11665. },
  11666. set: function (value) {
  11667. this.image = value;
  11668. }
  11669. });
  11670. /**
  11671. * @author Takahiro https://github.com/takahirox
  11672. */
  11673. function DataTexture2DArray(data, width, height, depth) {
  11674. Texture.call(this, null);
  11675. this.image = {
  11676. data: data || null,
  11677. width: width || 1,
  11678. height: height || 1,
  11679. depth: depth || 1
  11680. };
  11681. this.magFilter = NearestFilter;
  11682. this.minFilter = NearestFilter;
  11683. this.wrapR = ClampToEdgeWrapping;
  11684. this.generateMipmaps = false;
  11685. this.flipY = false;
  11686. this.needsUpdate = true;
  11687. }
  11688. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  11689. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  11690. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11691. /**
  11692. * @author Artur Trzesiok
  11693. */
  11694. function DataTexture3D(data, width, height, depth) {
  11695. // We're going to add .setXXX() methods for setting properties later.
  11696. // Users can still set in DataTexture3D directly.
  11697. //
  11698. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  11699. // texture.anisotropy = 16;
  11700. //
  11701. // See #14839
  11702. Texture.call(this, null);
  11703. this.image = {
  11704. data: data || null,
  11705. width: width || 1,
  11706. height: height || 1,
  11707. depth: depth || 1
  11708. };
  11709. this.magFilter = NearestFilter;
  11710. this.minFilter = NearestFilter;
  11711. this.wrapR = ClampToEdgeWrapping;
  11712. this.generateMipmaps = false;
  11713. this.flipY = false;
  11714. this.needsUpdate = true;
  11715. }
  11716. DataTexture3D.prototype = Object.create(Texture.prototype);
  11717. DataTexture3D.prototype.constructor = DataTexture3D;
  11718. DataTexture3D.prototype.isDataTexture3D = true;
  11719. /**
  11720. * @author tschw
  11721. * @author Mugen87 / https://github.com/Mugen87
  11722. * @author mrdoob / http://mrdoob.com/
  11723. *
  11724. * Uniforms of a program.
  11725. * Those form a tree structure with a special top-level container for the root,
  11726. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11727. *
  11728. *
  11729. * Properties of inner nodes including the top-level container:
  11730. *
  11731. * .seq - array of nested uniforms
  11732. * .map - nested uniforms by name
  11733. *
  11734. *
  11735. * Methods of all nodes except the top-level container:
  11736. *
  11737. * .setValue( gl, value, [textures] )
  11738. *
  11739. * uploads a uniform value(s)
  11740. * the 'textures' parameter is needed for sampler uniforms
  11741. *
  11742. *
  11743. * Static methods of the top-level container (textures factorizations):
  11744. *
  11745. * .upload( gl, seq, values, textures )
  11746. *
  11747. * sets uniforms in 'seq' to 'values[id].value'
  11748. *
  11749. * .seqWithValue( seq, values ) : filteredSeq
  11750. *
  11751. * filters 'seq' entries with corresponding entry in values
  11752. *
  11753. *
  11754. * Methods of the top-level container (textures factorizations):
  11755. *
  11756. * .setValue( gl, name, value, textures )
  11757. *
  11758. * sets uniform with name 'name' to 'value'
  11759. *
  11760. * .setOptional( gl, obj, prop )
  11761. *
  11762. * like .set for an optional property of the object
  11763. *
  11764. */
  11765. var emptyTexture = new Texture();
  11766. var emptyTexture2dArray = new DataTexture2DArray();
  11767. var emptyTexture3d = new DataTexture3D();
  11768. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  11769. // Array Caches (provide typed arrays for temporary by size)
  11770. var arrayCacheF32 = [];
  11771. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  11772. var mat4array = new Float32Array(16);
  11773. var mat3array = new Float32Array(9);
  11774. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  11775. function flatten(array, nBlocks, blockSize) {
  11776. var firstElem = array[0];
  11777. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  11778. // see http://jacksondunstan.com/articles/983
  11779. var n = nBlocks * blockSize,
  11780. r = arrayCacheF32[n];
  11781. if (r === undefined) {
  11782. r = new Float32Array(n);
  11783. arrayCacheF32[n] = r;
  11784. }
  11785. if (nBlocks !== 0) {
  11786. firstElem.toArray(r, 0);
  11787. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  11788. offset += blockSize;
  11789. array[i].toArray(r, offset);
  11790. }
  11791. }
  11792. return r;
  11793. }
  11794. function arraysEqual(a, b) {
  11795. if (a.length !== b.length) return false;
  11796. for (var i = 0, l = a.length; i < l; i++) {
  11797. if (a[i] !== b[i]) return false;
  11798. }
  11799. return true;
  11800. }
  11801. function copyArray(a, b) {
  11802. for (var i = 0, l = b.length; i < l; i++) {
  11803. a[i] = b[i];
  11804. }
  11805. } // Texture unit allocation
  11806. function allocTexUnits(textures, n) {
  11807. var r = arrayCacheI32[n];
  11808. if (r === undefined) {
  11809. r = new Int32Array(n);
  11810. arrayCacheI32[n] = r;
  11811. }
  11812. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  11813. return r;
  11814. } // --- Setters ---
  11815. // Note: Defining these methods externally, because they come in a bunch
  11816. // and this way their names minify.
  11817. // Single scalar
  11818. function setValueV1f(gl, v) {
  11819. var cache = this.cache;
  11820. if (cache[0] === v) return;
  11821. gl.uniform1f(this.addr, v);
  11822. cache[0] = v;
  11823. } // Single float vector (from flat array or THREE.VectorN)
  11824. function setValueV2f(gl, v) {
  11825. var cache = this.cache;
  11826. if (v.x !== undefined) {
  11827. if (cache[0] !== v.x || cache[1] !== v.y) {
  11828. gl.uniform2f(this.addr, v.x, v.y);
  11829. cache[0] = v.x;
  11830. cache[1] = v.y;
  11831. }
  11832. } else {
  11833. if (arraysEqual(cache, v)) return;
  11834. gl.uniform2fv(this.addr, v);
  11835. copyArray(cache, v);
  11836. }
  11837. }
  11838. function setValueV3f(gl, v) {
  11839. var cache = this.cache;
  11840. if (v.x !== undefined) {
  11841. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11842. gl.uniform3f(this.addr, v.x, v.y, v.z);
  11843. cache[0] = v.x;
  11844. cache[1] = v.y;
  11845. cache[2] = v.z;
  11846. }
  11847. } else if (v.r !== undefined) {
  11848. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  11849. gl.uniform3f(this.addr, v.r, v.g, v.b);
  11850. cache[0] = v.r;
  11851. cache[1] = v.g;
  11852. cache[2] = v.b;
  11853. }
  11854. } else {
  11855. if (arraysEqual(cache, v)) return;
  11856. gl.uniform3fv(this.addr, v);
  11857. copyArray(cache, v);
  11858. }
  11859. }
  11860. function setValueV4f(gl, v) {
  11861. var cache = this.cache;
  11862. if (v.x !== undefined) {
  11863. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11864. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  11865. cache[0] = v.x;
  11866. cache[1] = v.y;
  11867. cache[2] = v.z;
  11868. cache[3] = v.w;
  11869. }
  11870. } else {
  11871. if (arraysEqual(cache, v)) return;
  11872. gl.uniform4fv(this.addr, v);
  11873. copyArray(cache, v);
  11874. }
  11875. } // Single matrix (from flat array or MatrixN)
  11876. function setValueM2(gl, v) {
  11877. var cache = this.cache;
  11878. var elements = v.elements;
  11879. if (elements === undefined) {
  11880. if (arraysEqual(cache, v)) return;
  11881. gl.uniformMatrix2fv(this.addr, false, v);
  11882. copyArray(cache, v);
  11883. } else {
  11884. if (arraysEqual(cache, elements)) return;
  11885. mat2array.set(elements);
  11886. gl.uniformMatrix2fv(this.addr, false, mat2array);
  11887. copyArray(cache, elements);
  11888. }
  11889. }
  11890. function setValueM3(gl, v) {
  11891. var cache = this.cache;
  11892. var elements = v.elements;
  11893. if (elements === undefined) {
  11894. if (arraysEqual(cache, v)) return;
  11895. gl.uniformMatrix3fv(this.addr, false, v);
  11896. copyArray(cache, v);
  11897. } else {
  11898. if (arraysEqual(cache, elements)) return;
  11899. mat3array.set(elements);
  11900. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11901. copyArray(cache, elements);
  11902. }
  11903. }
  11904. function setValueM4(gl, v) {
  11905. var cache = this.cache;
  11906. var elements = v.elements;
  11907. if (elements === undefined) {
  11908. if (arraysEqual(cache, v)) return;
  11909. gl.uniformMatrix4fv(this.addr, false, v);
  11910. copyArray(cache, v);
  11911. } else {
  11912. if (arraysEqual(cache, elements)) return;
  11913. mat4array.set(elements);
  11914. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11915. copyArray(cache, elements);
  11916. }
  11917. } // Single texture (2D / Cube)
  11918. function setValueT1(gl, v, textures) {
  11919. var cache = this.cache;
  11920. var unit = textures.allocateTextureUnit();
  11921. if (cache[0] !== unit) {
  11922. gl.uniform1i(this.addr, unit);
  11923. cache[0] = unit;
  11924. }
  11925. textures.safeSetTexture2D(v || emptyTexture, unit);
  11926. }
  11927. function setValueT2DArray1(gl, v, textures) {
  11928. var cache = this.cache;
  11929. var unit = textures.allocateTextureUnit();
  11930. if (cache[0] !== unit) {
  11931. gl.uniform1i(this.addr, unit);
  11932. cache[0] = unit;
  11933. }
  11934. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11935. }
  11936. function setValueT3D1(gl, v, textures) {
  11937. var cache = this.cache;
  11938. var unit = textures.allocateTextureUnit();
  11939. if (cache[0] !== unit) {
  11940. gl.uniform1i(this.addr, unit);
  11941. cache[0] = unit;
  11942. }
  11943. textures.setTexture3D(v || emptyTexture3d, unit);
  11944. }
  11945. function setValueT6(gl, v, textures) {
  11946. var cache = this.cache;
  11947. var unit = textures.allocateTextureUnit();
  11948. if (cache[0] !== unit) {
  11949. gl.uniform1i(this.addr, unit);
  11950. cache[0] = unit;
  11951. }
  11952. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11953. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11954. function setValueV1i(gl, v) {
  11955. var cache = this.cache;
  11956. if (cache[0] === v) return;
  11957. gl.uniform1i(this.addr, v);
  11958. cache[0] = v;
  11959. }
  11960. function setValueV2i(gl, v) {
  11961. var cache = this.cache;
  11962. if (arraysEqual(cache, v)) return;
  11963. gl.uniform2iv(this.addr, v);
  11964. copyArray(cache, v);
  11965. }
  11966. function setValueV3i(gl, v) {
  11967. var cache = this.cache;
  11968. if (arraysEqual(cache, v)) return;
  11969. gl.uniform3iv(this.addr, v);
  11970. copyArray(cache, v);
  11971. }
  11972. function setValueV4i(gl, v) {
  11973. var cache = this.cache;
  11974. if (arraysEqual(cache, v)) return;
  11975. gl.uniform4iv(this.addr, v);
  11976. copyArray(cache, v);
  11977. } // Helper to pick the right setter for the singular case
  11978. function getSingularSetter(type) {
  11979. switch (type) {
  11980. case 0x1406:
  11981. return setValueV1f;
  11982. // FLOAT
  11983. case 0x8b50:
  11984. return setValueV2f;
  11985. // _VEC2
  11986. case 0x8b51:
  11987. return setValueV3f;
  11988. // _VEC3
  11989. case 0x8b52:
  11990. return setValueV4f;
  11991. // _VEC4
  11992. case 0x8b5a:
  11993. return setValueM2;
  11994. // _MAT2
  11995. case 0x8b5b:
  11996. return setValueM3;
  11997. // _MAT3
  11998. case 0x8b5c:
  11999. return setValueM4;
  12000. // _MAT4
  12001. case 0x8b5e:
  12002. case 0x8d66:
  12003. return setValueT1;
  12004. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  12005. case 0x8b5f:
  12006. return setValueT3D1;
  12007. // SAMPLER_3D
  12008. case 0x8b60:
  12009. return setValueT6;
  12010. // SAMPLER_CUBE
  12011. case 0x8DC1:
  12012. return setValueT2DArray1;
  12013. // SAMPLER_2D_ARRAY
  12014. case 0x1404:
  12015. case 0x8b56:
  12016. return setValueV1i;
  12017. // INT, BOOL
  12018. case 0x8b53:
  12019. case 0x8b57:
  12020. return setValueV2i;
  12021. // _VEC2
  12022. case 0x8b54:
  12023. case 0x8b58:
  12024. return setValueV3i;
  12025. // _VEC3
  12026. case 0x8b55:
  12027. case 0x8b59:
  12028. return setValueV4i;
  12029. // _VEC4
  12030. }
  12031. } // Array of scalars
  12032. function setValueV1fArray(gl, v) {
  12033. gl.uniform1fv(this.addr, v);
  12034. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  12035. function setValueV1iArray(gl, v) {
  12036. gl.uniform1iv(this.addr, v);
  12037. }
  12038. function setValueV2iArray(gl, v) {
  12039. gl.uniform2iv(this.addr, v);
  12040. }
  12041. function setValueV3iArray(gl, v) {
  12042. gl.uniform3iv(this.addr, v);
  12043. }
  12044. function setValueV4iArray(gl, v) {
  12045. gl.uniform4iv(this.addr, v);
  12046. } // Array of vectors (flat or from THREE classes)
  12047. function setValueV2fArray(gl, v) {
  12048. var data = flatten(v, this.size, 2);
  12049. gl.uniform2fv(this.addr, data);
  12050. }
  12051. function setValueV3fArray(gl, v) {
  12052. var data = flatten(v, this.size, 3);
  12053. gl.uniform3fv(this.addr, data);
  12054. }
  12055. function setValueV4fArray(gl, v) {
  12056. var data = flatten(v, this.size, 4);
  12057. gl.uniform4fv(this.addr, data);
  12058. } // Array of matrices (flat or from THREE clases)
  12059. function setValueM2Array(gl, v) {
  12060. var data = flatten(v, this.size, 4);
  12061. gl.uniformMatrix2fv(this.addr, false, data);
  12062. }
  12063. function setValueM3Array(gl, v) {
  12064. var data = flatten(v, this.size, 9);
  12065. gl.uniformMatrix3fv(this.addr, false, data);
  12066. }
  12067. function setValueM4Array(gl, v) {
  12068. var data = flatten(v, this.size, 16);
  12069. gl.uniformMatrix4fv(this.addr, false, data);
  12070. } // Array of textures (2D / Cube)
  12071. function setValueT1Array(gl, v, textures) {
  12072. var n = v.length;
  12073. var units = allocTexUnits(textures, n);
  12074. gl.uniform1iv(this.addr, units);
  12075. for (var i = 0; i !== n; ++i) {
  12076. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  12077. }
  12078. }
  12079. function setValueT6Array(gl, v, textures) {
  12080. var n = v.length;
  12081. var units = allocTexUnits(textures, n);
  12082. gl.uniform1iv(this.addr, units);
  12083. for (var i = 0; i !== n; ++i) {
  12084. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  12085. }
  12086. } // Helper to pick the right setter for a pure (bottom-level) array
  12087. function getPureArraySetter(type) {
  12088. switch (type) {
  12089. case 0x1406:
  12090. return setValueV1fArray;
  12091. // FLOAT
  12092. case 0x8b50:
  12093. return setValueV2fArray;
  12094. // _VEC2
  12095. case 0x8b51:
  12096. return setValueV3fArray;
  12097. // _VEC3
  12098. case 0x8b52:
  12099. return setValueV4fArray;
  12100. // _VEC4
  12101. case 0x8b5a:
  12102. return setValueM2Array;
  12103. // _MAT2
  12104. case 0x8b5b:
  12105. return setValueM3Array;
  12106. // _MAT3
  12107. case 0x8b5c:
  12108. return setValueM4Array;
  12109. // _MAT4
  12110. case 0x8b5e:
  12111. return setValueT1Array;
  12112. // SAMPLER_2D
  12113. case 0x8b60:
  12114. return setValueT6Array;
  12115. // SAMPLER_CUBE
  12116. case 0x1404:
  12117. case 0x8b56:
  12118. return setValueV1iArray;
  12119. // INT, BOOL
  12120. case 0x8b53:
  12121. case 0x8b57:
  12122. return setValueV2iArray;
  12123. // _VEC2
  12124. case 0x8b54:
  12125. case 0x8b58:
  12126. return setValueV3iArray;
  12127. // _VEC3
  12128. case 0x8b55:
  12129. case 0x8b59:
  12130. return setValueV4iArray;
  12131. // _VEC4
  12132. }
  12133. } // --- Uniform Classes ---
  12134. function SingleUniform(id, activeInfo, addr) {
  12135. this.id = id;
  12136. this.addr = addr;
  12137. this.cache = [];
  12138. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12139. }
  12140. function PureArrayUniform(id, activeInfo, addr) {
  12141. this.id = id;
  12142. this.addr = addr;
  12143. this.cache = [];
  12144. this.size = activeInfo.size;
  12145. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12146. }
  12147. PureArrayUniform.prototype.updateCache = function (data) {
  12148. var cache = this.cache;
  12149. if (data instanceof Float32Array && cache.length !== data.length) {
  12150. this.cache = new Float32Array(data.length);
  12151. }
  12152. copyArray(cache, data);
  12153. };
  12154. function StructuredUniform(id) {
  12155. this.id = id;
  12156. this.seq = [];
  12157. this.map = {};
  12158. }
  12159. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  12160. var seq = this.seq;
  12161. for (var i = 0, n = seq.length; i !== n; ++i) {
  12162. var u = seq[i];
  12163. u.setValue(gl, value[u.id], textures);
  12164. }
  12165. }; // --- Top-level ---
  12166. // Parser - builds up the property tree from the path strings
  12167. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  12168. // - the identifier (member name or array index)
  12169. // - followed by an optional right bracket (found when array index)
  12170. // - followed by an optional left bracket or dot (type of subscript)
  12171. //
  12172. // Note: These portions can be read in a non-overlapping fashion and
  12173. // allow straightforward parsing of the hierarchy that WebGL encodes
  12174. // in the uniform names.
  12175. function addUniform(container, uniformObject) {
  12176. container.seq.push(uniformObject);
  12177. container.map[uniformObject.id] = uniformObject;
  12178. }
  12179. function parseUniform(activeInfo, addr, container) {
  12180. var path = activeInfo.name,
  12181. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  12182. RePathPart.lastIndex = 0;
  12183. while (true) {
  12184. var match = RePathPart.exec(path),
  12185. matchEnd = RePathPart.lastIndex,
  12186. id = match[1],
  12187. idIsIndex = match[2] === ']',
  12188. subscript = match[3];
  12189. if (idIsIndex) id = id | 0; // convert to integer
  12190. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  12191. // bare name or "pure" bottom-level array "[0]" suffix
  12192. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  12193. break;
  12194. } else {
  12195. // step into inner node / create it in case it doesn't exist
  12196. var map = container.map,
  12197. next = map[id];
  12198. if (next === undefined) {
  12199. next = new StructuredUniform(id);
  12200. addUniform(container, next);
  12201. }
  12202. container = next;
  12203. }
  12204. }
  12205. } // Root Container
  12206. function WebGLUniforms(gl, program) {
  12207. this.seq = [];
  12208. this.map = {};
  12209. var n = gl.getProgramParameter(program, 35718);
  12210. for (var i = 0; i < n; ++i) {
  12211. var info = gl.getActiveUniform(program, i),
  12212. addr = gl.getUniformLocation(program, info.name);
  12213. parseUniform(info, addr, this);
  12214. }
  12215. }
  12216. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  12217. var u = this.map[name];
  12218. if (u !== undefined) u.setValue(gl, value, textures);
  12219. };
  12220. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  12221. var v = object[name];
  12222. if (v !== undefined) this.setValue(gl, name, v);
  12223. }; // Static interface
  12224. WebGLUniforms.upload = function (gl, seq, values, textures) {
  12225. for (var i = 0, n = seq.length; i !== n; ++i) {
  12226. var u = seq[i],
  12227. v = values[u.id];
  12228. if (v.needsUpdate !== false) {
  12229. // note: always updating when .needsUpdate is undefined
  12230. u.setValue(gl, v.value, textures);
  12231. }
  12232. }
  12233. };
  12234. WebGLUniforms.seqWithValue = function (seq, values) {
  12235. var r = [];
  12236. for (var i = 0, n = seq.length; i !== n; ++i) {
  12237. var u = seq[i];
  12238. if (u.id in values) r.push(u);
  12239. }
  12240. return r;
  12241. };
  12242. /**
  12243. * @author mrdoob / http://mrdoob.com/
  12244. */
  12245. function WebGLShader(gl, type, string) {
  12246. var shader = gl.createShader(type);
  12247. gl.shaderSource(shader, string);
  12248. gl.compileShader(shader);
  12249. return shader;
  12250. }
  12251. /**
  12252. * @author mrdoob / http://mrdoob.com/
  12253. */
  12254. var programIdCount = 0;
  12255. function addLineNumbers(string) {
  12256. var lines = string.split('\n');
  12257. for (var i = 0; i < lines.length; i++) {
  12258. lines[i] = i + 1 + ': ' + lines[i];
  12259. }
  12260. return lines.join('\n');
  12261. }
  12262. function getEncodingComponents(encoding) {
  12263. switch (encoding) {
  12264. case LinearEncoding:
  12265. return ['Linear', '( value )'];
  12266. case sRGBEncoding:
  12267. return ['sRGB', '( value )'];
  12268. case RGBEEncoding:
  12269. return ['RGBE', '( value )'];
  12270. case RGBM7Encoding:
  12271. return ['RGBM', '( value, 7.0 )'];
  12272. case RGBM16Encoding:
  12273. return ['RGBM', '( value, 16.0 )'];
  12274. case RGBDEncoding:
  12275. return ['RGBD', '( value, 256.0 )'];
  12276. case GammaEncoding:
  12277. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  12278. case LogLuvEncoding:
  12279. return ['LogLuv', '( value )'];
  12280. default:
  12281. throw new Error('unsupported encoding: ' + encoding);
  12282. }
  12283. }
  12284. function getShaderErrors(gl, shader, type) {
  12285. var status = gl.getShaderParameter(shader, 35713);
  12286. var log = gl.getShaderInfoLog(shader).trim();
  12287. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  12288. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12289. var source = gl.getShaderSource(shader);
  12290. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  12291. }
  12292. function getTexelDecodingFunction(functionName, encoding) {
  12293. var components = getEncodingComponents(encoding);
  12294. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  12295. }
  12296. function getTexelEncodingFunction(functionName, encoding) {
  12297. var components = getEncodingComponents(encoding);
  12298. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  12299. }
  12300. function getToneMappingFunction(functionName, toneMapping) {
  12301. var toneMappingName;
  12302. switch (toneMapping) {
  12303. case LinearToneMapping:
  12304. toneMappingName = 'Linear';
  12305. break;
  12306. case ReinhardToneMapping:
  12307. toneMappingName = 'Reinhard';
  12308. break;
  12309. case Uncharted2ToneMapping:
  12310. toneMappingName = 'Uncharted2';
  12311. break;
  12312. case CineonToneMapping:
  12313. toneMappingName = 'OptimizedCineon';
  12314. break;
  12315. case ACESFilmicToneMapping:
  12316. toneMappingName = 'ACESFilmic';
  12317. break;
  12318. default:
  12319. throw new Error('unsupported toneMapping: ' + toneMapping);
  12320. }
  12321. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12322. }
  12323. function generateExtensions(extensions, parameters, rendererExtensions) {
  12324. extensions = extensions || {};
  12325. var chunks = [extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading ? '#extension GL_OES_standard_derivatives : enable' : '', (extensions.fragDepth || parameters.logarithmicDepthBuffer) && rendererExtensions.get('EXT_frag_depth') ? '#extension GL_EXT_frag_depth : enable' : '', extensions.drawBuffers && rendererExtensions.get('WEBGL_draw_buffers') ? '#extension GL_EXT_draw_buffers : require' : '', (extensions.shaderTextureLOD || parameters.envMap) && rendererExtensions.get('EXT_shader_texture_lod') ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  12326. return chunks.filter(filterEmptyLine).join('\n');
  12327. }
  12328. function generateDefines(defines) {
  12329. var chunks = [];
  12330. for (var name in defines) {
  12331. var value = defines[name];
  12332. if (value === false) continue;
  12333. chunks.push('#define ' + name + ' ' + value);
  12334. }
  12335. return chunks.join('\n');
  12336. }
  12337. function fetchAttributeLocations(gl, program) {
  12338. var attributes = {};
  12339. var n = gl.getProgramParameter(program, 35721);
  12340. for (var i = 0; i < n; i++) {
  12341. var info = gl.getActiveAttrib(program, i);
  12342. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12343. attributes[name] = gl.getAttribLocation(program, name);
  12344. }
  12345. return attributes;
  12346. }
  12347. function filterEmptyLine(string) {
  12348. return string !== '';
  12349. }
  12350. function replaceLightNums(string, parameters) {
  12351. 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);
  12352. }
  12353. function replaceClippingPlaneNums(string, parameters) {
  12354. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  12355. } // Resolve Includes
  12356. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12357. function resolveIncludes(string) {
  12358. return string.replace(includePattern, includeReplacer);
  12359. }
  12360. function includeReplacer(match, include) {
  12361. var string = ShaderChunk[include];
  12362. if (string === undefined) {
  12363. throw new Error('Can not resolve #include <' + include + '>');
  12364. }
  12365. return resolveIncludes(string);
  12366. } // Unroll Loops
  12367. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12368. function unrollLoops(string) {
  12369. return string.replace(loopPattern, loopReplacer);
  12370. }
  12371. function loopReplacer(match, start, end, snippet) {
  12372. var string = '';
  12373. for (var i = parseInt(start); i < parseInt(end); i++) {
  12374. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  12375. }
  12376. return string;
  12377. } //
  12378. function generatePrecision(parameters) {
  12379. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  12380. if (parameters.precision === "highp") {
  12381. precisionstring += "\n#define HIGH_PRECISION";
  12382. } else if (parameters.precision === "mediump") {
  12383. precisionstring += "\n#define MEDIUM_PRECISION";
  12384. } else if (parameters.precision === "lowp") {
  12385. precisionstring += "\n#define LOW_PRECISION";
  12386. }
  12387. return precisionstring;
  12388. }
  12389. function generateShadowMapTypeDefine(parameters) {
  12390. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12391. if (parameters.shadowMapType === PCFShadowMap) {
  12392. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12393. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  12394. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12395. } else if (parameters.shadowMapType === VSMShadowMap) {
  12396. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12397. }
  12398. return shadowMapTypeDefine;
  12399. }
  12400. function generateEnvMapTypeDefine(parameters, material) {
  12401. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12402. if (parameters.envMap) {
  12403. switch (material.envMap.mapping) {
  12404. case CubeReflectionMapping:
  12405. case CubeRefractionMapping:
  12406. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12407. break;
  12408. case CubeUVReflectionMapping:
  12409. case CubeUVRefractionMapping:
  12410. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12411. break;
  12412. case EquirectangularReflectionMapping:
  12413. case EquirectangularRefractionMapping:
  12414. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12415. break;
  12416. case SphericalReflectionMapping:
  12417. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12418. break;
  12419. }
  12420. }
  12421. return envMapTypeDefine;
  12422. }
  12423. function generateEnvMapModeDefine(parameters, material) {
  12424. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12425. if (parameters.envMap) {
  12426. switch (material.envMap.mapping) {
  12427. case CubeRefractionMapping:
  12428. case EquirectangularRefractionMapping:
  12429. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12430. break;
  12431. }
  12432. }
  12433. return envMapModeDefine;
  12434. }
  12435. function generateEnvMapBlendingDefine(parameters, material) {
  12436. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12437. if (parameters.envMap) {
  12438. switch (material.combine) {
  12439. case MultiplyOperation:
  12440. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12441. break;
  12442. case MixOperation:
  12443. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12444. break;
  12445. case AddOperation:
  12446. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12447. break;
  12448. }
  12449. }
  12450. return envMapBlendingDefine;
  12451. }
  12452. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  12453. var gl = renderer.getContext();
  12454. var defines = material.defines;
  12455. var vertexShader = shader.vertexShader;
  12456. var fragmentShader = shader.fragmentShader;
  12457. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  12458. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  12459. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  12460. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  12461. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  12462. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  12463. var customDefines = generateDefines(defines);
  12464. var program = gl.createProgram();
  12465. var prefixVertex, prefixFragment;
  12466. var renderTarget = renderer.getRenderTarget();
  12467. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  12468. if (material.isRawShaderMaterial) {
  12469. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  12470. if (prefixVertex.length > 0) {
  12471. prefixVertex += '\n';
  12472. }
  12473. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  12474. if (prefixFragment.length > 0) {
  12475. prefixFragment += '\n';
  12476. }
  12477. } else {
  12478. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, 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.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.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.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', '#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');
  12479. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  12480. '#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.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.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.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', ((material.extensions ? material.extensions.shaderTextureLOD : false) || parameters.envMap) && (parameters.isWebGL2 || extensions.get('EXT_shader_texture_lod')) ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 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
  12481. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ? ShaderChunk['encodings_pars_fragment'] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  12482. 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.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  12483. }
  12484. vertexShader = resolveIncludes(vertexShader);
  12485. vertexShader = replaceLightNums(vertexShader, parameters);
  12486. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  12487. fragmentShader = resolveIncludes(fragmentShader);
  12488. fragmentShader = replaceLightNums(fragmentShader, parameters);
  12489. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  12490. vertexShader = unrollLoops(vertexShader);
  12491. fragmentShader = unrollLoops(fragmentShader);
  12492. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  12493. var isGLSL3ShaderMaterial = false;
  12494. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  12495. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  12496. isGLSL3ShaderMaterial = true;
  12497. vertexShader = vertexShader.replace(versionRegex, '');
  12498. fragmentShader = fragmentShader.replace(versionRegex, '');
  12499. } // GLSL 3.0 conversion
  12500. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  12501. 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; // Multiview
  12502. if (numMultiviewViews > 0) {
  12503. prefixVertex = prefixVertex.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', 'layout(num_views = ' + numMultiviewViews + ') in;', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12504. prefixVertex = prefixVertex.replace(['uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;'].join('\n'), ['uniform mat4 modelViewMatrices[' + numMultiviewViews + '];', 'uniform mat4 projectionMatrices[' + numMultiviewViews + '];', 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', 'uniform mat3 normalMatrices[' + numMultiviewViews + '];', '#define modelViewMatrix modelViewMatrices[VIEW_ID]', '#define projectionMatrix projectionMatrices[VIEW_ID]', '#define viewMatrix viewMatrices[VIEW_ID]', '#define normalMatrix normalMatrices[VIEW_ID]'].join('\n'));
  12505. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12506. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  12507. }
  12508. }
  12509. var vertexGlsl = prefixVertex + vertexShader;
  12510. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  12511. // console.log( '*FRAGMENT*', fragmentGlsl );
  12512. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  12513. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  12514. gl.attachShader(program, glVertexShader);
  12515. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  12516. if (material.index0AttributeName !== undefined) {
  12517. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  12518. } else if (parameters.morphTargets === true) {
  12519. // programs with morphTargets displace position out of attribute 0
  12520. gl.bindAttribLocation(program, 0, 'position');
  12521. }
  12522. gl.linkProgram(program); // check for link errors
  12523. if (renderer.debug.checkShaderErrors) {
  12524. var programLog = gl.getProgramInfoLog(program).trim();
  12525. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  12526. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  12527. var runnable = true;
  12528. var haveDiagnostics = true;
  12529. if (gl.getProgramParameter(program, 35714) === false) {
  12530. runnable = false;
  12531. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  12532. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  12533. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  12534. } else if (programLog !== '') {
  12535. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  12536. } else if (vertexLog === '' || fragmentLog === '') {
  12537. haveDiagnostics = false;
  12538. }
  12539. if (haveDiagnostics) {
  12540. this.diagnostics = {
  12541. runnable: runnable,
  12542. material: material,
  12543. programLog: programLog,
  12544. vertexShader: {
  12545. log: vertexLog,
  12546. prefix: prefixVertex
  12547. },
  12548. fragmentShader: {
  12549. log: fragmentLog,
  12550. prefix: prefixFragment
  12551. }
  12552. };
  12553. }
  12554. } // clean up
  12555. gl.deleteShader(glVertexShader);
  12556. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  12557. var cachedUniforms;
  12558. this.getUniforms = function () {
  12559. if (cachedUniforms === undefined) {
  12560. cachedUniforms = new WebGLUniforms(gl, program);
  12561. }
  12562. return cachedUniforms;
  12563. }; // set up caching for attribute locations
  12564. var cachedAttributes;
  12565. this.getAttributes = function () {
  12566. if (cachedAttributes === undefined) {
  12567. cachedAttributes = fetchAttributeLocations(gl, program);
  12568. }
  12569. return cachedAttributes;
  12570. }; // free resource
  12571. this.destroy = function () {
  12572. gl.deleteProgram(program);
  12573. this.program = undefined;
  12574. }; //
  12575. this.name = shader.name;
  12576. this.id = programIdCount++;
  12577. this.code = code;
  12578. this.usedTimes = 1;
  12579. this.program = program;
  12580. this.vertexShader = glVertexShader;
  12581. this.fragmentShader = glFragmentShader;
  12582. this.numMultiviewViews = numMultiviewViews;
  12583. return this;
  12584. }
  12585. /**
  12586. * @author mrdoob / http://mrdoob.com/
  12587. */
  12588. function WebGLPrograms(renderer, extensions, capabilities) {
  12589. var programs = [];
  12590. var shaderIDs = {
  12591. MeshDepthMaterial: 'depth',
  12592. MeshDistanceMaterial: 'distanceRGBA',
  12593. MeshNormalMaterial: 'normal',
  12594. MeshBasicMaterial: 'basic',
  12595. MeshLambertMaterial: 'lambert',
  12596. MeshPhongMaterial: 'phong',
  12597. MeshToonMaterial: 'phong',
  12598. MeshStandardMaterial: 'physical',
  12599. MeshPhysicalMaterial: 'physical',
  12600. MeshMatcapMaterial: 'matcap',
  12601. LineBasicMaterial: 'basic',
  12602. LineDashedMaterial: 'dashed',
  12603. PointsMaterial: 'points',
  12604. ShadowMaterial: 'shadow',
  12605. SpriteMaterial: 'sprite'
  12606. };
  12607. var parameterNames = ["precision", "supportsVertexTextures", "instancing", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen"];
  12608. function allocateBones(object) {
  12609. var skeleton = object.skeleton;
  12610. var bones = skeleton.bones;
  12611. if (capabilities.floatVertexTextures) {
  12612. return 1024;
  12613. } else {
  12614. // default for when object is not specified
  12615. // ( for example when prebuilding shader to be used with multiple objects )
  12616. //
  12617. // - leave some extra space for other uniforms
  12618. // - limit here is ANGLE's 254 max uniform vectors
  12619. // (up to 54 should be safe)
  12620. var nVertexUniforms = capabilities.maxVertexUniforms;
  12621. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  12622. var maxBones = Math.min(nVertexMatrices, bones.length);
  12623. if (maxBones < bones.length) {
  12624. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  12625. return 0;
  12626. }
  12627. return maxBones;
  12628. }
  12629. }
  12630. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  12631. var encoding;
  12632. if (!map) {
  12633. encoding = LinearEncoding;
  12634. } else if (map.isTexture) {
  12635. encoding = map.encoding;
  12636. } else if (map.isWebGLRenderTarget) {
  12637. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  12638. encoding = map.texture.encoding;
  12639. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12640. if (encoding === LinearEncoding && gammaOverrideLinear) {
  12641. encoding = GammaEncoding;
  12642. }
  12643. return encoding;
  12644. }
  12645. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  12646. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  12647. // (not to blow over maxLights budget)
  12648. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  12649. var precision = capabilities.precision;
  12650. if (material.precision !== null) {
  12651. precision = capabilities.getMaxPrecision(material.precision);
  12652. if (precision !== material.precision) {
  12653. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  12654. }
  12655. }
  12656. var currentRenderTarget = renderer.getRenderTarget();
  12657. var parameters = {
  12658. isWebGL2: capabilities.isWebGL2,
  12659. shaderID: shaderID,
  12660. precision: precision,
  12661. instancing: object.isInstancedMesh === true,
  12662. supportsVertexTextures: capabilities.vertexTextures,
  12663. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  12664. map: !!material.map,
  12665. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  12666. matcap: !!material.matcap,
  12667. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  12668. envMap: !!material.envMap,
  12669. envMapMode: material.envMap && material.envMap.mapping,
  12670. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  12671. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  12672. lightMap: !!material.lightMap,
  12673. aoMap: !!material.aoMap,
  12674. emissiveMap: !!material.emissiveMap,
  12675. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  12676. bumpMap: !!material.bumpMap,
  12677. normalMap: !!material.normalMap,
  12678. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12679. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12680. clearcoatNormalMap: !!material.clearcoatNormalMap,
  12681. displacementMap: !!material.displacementMap,
  12682. roughnessMap: !!material.roughnessMap,
  12683. metalnessMap: !!material.metalnessMap,
  12684. specularMap: !!material.specularMap,
  12685. alphaMap: !!material.alphaMap,
  12686. gradientMap: !!material.gradientMap,
  12687. sheen: !!material.sheen,
  12688. combine: material.combine,
  12689. vertexTangents: material.normalMap && material.vertexTangents,
  12690. vertexColors: material.vertexColors,
  12691. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  12692. fog: !!fog,
  12693. useFog: material.fog,
  12694. fogExp2: fog && fog.isFogExp2,
  12695. flatShading: material.flatShading,
  12696. sizeAttenuation: material.sizeAttenuation,
  12697. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12698. skinning: material.skinning && maxBones > 0,
  12699. maxBones: maxBones,
  12700. useVertexTexture: capabilities.floatVertexTextures,
  12701. morphTargets: material.morphTargets,
  12702. morphNormals: material.morphNormals,
  12703. maxMorphTargets: renderer.maxMorphTargets,
  12704. maxMorphNormals: renderer.maxMorphNormals,
  12705. numDirLights: lights.directional.length,
  12706. numPointLights: lights.point.length,
  12707. numSpotLights: lights.spot.length,
  12708. numRectAreaLights: lights.rectArea.length,
  12709. numHemiLights: lights.hemi.length,
  12710. numDirLightShadows: lights.directionalShadowMap.length,
  12711. numPointLightShadows: lights.pointShadowMap.length,
  12712. numSpotLightShadows: lights.spotShadowMap.length,
  12713. numClippingPlanes: nClipPlanes,
  12714. numClipIntersection: nClipIntersection,
  12715. dithering: material.dithering,
  12716. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12717. shadowMapType: renderer.shadowMap.type,
  12718. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12719. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12720. premultipliedAlpha: material.premultipliedAlpha,
  12721. alphaTest: material.alphaTest,
  12722. doubleSided: material.side === DoubleSide,
  12723. flipSided: material.side === BackSide,
  12724. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  12725. };
  12726. return parameters;
  12727. };
  12728. this.getProgramCode = function (material, parameters) {
  12729. var array = [];
  12730. if (parameters.shaderID) {
  12731. array.push(parameters.shaderID);
  12732. } else {
  12733. array.push(material.fragmentShader);
  12734. array.push(material.vertexShader);
  12735. }
  12736. if (material.defines !== undefined) {
  12737. for (var name in material.defines) {
  12738. array.push(name);
  12739. array.push(material.defines[name]);
  12740. }
  12741. }
  12742. for (var i = 0; i < parameterNames.length; i++) {
  12743. array.push(parameters[parameterNames[i]]);
  12744. }
  12745. array.push(material.onBeforeCompile.toString());
  12746. array.push(renderer.gammaOutput);
  12747. array.push(renderer.gammaFactor);
  12748. return array.join();
  12749. };
  12750. this.acquireProgram = function (material, shader, parameters, code) {
  12751. var program; // Check if code has been already compiled
  12752. for (var p = 0, pl = programs.length; p < pl; p++) {
  12753. var programInfo = programs[p];
  12754. if (programInfo.code === code) {
  12755. program = programInfo;
  12756. ++program.usedTimes;
  12757. break;
  12758. }
  12759. }
  12760. if (program === undefined) {
  12761. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  12762. programs.push(program);
  12763. }
  12764. return program;
  12765. };
  12766. this.releaseProgram = function (program) {
  12767. if (--program.usedTimes === 0) {
  12768. // Remove from unordered set
  12769. var i = programs.indexOf(program);
  12770. programs[i] = programs[programs.length - 1];
  12771. programs.pop(); // Free WebGL resources
  12772. program.destroy();
  12773. }
  12774. }; // Exposed for resource monitoring & error feedback via renderer.info:
  12775. this.programs = programs;
  12776. }
  12777. /**
  12778. * @author fordacious / fordacious.github.io
  12779. */
  12780. function WebGLProperties() {
  12781. var properties = new WeakMap();
  12782. function get(object) {
  12783. var map = properties.get(object);
  12784. if (map === undefined) {
  12785. map = {};
  12786. properties.set(object, map);
  12787. }
  12788. return map;
  12789. }
  12790. function remove(object) {
  12791. properties.delete(object);
  12792. }
  12793. function update(object, key, value) {
  12794. properties.get(object)[key] = value;
  12795. }
  12796. function dispose() {
  12797. properties = new WeakMap();
  12798. }
  12799. return {
  12800. get: get,
  12801. remove: remove,
  12802. update: update,
  12803. dispose: dispose
  12804. };
  12805. }
  12806. /**
  12807. * @author mrdoob / http://mrdoob.com/
  12808. */
  12809. function painterSortStable(a, b) {
  12810. if (a.groupOrder !== b.groupOrder) {
  12811. return a.groupOrder - b.groupOrder;
  12812. } else if (a.renderOrder !== b.renderOrder) {
  12813. return a.renderOrder - b.renderOrder;
  12814. } else if (a.program !== b.program) {
  12815. return a.program.id - b.program.id;
  12816. } else if (a.material.id !== b.material.id) {
  12817. return a.material.id - b.material.id;
  12818. } else if (a.z !== b.z) {
  12819. return a.z - b.z;
  12820. } else {
  12821. return a.id - b.id;
  12822. }
  12823. }
  12824. function reversePainterSortStable(a, b) {
  12825. if (a.groupOrder !== b.groupOrder) {
  12826. return a.groupOrder - b.groupOrder;
  12827. } else if (a.renderOrder !== b.renderOrder) {
  12828. return a.renderOrder - b.renderOrder;
  12829. } else if (a.z !== b.z) {
  12830. return b.z - a.z;
  12831. } else {
  12832. return a.id - b.id;
  12833. }
  12834. }
  12835. function WebGLRenderList() {
  12836. var renderItems = [];
  12837. var renderItemsIndex = 0;
  12838. var opaque = [];
  12839. var transparent = [];
  12840. var defaultProgram = {
  12841. id: -1
  12842. };
  12843. function init() {
  12844. renderItemsIndex = 0;
  12845. opaque.length = 0;
  12846. transparent.length = 0;
  12847. }
  12848. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12849. var renderItem = renderItems[renderItemsIndex];
  12850. if (renderItem === undefined) {
  12851. renderItem = {
  12852. id: object.id,
  12853. object: object,
  12854. geometry: geometry,
  12855. material: material,
  12856. program: material.program || defaultProgram,
  12857. groupOrder: groupOrder,
  12858. renderOrder: object.renderOrder,
  12859. z: z,
  12860. group: group
  12861. };
  12862. renderItems[renderItemsIndex] = renderItem;
  12863. } else {
  12864. renderItem.id = object.id;
  12865. renderItem.object = object;
  12866. renderItem.geometry = geometry;
  12867. renderItem.material = material;
  12868. renderItem.program = material.program || defaultProgram;
  12869. renderItem.groupOrder = groupOrder;
  12870. renderItem.renderOrder = object.renderOrder;
  12871. renderItem.z = z;
  12872. renderItem.group = group;
  12873. }
  12874. renderItemsIndex++;
  12875. return renderItem;
  12876. }
  12877. function push(object, geometry, material, groupOrder, z, group) {
  12878. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12879. (material.transparent === true ? transparent : opaque).push(renderItem);
  12880. }
  12881. function unshift(object, geometry, material, groupOrder, z, group) {
  12882. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12883. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12884. }
  12885. function sort() {
  12886. if (opaque.length > 1) opaque.sort(painterSortStable);
  12887. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  12888. }
  12889. return {
  12890. opaque: opaque,
  12891. transparent: transparent,
  12892. init: init,
  12893. push: push,
  12894. unshift: unshift,
  12895. sort: sort
  12896. };
  12897. }
  12898. function WebGLRenderLists() {
  12899. var lists = new WeakMap();
  12900. function onSceneDispose(event) {
  12901. var scene = event.target;
  12902. scene.removeEventListener('dispose', onSceneDispose);
  12903. lists.delete(scene);
  12904. }
  12905. function get(scene, camera) {
  12906. var cameras = lists.get(scene);
  12907. var list;
  12908. if (cameras === undefined) {
  12909. list = new WebGLRenderList();
  12910. lists.set(scene, new WeakMap());
  12911. lists.get(scene).set(camera, list);
  12912. scene.addEventListener('dispose', onSceneDispose);
  12913. } else {
  12914. list = cameras.get(camera);
  12915. if (list === undefined) {
  12916. list = new WebGLRenderList();
  12917. cameras.set(camera, list);
  12918. }
  12919. }
  12920. return list;
  12921. }
  12922. function dispose() {
  12923. lists = new WeakMap();
  12924. }
  12925. return {
  12926. get: get,
  12927. dispose: dispose
  12928. };
  12929. }
  12930. /**
  12931. * @author mrdoob / http://mrdoob.com/
  12932. */
  12933. function UniformsCache() {
  12934. var lights = {};
  12935. return {
  12936. get: function (light) {
  12937. if (lights[light.id] !== undefined) {
  12938. return lights[light.id];
  12939. }
  12940. var uniforms;
  12941. switch (light.type) {
  12942. case 'DirectionalLight':
  12943. uniforms = {
  12944. direction: new Vector3(),
  12945. color: new Color(),
  12946. shadow: false,
  12947. shadowBias: 0,
  12948. shadowRadius: 1,
  12949. shadowMapSize: new Vector2()
  12950. };
  12951. break;
  12952. case 'SpotLight':
  12953. uniforms = {
  12954. position: new Vector3(),
  12955. direction: new Vector3(),
  12956. color: new Color(),
  12957. distance: 0,
  12958. coneCos: 0,
  12959. penumbraCos: 0,
  12960. decay: 0,
  12961. shadow: false,
  12962. shadowBias: 0,
  12963. shadowRadius: 1,
  12964. shadowMapSize: new Vector2()
  12965. };
  12966. break;
  12967. case 'PointLight':
  12968. uniforms = {
  12969. position: new Vector3(),
  12970. color: new Color(),
  12971. distance: 0,
  12972. decay: 0,
  12973. shadow: false,
  12974. shadowBias: 0,
  12975. shadowRadius: 1,
  12976. shadowMapSize: new Vector2(),
  12977. shadowCameraNear: 1,
  12978. shadowCameraFar: 1000
  12979. };
  12980. break;
  12981. case 'HemisphereLight':
  12982. uniforms = {
  12983. direction: new Vector3(),
  12984. skyColor: new Color(),
  12985. groundColor: new Color()
  12986. };
  12987. break;
  12988. case 'RectAreaLight':
  12989. uniforms = {
  12990. color: new Color(),
  12991. position: new Vector3(),
  12992. halfWidth: new Vector3(),
  12993. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  12994. };
  12995. break;
  12996. }
  12997. lights[light.id] = uniforms;
  12998. return uniforms;
  12999. }
  13000. };
  13001. }
  13002. var nextVersion = 0;
  13003. function shadowCastingLightsFirst(lightA, lightB) {
  13004. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  13005. }
  13006. function WebGLLights() {
  13007. var cache = new UniformsCache();
  13008. var state = {
  13009. version: 0,
  13010. hash: {
  13011. directionalLength: -1,
  13012. pointLength: -1,
  13013. spotLength: -1,
  13014. rectAreaLength: -1,
  13015. hemiLength: -1,
  13016. numDirectionalShadows: -1,
  13017. numPointShadows: -1,
  13018. numSpotShadows: -1
  13019. },
  13020. ambient: [0, 0, 0],
  13021. probe: [],
  13022. directional: [],
  13023. directionalShadowMap: [],
  13024. directionalShadowMatrix: [],
  13025. spot: [],
  13026. spotShadowMap: [],
  13027. spotShadowMatrix: [],
  13028. rectArea: [],
  13029. point: [],
  13030. pointShadowMap: [],
  13031. pointShadowMatrix: [],
  13032. hemi: [],
  13033. numDirectionalShadows: -1,
  13034. numPointShadows: -1,
  13035. numSpotShadows: -1
  13036. };
  13037. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  13038. var vector3 = new Vector3();
  13039. var matrix4 = new Matrix4();
  13040. var matrix42 = new Matrix4();
  13041. function setup(lights, shadows, camera) {
  13042. var r = 0,
  13043. g = 0,
  13044. b = 0;
  13045. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  13046. var directionalLength = 0;
  13047. var pointLength = 0;
  13048. var spotLength = 0;
  13049. var rectAreaLength = 0;
  13050. var hemiLength = 0;
  13051. var numDirectionalShadows = 0;
  13052. var numPointShadows = 0;
  13053. var numSpotShadows = 0;
  13054. var viewMatrix = camera.matrixWorldInverse;
  13055. lights.sort(shadowCastingLightsFirst);
  13056. for (var i = 0, l = lights.length; i < l; i++) {
  13057. var light = lights[i];
  13058. var color = light.color;
  13059. var intensity = light.intensity;
  13060. var distance = light.distance;
  13061. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  13062. if (light.isAmbientLight) {
  13063. r += color.r * intensity;
  13064. g += color.g * intensity;
  13065. b += color.b * intensity;
  13066. } else if (light.isLightProbe) {
  13067. for (var j = 0; j < 9; j++) {
  13068. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  13069. }
  13070. } else if (light.isDirectionalLight) {
  13071. var uniforms = cache.get(light);
  13072. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13073. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13074. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13075. uniforms.direction.sub(vector3);
  13076. uniforms.direction.transformDirection(viewMatrix);
  13077. uniforms.shadow = light.castShadow;
  13078. if (light.castShadow) {
  13079. var shadow = light.shadow;
  13080. uniforms.shadowBias = shadow.bias;
  13081. uniforms.shadowRadius = shadow.radius;
  13082. uniforms.shadowMapSize = shadow.mapSize;
  13083. state.directionalShadowMap[directionalLength] = shadowMap;
  13084. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  13085. numDirectionalShadows++;
  13086. }
  13087. state.directional[directionalLength] = uniforms;
  13088. directionalLength++;
  13089. } else if (light.isSpotLight) {
  13090. var uniforms = cache.get(light);
  13091. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13092. uniforms.position.applyMatrix4(viewMatrix);
  13093. uniforms.color.copy(color).multiplyScalar(intensity);
  13094. uniforms.distance = distance;
  13095. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13096. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13097. uniforms.direction.sub(vector3);
  13098. uniforms.direction.transformDirection(viewMatrix);
  13099. uniforms.coneCos = Math.cos(light.angle);
  13100. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  13101. uniforms.decay = light.decay;
  13102. uniforms.shadow = light.castShadow;
  13103. if (light.castShadow) {
  13104. var shadow = light.shadow;
  13105. uniforms.shadowBias = shadow.bias;
  13106. uniforms.shadowRadius = shadow.radius;
  13107. uniforms.shadowMapSize = shadow.mapSize;
  13108. state.spotShadowMap[spotLength] = shadowMap;
  13109. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  13110. numSpotShadows++;
  13111. }
  13112. state.spot[spotLength] = uniforms;
  13113. spotLength++;
  13114. } else if (light.isRectAreaLight) {
  13115. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  13116. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13117. // (b) intensity is the brightness of the light
  13118. uniforms.color.copy(color).multiplyScalar(intensity);
  13119. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13120. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  13121. matrix42.identity();
  13122. matrix4.copy(light.matrixWorld);
  13123. matrix4.premultiply(viewMatrix);
  13124. matrix42.extractRotation(matrix4);
  13125. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  13126. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  13127. uniforms.halfWidth.applyMatrix4(matrix42);
  13128. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  13129. // uniforms.distance = distance;
  13130. state.rectArea[rectAreaLength] = uniforms;
  13131. rectAreaLength++;
  13132. } else if (light.isPointLight) {
  13133. var uniforms = cache.get(light);
  13134. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13135. uniforms.position.applyMatrix4(viewMatrix);
  13136. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13137. uniforms.distance = light.distance;
  13138. uniforms.decay = light.decay;
  13139. uniforms.shadow = light.castShadow;
  13140. if (light.castShadow) {
  13141. var shadow = light.shadow;
  13142. uniforms.shadowBias = shadow.bias;
  13143. uniforms.shadowRadius = shadow.radius;
  13144. uniforms.shadowMapSize = shadow.mapSize;
  13145. uniforms.shadowCameraNear = shadow.camera.near;
  13146. uniforms.shadowCameraFar = shadow.camera.far;
  13147. state.pointShadowMap[pointLength] = shadowMap;
  13148. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  13149. numPointShadows++;
  13150. }
  13151. state.point[pointLength] = uniforms;
  13152. pointLength++;
  13153. } else if (light.isHemisphereLight) {
  13154. var uniforms = cache.get(light);
  13155. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13156. uniforms.direction.transformDirection(viewMatrix);
  13157. uniforms.direction.normalize();
  13158. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  13159. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  13160. state.hemi[hemiLength] = uniforms;
  13161. hemiLength++;
  13162. }
  13163. }
  13164. state.ambient[0] = r;
  13165. state.ambient[1] = g;
  13166. state.ambient[2] = b;
  13167. var hash = state.hash;
  13168. 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) {
  13169. state.directional.length = directionalLength;
  13170. state.spot.length = spotLength;
  13171. state.rectArea.length = rectAreaLength;
  13172. state.point.length = pointLength;
  13173. state.hemi.length = hemiLength;
  13174. state.directionalShadowMap.length = numDirectionalShadows;
  13175. state.pointShadowMap.length = numPointShadows;
  13176. state.spotShadowMap.length = numSpotShadows;
  13177. state.directionalShadowMatrix.length = numDirectionalShadows;
  13178. state.pointShadowMatrix.length = numPointShadows;
  13179. state.spotShadowMatrix.length = numSpotShadows;
  13180. hash.directionalLength = directionalLength;
  13181. hash.pointLength = pointLength;
  13182. hash.spotLength = spotLength;
  13183. hash.rectAreaLength = rectAreaLength;
  13184. hash.hemiLength = hemiLength;
  13185. hash.numDirectionalShadows = numDirectionalShadows;
  13186. hash.numPointShadows = numPointShadows;
  13187. hash.numSpotShadows = numSpotShadows;
  13188. state.version = nextVersion++;
  13189. }
  13190. }
  13191. return {
  13192. setup: setup,
  13193. state: state
  13194. };
  13195. }
  13196. /**
  13197. * @author Mugen87 / https://github.com/Mugen87
  13198. */
  13199. function WebGLRenderState() {
  13200. var lights = new WebGLLights();
  13201. var lightsArray = [];
  13202. var shadowsArray = [];
  13203. function init() {
  13204. lightsArray.length = 0;
  13205. shadowsArray.length = 0;
  13206. }
  13207. function pushLight(light) {
  13208. lightsArray.push(light);
  13209. }
  13210. function pushShadow(shadowLight) {
  13211. shadowsArray.push(shadowLight);
  13212. }
  13213. function setupLights(camera) {
  13214. lights.setup(lightsArray, shadowsArray, camera);
  13215. }
  13216. var state = {
  13217. lightsArray: lightsArray,
  13218. shadowsArray: shadowsArray,
  13219. lights: lights
  13220. };
  13221. return {
  13222. init: init,
  13223. state: state,
  13224. setupLights: setupLights,
  13225. pushLight: pushLight,
  13226. pushShadow: pushShadow
  13227. };
  13228. }
  13229. function WebGLRenderStates() {
  13230. var renderStates = new WeakMap();
  13231. function onSceneDispose(event) {
  13232. var scene = event.target;
  13233. scene.removeEventListener('dispose', onSceneDispose);
  13234. renderStates.delete(scene);
  13235. }
  13236. function get(scene, camera) {
  13237. var renderState;
  13238. if (renderStates.has(scene) === false) {
  13239. renderState = new WebGLRenderState();
  13240. renderStates.set(scene, new WeakMap());
  13241. renderStates.get(scene).set(camera, renderState);
  13242. scene.addEventListener('dispose', onSceneDispose);
  13243. } else {
  13244. if (renderStates.get(scene).has(camera) === false) {
  13245. renderState = new WebGLRenderState();
  13246. renderStates.get(scene).set(camera, renderState);
  13247. } else {
  13248. renderState = renderStates.get(scene).get(camera);
  13249. }
  13250. }
  13251. return renderState;
  13252. }
  13253. function dispose() {
  13254. renderStates = new WeakMap();
  13255. }
  13256. return {
  13257. get: get,
  13258. dispose: dispose
  13259. };
  13260. }
  13261. /**
  13262. * @author mrdoob / http://mrdoob.com/
  13263. * @author alteredq / http://alteredqualia.com/
  13264. * @author bhouston / https://clara.io
  13265. * @author WestLangley / http://github.com/WestLangley
  13266. *
  13267. * parameters = {
  13268. *
  13269. * opacity: <float>,
  13270. *
  13271. * map: new THREE.Texture( <Image> ),
  13272. *
  13273. * alphaMap: new THREE.Texture( <Image> ),
  13274. *
  13275. * displacementMap: new THREE.Texture( <Image> ),
  13276. * displacementScale: <float>,
  13277. * displacementBias: <float>,
  13278. *
  13279. * wireframe: <boolean>,
  13280. * wireframeLinewidth: <float>
  13281. * }
  13282. */
  13283. function MeshDepthMaterial(parameters) {
  13284. Material.call(this);
  13285. this.type = 'MeshDepthMaterial';
  13286. this.depthPacking = BasicDepthPacking;
  13287. this.skinning = false;
  13288. this.morphTargets = false;
  13289. this.map = null;
  13290. this.alphaMap = null;
  13291. this.displacementMap = null;
  13292. this.displacementScale = 1;
  13293. this.displacementBias = 0;
  13294. this.wireframe = false;
  13295. this.wireframeLinewidth = 1;
  13296. this.fog = false;
  13297. this.setValues(parameters);
  13298. }
  13299. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  13300. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  13301. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13302. MeshDepthMaterial.prototype.copy = function (source) {
  13303. Material.prototype.copy.call(this, source);
  13304. this.depthPacking = source.depthPacking;
  13305. this.skinning = source.skinning;
  13306. this.morphTargets = source.morphTargets;
  13307. this.map = source.map;
  13308. this.alphaMap = source.alphaMap;
  13309. this.displacementMap = source.displacementMap;
  13310. this.displacementScale = source.displacementScale;
  13311. this.displacementBias = source.displacementBias;
  13312. this.wireframe = source.wireframe;
  13313. this.wireframeLinewidth = source.wireframeLinewidth;
  13314. return this;
  13315. };
  13316. /**
  13317. * @author WestLangley / http://github.com/WestLangley
  13318. *
  13319. * parameters = {
  13320. *
  13321. * referencePosition: <float>,
  13322. * nearDistance: <float>,
  13323. * farDistance: <float>,
  13324. *
  13325. * skinning: <bool>,
  13326. * morphTargets: <bool>,
  13327. *
  13328. * map: new THREE.Texture( <Image> ),
  13329. *
  13330. * alphaMap: new THREE.Texture( <Image> ),
  13331. *
  13332. * displacementMap: new THREE.Texture( <Image> ),
  13333. * displacementScale: <float>,
  13334. * displacementBias: <float>
  13335. *
  13336. * }
  13337. */
  13338. function MeshDistanceMaterial(parameters) {
  13339. Material.call(this);
  13340. this.type = 'MeshDistanceMaterial';
  13341. this.referencePosition = new Vector3();
  13342. this.nearDistance = 1;
  13343. this.farDistance = 1000;
  13344. this.skinning = false;
  13345. this.morphTargets = false;
  13346. this.map = null;
  13347. this.alphaMap = null;
  13348. this.displacementMap = null;
  13349. this.displacementScale = 1;
  13350. this.displacementBias = 0;
  13351. this.fog = false;
  13352. this.setValues(parameters);
  13353. }
  13354. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  13355. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  13356. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13357. MeshDistanceMaterial.prototype.copy = function (source) {
  13358. Material.prototype.copy.call(this, source);
  13359. this.referencePosition.copy(source.referencePosition);
  13360. this.nearDistance = source.nearDistance;
  13361. this.farDistance = source.farDistance;
  13362. this.skinning = source.skinning;
  13363. this.morphTargets = source.morphTargets;
  13364. this.map = source.map;
  13365. this.alphaMap = source.alphaMap;
  13366. this.displacementMap = source.displacementMap;
  13367. this.displacementScale = source.displacementScale;
  13368. this.displacementBias = source.displacementBias;
  13369. return this;
  13370. };
  13371. 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 \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 = decodeHalfRGBA ( 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 = pow( squared_mean - mean * mean, 0.5 );\n gl_FragColor = encodeHalfRGBA( vec2( mean, std_dev ) );\n}";
  13372. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13373. /**
  13374. * @author alteredq / http://alteredqualia.com/
  13375. * @author mrdoob / http://mrdoob.com/
  13376. */
  13377. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  13378. var _frustum = new Frustum(),
  13379. _shadowMapSize = new Vector2(),
  13380. _viewportSize = new Vector2(),
  13381. _viewport = new Vector4(),
  13382. _MorphingFlag = 1,
  13383. _SkinningFlag = 2,
  13384. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  13385. _depthMaterials = new Array(_NumberOfMaterialVariants),
  13386. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  13387. _materialCache = {};
  13388. var shadowSide = {
  13389. 0: BackSide,
  13390. 1: FrontSide,
  13391. 2: DoubleSide
  13392. };
  13393. var shadowMaterialVertical = new ShaderMaterial({
  13394. defines: {
  13395. SAMPLE_RATE: 2.0 / 8.0,
  13396. HALF_SAMPLE_RATE: 1.0 / 8.0
  13397. },
  13398. uniforms: {
  13399. shadow_pass: {
  13400. value: null
  13401. },
  13402. resolution: {
  13403. value: new Vector2()
  13404. },
  13405. radius: {
  13406. value: 4.0
  13407. }
  13408. },
  13409. vertexShader: vsm_vert,
  13410. fragmentShader: vsm_frag
  13411. });
  13412. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  13413. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  13414. var fullScreenTri = new BufferGeometry();
  13415. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  13416. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  13417. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  13418. var useMorphing = (i & _MorphingFlag) !== 0;
  13419. var useSkinning = (i & _SkinningFlag) !== 0;
  13420. var depthMaterial = new MeshDepthMaterial({
  13421. depthPacking: RGBADepthPacking,
  13422. morphTargets: useMorphing,
  13423. skinning: useSkinning
  13424. });
  13425. _depthMaterials[i] = depthMaterial;
  13426. var distanceMaterial = new MeshDistanceMaterial({
  13427. morphTargets: useMorphing,
  13428. skinning: useSkinning
  13429. });
  13430. _distanceMaterials[i] = distanceMaterial;
  13431. }
  13432. var scope = this;
  13433. this.enabled = false;
  13434. this.autoUpdate = true;
  13435. this.needsUpdate = false;
  13436. this.type = PCFShadowMap;
  13437. this.render = function (lights, scene, camera) {
  13438. if (scope.enabled === false) return;
  13439. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  13440. if (lights.length === 0) return;
  13441. var currentRenderTarget = _renderer.getRenderTarget();
  13442. var activeCubeFace = _renderer.getActiveCubeFace();
  13443. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13444. var _state = _renderer.state; // Set GL state for depth map.
  13445. _state.setBlending(NoBlending);
  13446. _state.buffers.color.setClear(1, 1, 1, 1);
  13447. _state.buffers.depth.setTest(true);
  13448. _state.setScissorTest(false); // render depth map
  13449. for (var i = 0, il = lights.length; i < il; i++) {
  13450. var light = lights[i];
  13451. var shadow = light.shadow;
  13452. if (shadow === undefined) {
  13453. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  13454. continue;
  13455. }
  13456. _shadowMapSize.copy(shadow.mapSize);
  13457. var shadowFrameExtents = shadow.getFrameExtents();
  13458. _shadowMapSize.multiply(shadowFrameExtents);
  13459. _viewportSize.copy(shadow.mapSize);
  13460. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  13461. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  13462. if (_shadowMapSize.x > maxTextureSize) {
  13463. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  13464. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13465. shadow.mapSize.x = _viewportSize.x;
  13466. }
  13467. if (_shadowMapSize.y > maxTextureSize) {
  13468. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  13469. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13470. shadow.mapSize.y = _viewportSize.y;
  13471. }
  13472. }
  13473. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13474. var pars = {
  13475. minFilter: LinearFilter,
  13476. magFilter: LinearFilter,
  13477. format: RGBAFormat
  13478. };
  13479. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13480. shadow.map.texture.name = light.name + ".shadowMap";
  13481. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13482. shadow.camera.updateProjectionMatrix();
  13483. }
  13484. if (shadow.map === null) {
  13485. var pars = {
  13486. minFilter: NearestFilter,
  13487. magFilter: NearestFilter,
  13488. format: RGBAFormat
  13489. };
  13490. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13491. shadow.map.texture.name = light.name + ".shadowMap";
  13492. shadow.camera.updateProjectionMatrix();
  13493. }
  13494. _renderer.setRenderTarget(shadow.map);
  13495. _renderer.clear();
  13496. var viewportCount = shadow.getViewportCount();
  13497. for (var vp = 0; vp < viewportCount; vp++) {
  13498. var viewport = shadow.getViewport(vp);
  13499. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  13500. _state.viewport(_viewport);
  13501. shadow.updateMatrices(light, camera, vp);
  13502. _frustum = shadow.getFrustum();
  13503. renderObject(scene, camera, shadow.camera, light, this.type);
  13504. } // do blur pass for VSM
  13505. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13506. VSMPass(shadow, camera);
  13507. }
  13508. }
  13509. scope.needsUpdate = false;
  13510. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13511. };
  13512. function VSMPass(shadow, camera) {
  13513. var geometry = _objects.update(fullScreenMesh); // vertical pass
  13514. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13515. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13516. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13517. _renderer.setRenderTarget(shadow.mapPass);
  13518. _renderer.clear();
  13519. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  13520. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13521. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  13522. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  13523. _renderer.setRenderTarget(shadow.map);
  13524. _renderer.clear();
  13525. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  13526. }
  13527. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13528. var geometry = object.geometry;
  13529. var result = null;
  13530. var materialVariants = _depthMaterials;
  13531. var customMaterial = object.customDepthMaterial;
  13532. if (light.isPointLight) {
  13533. materialVariants = _distanceMaterials;
  13534. customMaterial = object.customDistanceMaterial;
  13535. }
  13536. if (!customMaterial) {
  13537. var useMorphing = false;
  13538. if (material.morphTargets) {
  13539. if (geometry && geometry.isBufferGeometry) {
  13540. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  13541. } else if (geometry && geometry.isGeometry) {
  13542. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  13543. }
  13544. }
  13545. if (object.isSkinnedMesh && material.skinning === false) {
  13546. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  13547. }
  13548. var useSkinning = object.isSkinnedMesh && material.skinning;
  13549. var variantIndex = 0;
  13550. if (useMorphing) variantIndex |= _MorphingFlag;
  13551. if (useSkinning) variantIndex |= _SkinningFlag;
  13552. result = materialVariants[variantIndex];
  13553. } else {
  13554. result = customMaterial;
  13555. }
  13556. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  13557. // in this case we need a unique material instance reflecting the
  13558. // appropriate state
  13559. var keyA = result.uuid,
  13560. keyB = material.uuid;
  13561. var materialsForVariant = _materialCache[keyA];
  13562. if (materialsForVariant === undefined) {
  13563. materialsForVariant = {};
  13564. _materialCache[keyA] = materialsForVariant;
  13565. }
  13566. var cachedMaterial = materialsForVariant[keyB];
  13567. if (cachedMaterial === undefined) {
  13568. cachedMaterial = result.clone();
  13569. materialsForVariant[keyB] = cachedMaterial;
  13570. }
  13571. result = cachedMaterial;
  13572. }
  13573. result.visible = material.visible;
  13574. result.wireframe = material.wireframe;
  13575. if (type === VSMShadowMap) {
  13576. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  13577. } else {
  13578. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  13579. }
  13580. result.clipShadows = material.clipShadows;
  13581. result.clippingPlanes = material.clippingPlanes;
  13582. result.clipIntersection = material.clipIntersection;
  13583. result.wireframeLinewidth = material.wireframeLinewidth;
  13584. result.linewidth = material.linewidth;
  13585. if (light.isPointLight && result.isMeshDistanceMaterial) {
  13586. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13587. result.nearDistance = shadowCameraNear;
  13588. result.farDistance = shadowCameraFar;
  13589. }
  13590. return result;
  13591. }
  13592. function renderObject(object, camera, shadowCamera, light, type) {
  13593. if (object.visible === false) return;
  13594. var visible = object.layers.test(camera.layers);
  13595. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13596. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13597. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13598. var geometry = _objects.update(object);
  13599. var material = object.material;
  13600. if (Array.isArray(material)) {
  13601. var groups = geometry.groups;
  13602. for (var k = 0, kl = groups.length; k < kl; k++) {
  13603. var group = groups[k];
  13604. var groupMaterial = material[group.materialIndex];
  13605. if (groupMaterial && groupMaterial.visible) {
  13606. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13607. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13608. }
  13609. }
  13610. } else if (material.visible) {
  13611. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13612. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13613. }
  13614. }
  13615. }
  13616. var children = object.children;
  13617. for (var i = 0, l = children.length; i < l; i++) {
  13618. renderObject(children[i], camera, shadowCamera, light, type);
  13619. }
  13620. }
  13621. }
  13622. /**
  13623. * @author mrdoob / http://mrdoob.com/
  13624. */
  13625. function WebGLState(gl, extensions, utils, capabilities) {
  13626. function ColorBuffer() {
  13627. var locked = false;
  13628. var color = new Vector4();
  13629. var currentColorMask = null;
  13630. var currentColorClear = new Vector4(0, 0, 0, 0);
  13631. return {
  13632. setMask: function (colorMask) {
  13633. if (currentColorMask !== colorMask && !locked) {
  13634. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13635. currentColorMask = colorMask;
  13636. }
  13637. },
  13638. setLocked: function (lock) {
  13639. locked = lock;
  13640. },
  13641. setClear: function (r, g, b, a, premultipliedAlpha) {
  13642. if (premultipliedAlpha === true) {
  13643. r *= a;
  13644. g *= a;
  13645. b *= a;
  13646. }
  13647. color.set(r, g, b, a);
  13648. if (currentColorClear.equals(color) === false) {
  13649. gl.clearColor(r, g, b, a);
  13650. currentColorClear.copy(color);
  13651. }
  13652. },
  13653. reset: function () {
  13654. locked = false;
  13655. currentColorMask = null;
  13656. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13657. }
  13658. };
  13659. }
  13660. function DepthBuffer() {
  13661. var locked = false;
  13662. var currentDepthMask = null;
  13663. var currentDepthFunc = null;
  13664. var currentDepthClear = null;
  13665. return {
  13666. setTest: function (depthTest) {
  13667. if (depthTest) {
  13668. enable(2929);
  13669. } else {
  13670. disable(2929);
  13671. }
  13672. },
  13673. setMask: function (depthMask) {
  13674. if (currentDepthMask !== depthMask && !locked) {
  13675. gl.depthMask(depthMask);
  13676. currentDepthMask = depthMask;
  13677. }
  13678. },
  13679. setFunc: function (depthFunc) {
  13680. if (currentDepthFunc !== depthFunc) {
  13681. if (depthFunc) {
  13682. switch (depthFunc) {
  13683. case NeverDepth:
  13684. gl.depthFunc(512);
  13685. break;
  13686. case AlwaysDepth:
  13687. gl.depthFunc(519);
  13688. break;
  13689. case LessDepth:
  13690. gl.depthFunc(513);
  13691. break;
  13692. case LessEqualDepth:
  13693. gl.depthFunc(515);
  13694. break;
  13695. case EqualDepth:
  13696. gl.depthFunc(514);
  13697. break;
  13698. case GreaterEqualDepth:
  13699. gl.depthFunc(518);
  13700. break;
  13701. case GreaterDepth:
  13702. gl.depthFunc(516);
  13703. break;
  13704. case NotEqualDepth:
  13705. gl.depthFunc(517);
  13706. break;
  13707. default:
  13708. gl.depthFunc(515);
  13709. }
  13710. } else {
  13711. gl.depthFunc(515);
  13712. }
  13713. currentDepthFunc = depthFunc;
  13714. }
  13715. },
  13716. setLocked: function (lock) {
  13717. locked = lock;
  13718. },
  13719. setClear: function (depth) {
  13720. if (currentDepthClear !== depth) {
  13721. gl.clearDepth(depth);
  13722. currentDepthClear = depth;
  13723. }
  13724. },
  13725. reset: function () {
  13726. locked = false;
  13727. currentDepthMask = null;
  13728. currentDepthFunc = null;
  13729. currentDepthClear = null;
  13730. }
  13731. };
  13732. }
  13733. function StencilBuffer() {
  13734. var locked = false;
  13735. var currentStencilMask = null;
  13736. var currentStencilFunc = null;
  13737. var currentStencilRef = null;
  13738. var currentStencilFuncMask = null;
  13739. var currentStencilFail = null;
  13740. var currentStencilZFail = null;
  13741. var currentStencilZPass = null;
  13742. var currentStencilClear = null;
  13743. return {
  13744. setTest: function (stencilTest) {
  13745. if (!locked) {
  13746. if (stencilTest) {
  13747. enable(2960);
  13748. } else {
  13749. disable(2960);
  13750. }
  13751. }
  13752. },
  13753. setMask: function (stencilMask) {
  13754. if (currentStencilMask !== stencilMask && !locked) {
  13755. gl.stencilMask(stencilMask);
  13756. currentStencilMask = stencilMask;
  13757. }
  13758. },
  13759. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13760. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13761. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13762. currentStencilFunc = stencilFunc;
  13763. currentStencilRef = stencilRef;
  13764. currentStencilFuncMask = stencilMask;
  13765. }
  13766. },
  13767. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13768. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13769. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13770. currentStencilFail = stencilFail;
  13771. currentStencilZFail = stencilZFail;
  13772. currentStencilZPass = stencilZPass;
  13773. }
  13774. },
  13775. setLocked: function (lock) {
  13776. locked = lock;
  13777. },
  13778. setClear: function (stencil) {
  13779. if (currentStencilClear !== stencil) {
  13780. gl.clearStencil(stencil);
  13781. currentStencilClear = stencil;
  13782. }
  13783. },
  13784. reset: function () {
  13785. locked = false;
  13786. currentStencilMask = null;
  13787. currentStencilFunc = null;
  13788. currentStencilRef = null;
  13789. currentStencilFuncMask = null;
  13790. currentStencilFail = null;
  13791. currentStencilZFail = null;
  13792. currentStencilZPass = null;
  13793. currentStencilClear = null;
  13794. }
  13795. };
  13796. } //
  13797. var colorBuffer = new ColorBuffer();
  13798. var depthBuffer = new DepthBuffer();
  13799. var stencilBuffer = new StencilBuffer();
  13800. var maxVertexAttributes = gl.getParameter(34921);
  13801. var newAttributes = new Uint8Array(maxVertexAttributes);
  13802. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13803. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13804. var enabledCapabilities = {};
  13805. var compressedTextureFormats = null;
  13806. var currentProgram = null;
  13807. var currentBlendingEnabled = null;
  13808. var currentBlending = null;
  13809. var currentBlendEquation = null;
  13810. var currentBlendSrc = null;
  13811. var currentBlendDst = null;
  13812. var currentBlendEquationAlpha = null;
  13813. var currentBlendSrcAlpha = null;
  13814. var currentBlendDstAlpha = null;
  13815. var currentPremultipledAlpha = false;
  13816. var currentFlipSided = null;
  13817. var currentCullFace = null;
  13818. var currentLineWidth = null;
  13819. var currentPolygonOffsetFactor = null;
  13820. var currentPolygonOffsetUnits = null;
  13821. var maxTextures = gl.getParameter(35661);
  13822. var lineWidthAvailable = false;
  13823. var version = 0;
  13824. var glVersion = gl.getParameter(7938);
  13825. if (glVersion.indexOf('WebGL') !== -1) {
  13826. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13827. lineWidthAvailable = version >= 1.0;
  13828. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13829. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13830. lineWidthAvailable = version >= 2.0;
  13831. }
  13832. var currentTextureSlot = null;
  13833. var currentBoundTextures = {};
  13834. var currentScissor = new Vector4();
  13835. var currentViewport = new Vector4();
  13836. function createTexture(type, target, count) {
  13837. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13838. var texture = gl.createTexture();
  13839. gl.bindTexture(type, texture);
  13840. gl.texParameteri(type, 10241, 9728);
  13841. gl.texParameteri(type, 10240, 9728);
  13842. for (var i = 0; i < count; i++) {
  13843. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13844. }
  13845. return texture;
  13846. }
  13847. var emptyTextures = {};
  13848. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13849. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13850. colorBuffer.setClear(0, 0, 0, 1);
  13851. depthBuffer.setClear(1);
  13852. stencilBuffer.setClear(0);
  13853. enable(2929);
  13854. depthBuffer.setFunc(LessEqualDepth);
  13855. setFlipSided(false);
  13856. setCullFace(CullFaceBack);
  13857. enable(2884);
  13858. setBlending(NoBlending); //
  13859. function initAttributes() {
  13860. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13861. newAttributes[i] = 0;
  13862. }
  13863. }
  13864. function enableAttribute(attribute) {
  13865. enableAttributeAndDivisor(attribute, 0);
  13866. }
  13867. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13868. newAttributes[attribute] = 1;
  13869. if (enabledAttributes[attribute] === 0) {
  13870. gl.enableVertexAttribArray(attribute);
  13871. enabledAttributes[attribute] = 1;
  13872. }
  13873. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13874. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13875. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13876. attributeDivisors[attribute] = meshPerAttribute;
  13877. }
  13878. }
  13879. function disableUnusedAttributes() {
  13880. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13881. if (enabledAttributes[i] !== newAttributes[i]) {
  13882. gl.disableVertexAttribArray(i);
  13883. enabledAttributes[i] = 0;
  13884. }
  13885. }
  13886. }
  13887. function enable(id) {
  13888. if (enabledCapabilities[id] !== true) {
  13889. gl.enable(id);
  13890. enabledCapabilities[id] = true;
  13891. }
  13892. }
  13893. function disable(id) {
  13894. if (enabledCapabilities[id] !== false) {
  13895. gl.disable(id);
  13896. enabledCapabilities[id] = false;
  13897. }
  13898. }
  13899. function getCompressedTextureFormats() {
  13900. if (compressedTextureFormats === null) {
  13901. compressedTextureFormats = [];
  13902. if (extensions.get('WEBGL_compressed_texture_pvrtc') || extensions.get('WEBGL_compressed_texture_s3tc') || extensions.get('WEBGL_compressed_texture_etc1') || extensions.get('WEBGL_compressed_texture_astc')) {
  13903. var formats = gl.getParameter(34467);
  13904. for (var i = 0; i < formats.length; i++) {
  13905. compressedTextureFormats.push(formats[i]);
  13906. }
  13907. }
  13908. }
  13909. return compressedTextureFormats;
  13910. }
  13911. function useProgram(program) {
  13912. if (currentProgram !== program) {
  13913. gl.useProgram(program);
  13914. currentProgram = program;
  13915. return true;
  13916. }
  13917. return false;
  13918. }
  13919. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13920. if (blending === NoBlending) {
  13921. if (currentBlendingEnabled) {
  13922. disable(3042);
  13923. currentBlendingEnabled = false;
  13924. }
  13925. return;
  13926. }
  13927. if (!currentBlendingEnabled) {
  13928. enable(3042);
  13929. currentBlendingEnabled = true;
  13930. }
  13931. if (blending !== CustomBlending) {
  13932. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13933. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13934. gl.blendEquation(32774);
  13935. currentBlendEquation = AddEquation;
  13936. currentBlendEquationAlpha = AddEquation;
  13937. }
  13938. if (premultipliedAlpha) {
  13939. switch (blending) {
  13940. case NormalBlending:
  13941. gl.blendFuncSeparate(1, 771, 1, 771);
  13942. break;
  13943. case AdditiveBlending:
  13944. gl.blendFunc(1, 1);
  13945. break;
  13946. case SubtractiveBlending:
  13947. gl.blendFuncSeparate(0, 0, 769, 771);
  13948. break;
  13949. case MultiplyBlending:
  13950. gl.blendFuncSeparate(0, 768, 0, 770);
  13951. break;
  13952. default:
  13953. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13954. break;
  13955. }
  13956. } else {
  13957. switch (blending) {
  13958. case NormalBlending:
  13959. gl.blendFuncSeparate(770, 771, 1, 771);
  13960. break;
  13961. case AdditiveBlending:
  13962. gl.blendFunc(770, 1);
  13963. break;
  13964. case SubtractiveBlending:
  13965. gl.blendFunc(0, 769);
  13966. break;
  13967. case MultiplyBlending:
  13968. gl.blendFunc(0, 768);
  13969. break;
  13970. default:
  13971. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13972. break;
  13973. }
  13974. }
  13975. currentBlendSrc = null;
  13976. currentBlendDst = null;
  13977. currentBlendSrcAlpha = null;
  13978. currentBlendDstAlpha = null;
  13979. currentBlending = blending;
  13980. currentPremultipledAlpha = premultipliedAlpha;
  13981. }
  13982. return;
  13983. } // custom blending
  13984. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13985. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13986. blendDstAlpha = blendDstAlpha || blendDst;
  13987. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13988. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  13989. currentBlendEquation = blendEquation;
  13990. currentBlendEquationAlpha = blendEquationAlpha;
  13991. }
  13992. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13993. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  13994. currentBlendSrc = blendSrc;
  13995. currentBlendDst = blendDst;
  13996. currentBlendSrcAlpha = blendSrcAlpha;
  13997. currentBlendDstAlpha = blendDstAlpha;
  13998. }
  13999. currentBlending = blending;
  14000. currentPremultipledAlpha = null;
  14001. }
  14002. function setMaterial(material, frontFaceCW) {
  14003. material.side === DoubleSide ? disable(2884) : enable(2884);
  14004. var flipSided = material.side === BackSide;
  14005. if (frontFaceCW) flipSided = !flipSided;
  14006. setFlipSided(flipSided);
  14007. 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);
  14008. depthBuffer.setFunc(material.depthFunc);
  14009. depthBuffer.setTest(material.depthTest);
  14010. depthBuffer.setMask(material.depthWrite);
  14011. colorBuffer.setMask(material.colorWrite);
  14012. var stencilWrite = material.stencilWrite;
  14013. stencilBuffer.setTest(stencilWrite);
  14014. if (stencilWrite) {
  14015. stencilBuffer.setMask(material.stencilWriteMask);
  14016. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  14017. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  14018. }
  14019. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  14020. } //
  14021. function setFlipSided(flipSided) {
  14022. if (currentFlipSided !== flipSided) {
  14023. if (flipSided) {
  14024. gl.frontFace(2304);
  14025. } else {
  14026. gl.frontFace(2305);
  14027. }
  14028. currentFlipSided = flipSided;
  14029. }
  14030. }
  14031. function setCullFace(cullFace) {
  14032. if (cullFace !== CullFaceNone) {
  14033. enable(2884);
  14034. if (cullFace !== currentCullFace) {
  14035. if (cullFace === CullFaceBack) {
  14036. gl.cullFace(1029);
  14037. } else if (cullFace === CullFaceFront) {
  14038. gl.cullFace(1028);
  14039. } else {
  14040. gl.cullFace(1032);
  14041. }
  14042. }
  14043. } else {
  14044. disable(2884);
  14045. }
  14046. currentCullFace = cullFace;
  14047. }
  14048. function setLineWidth(width) {
  14049. if (width !== currentLineWidth) {
  14050. if (lineWidthAvailable) gl.lineWidth(width);
  14051. currentLineWidth = width;
  14052. }
  14053. }
  14054. function setPolygonOffset(polygonOffset, factor, units) {
  14055. if (polygonOffset) {
  14056. enable(32823);
  14057. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  14058. gl.polygonOffset(factor, units);
  14059. currentPolygonOffsetFactor = factor;
  14060. currentPolygonOffsetUnits = units;
  14061. }
  14062. } else {
  14063. disable(32823);
  14064. }
  14065. }
  14066. function setScissorTest(scissorTest) {
  14067. if (scissorTest) {
  14068. enable(3089);
  14069. } else {
  14070. disable(3089);
  14071. }
  14072. } // texture
  14073. function activeTexture(webglSlot) {
  14074. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  14075. if (currentTextureSlot !== webglSlot) {
  14076. gl.activeTexture(webglSlot);
  14077. currentTextureSlot = webglSlot;
  14078. }
  14079. }
  14080. function bindTexture(webglType, webglTexture) {
  14081. if (currentTextureSlot === null) {
  14082. activeTexture();
  14083. }
  14084. var boundTexture = currentBoundTextures[currentTextureSlot];
  14085. if (boundTexture === undefined) {
  14086. boundTexture = {
  14087. type: undefined,
  14088. texture: undefined
  14089. };
  14090. currentBoundTextures[currentTextureSlot] = boundTexture;
  14091. }
  14092. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  14093. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  14094. boundTexture.type = webglType;
  14095. boundTexture.texture = webglTexture;
  14096. }
  14097. }
  14098. function compressedTexImage2D() {
  14099. try {
  14100. gl.compressedTexImage2D.apply(gl, arguments);
  14101. } catch (error) {
  14102. console.error('THREE.WebGLState:', error);
  14103. }
  14104. }
  14105. function texImage2D() {
  14106. try {
  14107. gl.texImage2D.apply(gl, arguments);
  14108. } catch (error) {
  14109. console.error('THREE.WebGLState:', error);
  14110. }
  14111. }
  14112. function texImage3D() {
  14113. try {
  14114. gl.texImage3D.apply(gl, arguments);
  14115. } catch (error) {
  14116. console.error('THREE.WebGLState:', error);
  14117. }
  14118. } //
  14119. function scissor(scissor) {
  14120. if (currentScissor.equals(scissor) === false) {
  14121. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  14122. currentScissor.copy(scissor);
  14123. }
  14124. }
  14125. function viewport(viewport) {
  14126. if (currentViewport.equals(viewport) === false) {
  14127. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  14128. currentViewport.copy(viewport);
  14129. }
  14130. } //
  14131. function reset() {
  14132. for (var i = 0; i < enabledAttributes.length; i++) {
  14133. if (enabledAttributes[i] === 1) {
  14134. gl.disableVertexAttribArray(i);
  14135. enabledAttributes[i] = 0;
  14136. }
  14137. }
  14138. enabledCapabilities = {};
  14139. compressedTextureFormats = null;
  14140. currentTextureSlot = null;
  14141. currentBoundTextures = {};
  14142. currentProgram = null;
  14143. currentBlending = null;
  14144. currentFlipSided = null;
  14145. currentCullFace = null;
  14146. colorBuffer.reset();
  14147. depthBuffer.reset();
  14148. stencilBuffer.reset();
  14149. }
  14150. return {
  14151. buffers: {
  14152. color: colorBuffer,
  14153. depth: depthBuffer,
  14154. stencil: stencilBuffer
  14155. },
  14156. initAttributes: initAttributes,
  14157. enableAttribute: enableAttribute,
  14158. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14159. disableUnusedAttributes: disableUnusedAttributes,
  14160. enable: enable,
  14161. disable: disable,
  14162. getCompressedTextureFormats: getCompressedTextureFormats,
  14163. useProgram: useProgram,
  14164. setBlending: setBlending,
  14165. setMaterial: setMaterial,
  14166. setFlipSided: setFlipSided,
  14167. setCullFace: setCullFace,
  14168. setLineWidth: setLineWidth,
  14169. setPolygonOffset: setPolygonOffset,
  14170. setScissorTest: setScissorTest,
  14171. activeTexture: activeTexture,
  14172. bindTexture: bindTexture,
  14173. compressedTexImage2D: compressedTexImage2D,
  14174. texImage2D: texImage2D,
  14175. texImage3D: texImage3D,
  14176. scissor: scissor,
  14177. viewport: viewport,
  14178. reset: reset
  14179. };
  14180. }
  14181. /**
  14182. * @author mrdoob / http://mrdoob.com/
  14183. */
  14184. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  14185. var _videoTextures = new WeakMap();
  14186. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14187. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14188. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  14189. function createCanvas(width, height) {
  14190. // Use OffscreenCanvas when available. Specially needed in web workers
  14191. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14192. }
  14193. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  14194. var scale = 1; // handle case if texture exceeds max size
  14195. if (image.width > maxSize || image.height > maxSize) {
  14196. scale = maxSize / Math.max(image.width, image.height);
  14197. } // only perform resize if necessary
  14198. if (scale < 1 || needsPowerOfTwo === true) {
  14199. // only perform resize for certain image types
  14200. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  14201. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  14202. var width = floor(scale * image.width);
  14203. var height = floor(scale * image.height);
  14204. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  14205. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  14206. canvas.width = width;
  14207. canvas.height = height;
  14208. var context = canvas.getContext('2d');
  14209. context.drawImage(image, 0, 0, width, height);
  14210. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  14211. return canvas;
  14212. } else {
  14213. if ('data' in image) {
  14214. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  14215. }
  14216. return image;
  14217. }
  14218. }
  14219. return image;
  14220. }
  14221. function isPowerOfTwo(image) {
  14222. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  14223. }
  14224. function textureNeedsPowerOfTwo(texture) {
  14225. if (capabilities.isWebGL2) return false;
  14226. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14227. }
  14228. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  14229. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14230. }
  14231. function generateMipmap(target, texture, width, height) {
  14232. _gl.generateMipmap(target);
  14233. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  14234. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  14235. }
  14236. function getInternalFormat(glFormat, glType) {
  14237. if (!capabilities.isWebGL2) return glFormat;
  14238. var internalFormat = glFormat;
  14239. if (glFormat === 6403) {
  14240. if (glType === 5126) internalFormat = 33326;
  14241. if (glType === 5131) internalFormat = 33325;
  14242. if (glType === 5121) internalFormat = 33321;
  14243. }
  14244. if (glFormat === 6407) {
  14245. if (glType === 5126) internalFormat = 34837;
  14246. if (glType === 5131) internalFormat = 34843;
  14247. if (glType === 5121) internalFormat = 32849;
  14248. }
  14249. if (glFormat === 6408) {
  14250. if (glType === 5126) internalFormat = 34836;
  14251. if (glType === 5131) internalFormat = 34842;
  14252. if (glType === 5121) internalFormat = 32856;
  14253. }
  14254. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  14255. extensions.get('EXT_color_buffer_float');
  14256. } else if (internalFormat === 34843 || internalFormat === 34837) {
  14257. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  14258. }
  14259. return internalFormat;
  14260. } // Fallback filters for non-power-of-2 textures
  14261. function filterFallback(f) {
  14262. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  14263. return 9728;
  14264. }
  14265. return 9729;
  14266. } //
  14267. function onTextureDispose(event) {
  14268. var texture = event.target;
  14269. texture.removeEventListener('dispose', onTextureDispose);
  14270. deallocateTexture(texture);
  14271. if (texture.isVideoTexture) {
  14272. _videoTextures.delete(texture);
  14273. }
  14274. info.memory.textures--;
  14275. }
  14276. function onRenderTargetDispose(event) {
  14277. var renderTarget = event.target;
  14278. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  14279. deallocateRenderTarget(renderTarget);
  14280. info.memory.textures--;
  14281. } //
  14282. function deallocateTexture(texture) {
  14283. var textureProperties = properties.get(texture);
  14284. if (textureProperties.__webglInit === undefined) return;
  14285. _gl.deleteTexture(textureProperties.__webglTexture);
  14286. properties.remove(texture);
  14287. }
  14288. function deallocateRenderTarget(renderTarget) {
  14289. var renderTargetProperties = properties.get(renderTarget);
  14290. var textureProperties = properties.get(renderTarget.texture);
  14291. if (!renderTarget) return;
  14292. if (textureProperties.__webglTexture !== undefined) {
  14293. _gl.deleteTexture(textureProperties.__webglTexture);
  14294. }
  14295. if (renderTarget.depthTexture) {
  14296. renderTarget.depthTexture.dispose();
  14297. }
  14298. if (renderTarget.isWebGLRenderTargetCube) {
  14299. for (var i = 0; i < 6; i++) {
  14300. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14301. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14302. }
  14303. } else {
  14304. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14305. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14306. }
  14307. if (renderTarget.isWebGLMultiviewRenderTarget) {
  14308. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  14309. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  14310. info.memory.textures -= 2;
  14311. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  14312. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  14313. }
  14314. }
  14315. properties.remove(renderTarget.texture);
  14316. properties.remove(renderTarget);
  14317. } //
  14318. var textureUnits = 0;
  14319. function resetTextureUnits() {
  14320. textureUnits = 0;
  14321. }
  14322. function allocateTextureUnit() {
  14323. var textureUnit = textureUnits;
  14324. if (textureUnit >= capabilities.maxTextures) {
  14325. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  14326. }
  14327. textureUnits += 1;
  14328. return textureUnit;
  14329. } //
  14330. function setTexture2D(texture, slot) {
  14331. var textureProperties = properties.get(texture);
  14332. if (texture.isVideoTexture) updateVideoTexture(texture);
  14333. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14334. var image = texture.image;
  14335. if (image === undefined) {
  14336. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  14337. } else if (image.complete === false) {
  14338. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14339. } else {
  14340. uploadTexture(textureProperties, texture, slot);
  14341. return;
  14342. }
  14343. }
  14344. state.activeTexture(33984 + slot);
  14345. state.bindTexture(3553, textureProperties.__webglTexture);
  14346. }
  14347. function setTexture2DArray(texture, slot) {
  14348. var textureProperties = properties.get(texture);
  14349. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14350. uploadTexture(textureProperties, texture, slot);
  14351. return;
  14352. }
  14353. state.activeTexture(33984 + slot);
  14354. state.bindTexture(35866, textureProperties.__webglTexture);
  14355. }
  14356. function setTexture3D(texture, slot) {
  14357. var textureProperties = properties.get(texture);
  14358. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14359. uploadTexture(textureProperties, texture, slot);
  14360. return;
  14361. }
  14362. state.activeTexture(33984 + slot);
  14363. state.bindTexture(32879, textureProperties.__webglTexture);
  14364. }
  14365. function setTextureCube(texture, slot) {
  14366. if (texture.image.length !== 6) return;
  14367. var textureProperties = properties.get(texture);
  14368. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14369. initTexture(textureProperties, texture);
  14370. state.activeTexture(33984 + slot);
  14371. state.bindTexture(34067, textureProperties.__webglTexture);
  14372. _gl.pixelStorei(37440, texture.flipY);
  14373. var isCompressed = texture && texture.isCompressedTexture;
  14374. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14375. var cubeImage = [];
  14376. for (var i = 0; i < 6; i++) {
  14377. if (!isCompressed && !isDataTexture) {
  14378. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  14379. } else {
  14380. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14381. }
  14382. }
  14383. var image = cubeImage[0],
  14384. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14385. glFormat = utils.convert(texture.format),
  14386. glType = utils.convert(texture.type),
  14387. glInternalFormat = getInternalFormat(glFormat, glType);
  14388. setTextureParameters(34067, texture, supportsMips);
  14389. var mipmaps;
  14390. if (isCompressed) {
  14391. for (var i = 0; i < 6; i++) {
  14392. mipmaps = cubeImage[i].mipmaps;
  14393. for (var j = 0; j < mipmaps.length; j++) {
  14394. var mipmap = mipmaps[j];
  14395. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14396. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14397. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14398. } else {
  14399. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14400. }
  14401. } else {
  14402. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14403. }
  14404. }
  14405. }
  14406. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14407. } else {
  14408. mipmaps = texture.mipmaps;
  14409. for (var i = 0; i < 6; i++) {
  14410. if (isDataTexture) {
  14411. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14412. for (var j = 0; j < mipmaps.length; j++) {
  14413. var mipmap = mipmaps[j];
  14414. var mipmapImage = mipmap.image[i].image;
  14415. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14416. }
  14417. } else {
  14418. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14419. for (var j = 0; j < mipmaps.length; j++) {
  14420. var mipmap = mipmaps[j];
  14421. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14422. }
  14423. }
  14424. }
  14425. textureProperties.__maxMipLevel = mipmaps.length;
  14426. }
  14427. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14428. // We assume images for cube map have the same size.
  14429. generateMipmap(34067, texture, image.width, image.height);
  14430. }
  14431. textureProperties.__version = texture.version;
  14432. if (texture.onUpdate) texture.onUpdate(texture);
  14433. } else {
  14434. state.activeTexture(33984 + slot);
  14435. state.bindTexture(34067, textureProperties.__webglTexture);
  14436. }
  14437. }
  14438. function setTextureCubeDynamic(texture, slot) {
  14439. state.activeTexture(33984 + slot);
  14440. state.bindTexture(34067, properties.get(texture).__webglTexture);
  14441. }
  14442. function setTextureParameters(textureType, texture, supportsMips) {
  14443. var extension;
  14444. if (supportsMips) {
  14445. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  14446. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  14447. if (textureType === 32879 || textureType === 35866) {
  14448. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  14449. }
  14450. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  14451. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  14452. } else {
  14453. _gl.texParameteri(textureType, 10242, 33071);
  14454. _gl.texParameteri(textureType, 10243, 33071);
  14455. if (textureType === 32879 || textureType === 35866) {
  14456. _gl.texParameteri(textureType, 32882, 33071);
  14457. }
  14458. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14459. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14460. }
  14461. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  14462. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  14463. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14464. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14465. }
  14466. }
  14467. extension = extensions.get('EXT_texture_filter_anisotropic');
  14468. if (extension) {
  14469. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  14470. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  14471. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14472. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14473. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14474. }
  14475. }
  14476. }
  14477. function initTexture(textureProperties, texture) {
  14478. if (textureProperties.__webglInit === undefined) {
  14479. textureProperties.__webglInit = true;
  14480. texture.addEventListener('dispose', onTextureDispose);
  14481. textureProperties.__webglTexture = _gl.createTexture();
  14482. info.memory.textures++;
  14483. }
  14484. }
  14485. function uploadTexture(textureProperties, texture, slot) {
  14486. var textureType = 3553;
  14487. if (texture.isDataTexture2DArray) textureType = 35866;
  14488. if (texture.isDataTexture3D) textureType = 32879;
  14489. initTexture(textureProperties, texture);
  14490. state.activeTexture(33984 + slot);
  14491. state.bindTexture(textureType, textureProperties.__webglTexture);
  14492. _gl.pixelStorei(37440, texture.flipY);
  14493. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  14494. _gl.pixelStorei(3317, texture.unpackAlignment);
  14495. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  14496. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  14497. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14498. glFormat = utils.convert(texture.format),
  14499. glType = utils.convert(texture.type),
  14500. glInternalFormat = getInternalFormat(glFormat, glType);
  14501. setTextureParameters(textureType, texture, supportsMips);
  14502. var mipmap,
  14503. mipmaps = texture.mipmaps;
  14504. if (texture.isDepthTexture) {
  14505. // populate depth texture with dummy data
  14506. glInternalFormat = 6402;
  14507. if (texture.type === FloatType) {
  14508. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14509. glInternalFormat = 36012;
  14510. } else if (capabilities.isWebGL2) {
  14511. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14512. glInternalFormat = 33189;
  14513. }
  14514. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  14515. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14516. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14517. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14518. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14519. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14520. texture.type = UnsignedShortType;
  14521. glType = utils.convert(texture.type);
  14522. }
  14523. } // Depth stencil textures need the DEPTH_STENCIL internal format
  14524. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14525. if (texture.format === DepthStencilFormat) {
  14526. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14527. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14528. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14529. if (texture.type !== UnsignedInt248Type) {
  14530. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14531. texture.type = UnsignedInt248Type;
  14532. glType = utils.convert(texture.type);
  14533. }
  14534. }
  14535. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14536. } else if (texture.isDataTexture) {
  14537. // use manually created mipmaps if available
  14538. // if there are no manual mipmaps
  14539. // set 0 level mipmap and then use GL to generate other mipmap levels
  14540. if (mipmaps.length > 0 && supportsMips) {
  14541. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14542. mipmap = mipmaps[i];
  14543. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14544. }
  14545. texture.generateMipmaps = false;
  14546. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14547. } else {
  14548. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14549. textureProperties.__maxMipLevel = 0;
  14550. }
  14551. } else if (texture.isCompressedTexture) {
  14552. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14553. mipmap = mipmaps[i];
  14554. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14555. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14556. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14557. } else {
  14558. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14559. }
  14560. } else {
  14561. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14562. }
  14563. }
  14564. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14565. } else if (texture.isDataTexture2DArray) {
  14566. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14567. textureProperties.__maxMipLevel = 0;
  14568. } else if (texture.isDataTexture3D) {
  14569. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14570. textureProperties.__maxMipLevel = 0;
  14571. } else {
  14572. // regular Texture (image, video, canvas)
  14573. // use manually created mipmaps if available
  14574. // if there are no manual mipmaps
  14575. // set 0 level mipmap and then use GL to generate other mipmap levels
  14576. if (mipmaps.length > 0 && supportsMips) {
  14577. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14578. mipmap = mipmaps[i];
  14579. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  14580. }
  14581. texture.generateMipmaps = false;
  14582. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14583. } else {
  14584. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  14585. textureProperties.__maxMipLevel = 0;
  14586. }
  14587. }
  14588. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14589. generateMipmap(3553, texture, image.width, image.height);
  14590. }
  14591. textureProperties.__version = texture.version;
  14592. if (texture.onUpdate) texture.onUpdate(texture);
  14593. } // Render targets
  14594. // Setup storage for target texture and bind it to correct framebuffer
  14595. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  14596. var glFormat = utils.convert(renderTarget.texture.format);
  14597. var glType = utils.convert(renderTarget.texture.type);
  14598. var glInternalFormat = getInternalFormat(glFormat, glType);
  14599. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14600. _gl.bindFramebuffer(36160, framebuffer);
  14601. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  14602. _gl.bindFramebuffer(36160, null);
  14603. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14604. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14605. _gl.bindRenderbuffer(36161, renderbuffer);
  14606. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14607. if (isMultisample) {
  14608. var samples = getRenderTargetSamples(renderTarget);
  14609. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  14610. } else {
  14611. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  14612. }
  14613. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  14614. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14615. if (isMultisample) {
  14616. var samples = getRenderTargetSamples(renderTarget);
  14617. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  14618. } else {
  14619. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  14620. }
  14621. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  14622. } else {
  14623. var glFormat = utils.convert(renderTarget.texture.format);
  14624. var glType = utils.convert(renderTarget.texture.type);
  14625. var glInternalFormat = getInternalFormat(glFormat, glType);
  14626. if (isMultisample) {
  14627. var samples = getRenderTargetSamples(renderTarget);
  14628. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14629. } else {
  14630. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  14631. }
  14632. }
  14633. _gl.bindRenderbuffer(36161, null);
  14634. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14635. function setupDepthTexture(framebuffer, renderTarget) {
  14636. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  14637. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14638. _gl.bindFramebuffer(36160, framebuffer);
  14639. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14640. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14641. } // upload an empty depth texture with framebuffer size
  14642. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14643. renderTarget.depthTexture.image.width = renderTarget.width;
  14644. renderTarget.depthTexture.image.height = renderTarget.height;
  14645. renderTarget.depthTexture.needsUpdate = true;
  14646. }
  14647. setTexture2D(renderTarget.depthTexture, 0);
  14648. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14649. if (renderTarget.depthTexture.format === DepthFormat) {
  14650. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  14651. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14652. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  14653. } else {
  14654. throw new Error('Unknown depthTexture format');
  14655. }
  14656. } // Setup GL resources for a non-texture depth buffer
  14657. function setupDepthRenderbuffer(renderTarget) {
  14658. var renderTargetProperties = properties.get(renderTarget);
  14659. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14660. if (renderTarget.depthTexture) {
  14661. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14662. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14663. } else {
  14664. if (isCube) {
  14665. renderTargetProperties.__webglDepthbuffer = [];
  14666. for (var i = 0; i < 6; i++) {
  14667. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  14668. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14669. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  14670. }
  14671. } else {
  14672. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14673. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14674. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  14675. }
  14676. }
  14677. _gl.bindFramebuffer(36160, null);
  14678. } // Set up GL resources for the render target
  14679. function setupRenderTarget(renderTarget) {
  14680. var renderTargetProperties = properties.get(renderTarget);
  14681. var textureProperties = properties.get(renderTarget.texture);
  14682. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14683. textureProperties.__webglTexture = _gl.createTexture();
  14684. info.memory.textures++;
  14685. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14686. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  14687. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  14688. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  14689. if (isCube) {
  14690. renderTargetProperties.__webglFramebuffer = [];
  14691. for (var i = 0; i < 6; i++) {
  14692. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14693. }
  14694. } else {
  14695. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14696. if (isMultisample) {
  14697. if (capabilities.isWebGL2) {
  14698. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14699. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14700. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  14701. var glFormat = utils.convert(renderTarget.texture.format);
  14702. var glType = utils.convert(renderTarget.texture.type);
  14703. var glInternalFormat = getInternalFormat(glFormat, glType);
  14704. var samples = getRenderTargetSamples(renderTarget);
  14705. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14706. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14707. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14708. _gl.bindRenderbuffer(36161, null);
  14709. if (renderTarget.depthBuffer) {
  14710. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14711. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14712. }
  14713. _gl.bindFramebuffer(36160, null);
  14714. } else {
  14715. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14716. }
  14717. } else if (isMultiview) {
  14718. var width = renderTarget.width;
  14719. var height = renderTarget.height;
  14720. var numViews = renderTarget.numViews;
  14721. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14722. var ext = extensions.get('OVR_multiview2');
  14723. info.memory.textures += 2;
  14724. var colorTexture = _gl.createTexture();
  14725. _gl.bindTexture(35866, colorTexture);
  14726. _gl.texParameteri(35866, 10240, 9728);
  14727. _gl.texParameteri(35866, 10241, 9728);
  14728. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  14729. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  14730. var depthStencilTexture = _gl.createTexture();
  14731. _gl.bindTexture(35866, depthStencilTexture);
  14732. _gl.texParameteri(35866, 10240, 9728);
  14733. _gl.texParameteri(35866, 10241, 9728);
  14734. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  14735. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  14736. var viewFramebuffers = new Array(numViews);
  14737. for (var i = 0; i < numViews; ++i) {
  14738. viewFramebuffers[i] = _gl.createFramebuffer();
  14739. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  14740. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  14741. }
  14742. renderTargetProperties.__webglColorTexture = colorTexture;
  14743. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  14744. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  14745. _gl.bindFramebuffer(36160, null);
  14746. _gl.bindTexture(35866, null);
  14747. }
  14748. } // Setup color buffer
  14749. if (isCube) {
  14750. state.bindTexture(34067, textureProperties.__webglTexture);
  14751. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14752. for (var i = 0; i < 6; i++) {
  14753. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14754. }
  14755. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14756. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14757. }
  14758. state.bindTexture(34067, null);
  14759. } else if (!isMultiview) {
  14760. state.bindTexture(3553, textureProperties.__webglTexture);
  14761. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14762. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14763. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14764. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14765. }
  14766. state.bindTexture(3553, null);
  14767. } // Setup depth and stencil buffers
  14768. if (renderTarget.depthBuffer) {
  14769. setupDepthRenderbuffer(renderTarget);
  14770. }
  14771. }
  14772. function updateRenderTargetMipmap(renderTarget) {
  14773. var texture = renderTarget.texture;
  14774. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  14775. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14776. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  14777. var webglTexture = properties.get(texture).__webglTexture;
  14778. state.bindTexture(target, webglTexture);
  14779. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14780. state.bindTexture(target, null);
  14781. }
  14782. }
  14783. function updateMultisampleRenderTarget(renderTarget) {
  14784. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14785. if (capabilities.isWebGL2) {
  14786. var renderTargetProperties = properties.get(renderTarget);
  14787. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14788. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14789. var width = renderTarget.width;
  14790. var height = renderTarget.height;
  14791. var mask = 16384;
  14792. if (renderTarget.depthBuffer) mask |= 256;
  14793. if (renderTarget.stencilBuffer) mask |= 1024;
  14794. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14795. } else {
  14796. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14797. }
  14798. }
  14799. }
  14800. function getRenderTargetSamples(renderTarget) {
  14801. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  14802. }
  14803. function updateVideoTexture(texture) {
  14804. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14805. if (_videoTextures.get(texture) !== frame) {
  14806. _videoTextures.set(texture, frame);
  14807. texture.update();
  14808. }
  14809. } // backwards compatibility
  14810. var warnedTexture2D = false;
  14811. var warnedTextureCube = false;
  14812. function safeSetTexture2D(texture, slot) {
  14813. if (texture && texture.isWebGLRenderTarget) {
  14814. if (warnedTexture2D === false) {
  14815. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14816. warnedTexture2D = true;
  14817. }
  14818. texture = texture.texture;
  14819. }
  14820. setTexture2D(texture, slot);
  14821. }
  14822. function safeSetTextureCube(texture, slot) {
  14823. if (texture && texture.isWebGLRenderTargetCube) {
  14824. if (warnedTextureCube === false) {
  14825. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14826. warnedTextureCube = true;
  14827. }
  14828. texture = texture.texture;
  14829. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  14830. // TODO: unify these code paths
  14831. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14832. // CompressedTexture can have Array in image :/
  14833. // this function alone should take care of cube textures
  14834. setTextureCube(texture, slot);
  14835. } else {
  14836. // assumed: texture property of THREE.WebGLRenderTargetCube
  14837. setTextureCubeDynamic(texture, slot);
  14838. }
  14839. } //
  14840. this.allocateTextureUnit = allocateTextureUnit;
  14841. this.resetTextureUnits = resetTextureUnits;
  14842. this.setTexture2D = setTexture2D;
  14843. this.setTexture2DArray = setTexture2DArray;
  14844. this.setTexture3D = setTexture3D;
  14845. this.setTextureCube = setTextureCube;
  14846. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14847. this.setupRenderTarget = setupRenderTarget;
  14848. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14849. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14850. this.safeSetTexture2D = safeSetTexture2D;
  14851. this.safeSetTextureCube = safeSetTextureCube;
  14852. }
  14853. /**
  14854. * @author thespite / http://www.twitter.com/thespite
  14855. */
  14856. function WebGLUtils(gl, extensions, capabilities) {
  14857. function convert(p) {
  14858. var extension;
  14859. if (p === RepeatWrapping) return 10497;
  14860. if (p === ClampToEdgeWrapping) return 33071;
  14861. if (p === MirroredRepeatWrapping) return 33648;
  14862. if (p === NearestFilter) return 9728;
  14863. if (p === NearestMipmapNearestFilter) return 9984;
  14864. if (p === NearestMipmapLinearFilter) return 9986;
  14865. if (p === LinearFilter) return 9729;
  14866. if (p === LinearMipmapNearestFilter) return 9985;
  14867. if (p === LinearMipmapLinearFilter) return 9987;
  14868. if (p === UnsignedByteType) return 5121;
  14869. if (p === UnsignedShort4444Type) return 32819;
  14870. if (p === UnsignedShort5551Type) return 32820;
  14871. if (p === UnsignedShort565Type) return 33635;
  14872. if (p === ByteType) return 5120;
  14873. if (p === ShortType) return 5122;
  14874. if (p === UnsignedShortType) return 5123;
  14875. if (p === IntType) return 5124;
  14876. if (p === UnsignedIntType) return 5125;
  14877. if (p === FloatType) return 5126;
  14878. if (p === HalfFloatType) {
  14879. if (capabilities.isWebGL2) return 5131;
  14880. extension = extensions.get('OES_texture_half_float');
  14881. if (extension !== null) return extension.HALF_FLOAT_OES;
  14882. }
  14883. if (p === AlphaFormat) return 6406;
  14884. if (p === RGBFormat) return 6407;
  14885. if (p === RGBAFormat) return 6408;
  14886. if (p === LuminanceFormat) return 6409;
  14887. if (p === LuminanceAlphaFormat) return 6410;
  14888. if (p === DepthFormat) return 6402;
  14889. if (p === DepthStencilFormat) return 34041;
  14890. if (p === RedFormat) return 6403;
  14891. if (p === AddEquation) return 32774;
  14892. if (p === SubtractEquation) return 32778;
  14893. if (p === ReverseSubtractEquation) return 32779;
  14894. if (p === ZeroFactor) return 0;
  14895. if (p === OneFactor) return 1;
  14896. if (p === SrcColorFactor) return 768;
  14897. if (p === OneMinusSrcColorFactor) return 769;
  14898. if (p === SrcAlphaFactor) return 770;
  14899. if (p === OneMinusSrcAlphaFactor) return 771;
  14900. if (p === DstAlphaFactor) return 772;
  14901. if (p === OneMinusDstAlphaFactor) return 773;
  14902. if (p === DstColorFactor) return 774;
  14903. if (p === OneMinusDstColorFactor) return 775;
  14904. if (p === SrcAlphaSaturateFactor) return 776;
  14905. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14906. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14907. if (extension !== null) {
  14908. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14909. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14910. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14911. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14912. }
  14913. }
  14914. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14915. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14916. if (extension !== null) {
  14917. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14918. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14919. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14920. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14921. }
  14922. }
  14923. if (p === RGB_ETC1_Format) {
  14924. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14925. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14926. }
  14927. 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) {
  14928. extension = extensions.get('WEBGL_compressed_texture_astc');
  14929. if (extension !== null) {
  14930. return p;
  14931. }
  14932. }
  14933. if (p === MinEquation || p === MaxEquation) {
  14934. if (capabilities.isWebGL2) {
  14935. if (p === MinEquation) return 32775;
  14936. if (p === MaxEquation) return 32776;
  14937. }
  14938. extension = extensions.get('EXT_blend_minmax');
  14939. if (extension !== null) {
  14940. if (p === MinEquation) return extension.MIN_EXT;
  14941. if (p === MaxEquation) return extension.MAX_EXT;
  14942. }
  14943. }
  14944. if (p === UnsignedInt248Type) {
  14945. if (capabilities.isWebGL2) return 34042;
  14946. extension = extensions.get('WEBGL_depth_texture');
  14947. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  14948. }
  14949. return 0;
  14950. }
  14951. return {
  14952. convert: convert
  14953. };
  14954. }
  14955. /**
  14956. * @author fernandojsg / http://fernandojsg.com
  14957. * @author Takahiro https://github.com/takahirox
  14958. */
  14959. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  14960. WebGLRenderTarget.call(this, width, height, options);
  14961. this.depthBuffer = false;
  14962. this.stencilBuffer = false;
  14963. this.numViews = numViews;
  14964. }
  14965. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  14966. constructor: WebGLMultiviewRenderTarget,
  14967. isWebGLMultiviewRenderTarget: true,
  14968. copy: function (source) {
  14969. WebGLRenderTarget.prototype.copy.call(this, source);
  14970. this.numViews = source.numViews;
  14971. return this;
  14972. },
  14973. setNumViews: function (numViews) {
  14974. if (this.numViews !== numViews) {
  14975. this.numViews = numViews;
  14976. this.dispose();
  14977. }
  14978. return this;
  14979. }
  14980. });
  14981. /**
  14982. * @author fernandojsg / http://fernandojsg.com
  14983. * @author Takahiro https://github.com/takahirox
  14984. */
  14985. function WebGLMultiview(renderer, gl) {
  14986. var DEFAULT_NUMVIEWS = 2;
  14987. var extensions = renderer.extensions;
  14988. var properties = renderer.properties;
  14989. var renderTarget, currentRenderTarget;
  14990. var mat3, mat4, cameraArray, renderSize;
  14991. var available;
  14992. var maxNumViews = 0; //
  14993. function isAvailable() {
  14994. if (available === undefined) {
  14995. var extension = extensions.get('OVR_multiview2');
  14996. available = extension !== null && gl.getContextAttributes().antialias === false;
  14997. if (available) {
  14998. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  14999. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  15000. renderSize = new Vector2();
  15001. mat4 = [];
  15002. mat3 = [];
  15003. cameraArray = [];
  15004. for (var i = 0; i < maxNumViews; i++) {
  15005. mat4[i] = new Matrix4();
  15006. mat3[i] = new Matrix3();
  15007. }
  15008. }
  15009. }
  15010. return available;
  15011. }
  15012. function getCameraArray(camera) {
  15013. if (camera.isArrayCamera) return camera.cameras;
  15014. cameraArray[0] = camera;
  15015. return cameraArray;
  15016. }
  15017. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  15018. var cameras = getCameraArray(camera);
  15019. for (var i = 0; i < cameras.length; i++) {
  15020. mat4[i].copy(cameras[i].projectionMatrix);
  15021. }
  15022. uniforms.setValue(gl, 'projectionMatrices', mat4);
  15023. }
  15024. function updateCameraViewMatricesUniform(camera, uniforms) {
  15025. var cameras = getCameraArray(camera);
  15026. for (var i = 0; i < cameras.length; i++) {
  15027. mat4[i].copy(cameras[i].matrixWorldInverse);
  15028. }
  15029. uniforms.setValue(gl, 'viewMatrices', mat4);
  15030. }
  15031. function updateObjectMatricesUniforms(object, camera, uniforms) {
  15032. var cameras = getCameraArray(camera);
  15033. for (var i = 0; i < cameras.length; i++) {
  15034. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  15035. mat3[i].getNormalMatrix(mat4[i]);
  15036. }
  15037. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  15038. uniforms.setValue(gl, 'normalMatrices', mat3);
  15039. }
  15040. function isMultiviewCompatible(camera) {
  15041. if (camera.isArrayCamera === undefined) return true;
  15042. var cameras = camera.cameras;
  15043. if (cameras.length > maxNumViews) return false;
  15044. for (var i = 1, il = cameras.length; i < il; i++) {
  15045. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  15046. }
  15047. return true;
  15048. }
  15049. function resizeRenderTarget(camera) {
  15050. if (currentRenderTarget) {
  15051. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  15052. } else {
  15053. renderer.getDrawingBufferSize(renderSize);
  15054. }
  15055. if (camera.isArrayCamera) {
  15056. var viewport = camera.cameras[0].viewport;
  15057. renderTarget.setSize(viewport.z, viewport.w);
  15058. renderTarget.setNumViews(camera.cameras.length);
  15059. } else {
  15060. renderTarget.setSize(renderSize.x, renderSize.y);
  15061. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  15062. }
  15063. }
  15064. function attachCamera(camera) {
  15065. if (isMultiviewCompatible(camera) === false) return;
  15066. currentRenderTarget = renderer.getRenderTarget();
  15067. resizeRenderTarget(camera);
  15068. renderer.setRenderTarget(renderTarget);
  15069. }
  15070. function detachCamera(camera) {
  15071. if (renderTarget !== renderer.getRenderTarget()) return;
  15072. renderer.setRenderTarget(currentRenderTarget);
  15073. flush(camera);
  15074. }
  15075. function flush(camera) {
  15076. var srcRenderTarget = renderTarget;
  15077. var numViews = srcRenderTarget.numViews;
  15078. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  15079. var viewWidth = srcRenderTarget.width;
  15080. var viewHeight = srcRenderTarget.height;
  15081. if (camera.isArrayCamera) {
  15082. for (var i = 0; i < numViews; i++) {
  15083. var viewport = camera.cameras[i].viewport;
  15084. var x1 = viewport.x;
  15085. var y1 = viewport.y;
  15086. var x2 = x1 + viewport.z;
  15087. var y2 = y1 + viewport.w;
  15088. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  15089. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  15090. }
  15091. } else {
  15092. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  15093. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  15094. }
  15095. }
  15096. this.isAvailable = isAvailable;
  15097. this.attachCamera = attachCamera;
  15098. this.detachCamera = detachCamera;
  15099. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  15100. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  15101. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  15102. }
  15103. /**
  15104. * @author mrdoob / http://mrdoob.com/
  15105. */
  15106. function Group() {
  15107. Object3D.call(this);
  15108. this.type = 'Group';
  15109. }
  15110. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  15111. constructor: Group,
  15112. isGroup: true
  15113. });
  15114. /**
  15115. * @author mrdoob / http://mrdoob.com/
  15116. */
  15117. function ArrayCamera(array) {
  15118. PerspectiveCamera.call(this);
  15119. this.cameras = array || [];
  15120. }
  15121. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  15122. constructor: ArrayCamera,
  15123. isArrayCamera: true
  15124. });
  15125. /**
  15126. * @author jsantell / https://www.jsantell.com/
  15127. * @author mrdoob / http://mrdoob.com/
  15128. */
  15129. var cameraLPos = new Vector3();
  15130. var cameraRPos = new Vector3();
  15131. /**
  15132. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15133. * the cameras' projection and world matrices have already been set.
  15134. * And that near and far planes are identical for both cameras.
  15135. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15136. */
  15137. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15138. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15139. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15140. var ipd = cameraLPos.distanceTo(cameraRPos);
  15141. var projL = cameraL.projectionMatrix.elements;
  15142. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15143. // most likely identical top and bottom frustum extents.
  15144. // Use the left camera for these values.
  15145. var near = projL[14] / (projL[10] - 1);
  15146. var far = projL[14] / (projL[10] + 1);
  15147. var topFov = (projL[9] + 1) / projL[5];
  15148. var bottomFov = (projL[9] - 1) / projL[5];
  15149. var leftFov = (projL[8] - 1) / projL[0];
  15150. var rightFov = (projR[8] + 1) / projR[0];
  15151. var left = near * leftFov;
  15152. var right = near * rightFov; // Calculate the new camera's position offset from the
  15153. // left camera. xOffset should be roughly half `ipd`.
  15154. var zOffset = ipd / (-leftFov + rightFov);
  15155. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15156. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15157. camera.translateX(xOffset);
  15158. camera.translateZ(zOffset);
  15159. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15160. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  15161. // the values so that the near plane's position does not change in world space,
  15162. // although must now be relative to the new union camera.
  15163. var near2 = near + zOffset;
  15164. var far2 = far + zOffset;
  15165. var left2 = left - xOffset;
  15166. var right2 = right + (ipd - xOffset);
  15167. var top2 = topFov * far / far2 * near2;
  15168. var bottom2 = bottomFov * far / far2 * near2;
  15169. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15170. }
  15171. /**
  15172. * @author mrdoob / http://mrdoob.com/
  15173. */
  15174. function WebVRManager(renderer) {
  15175. var renderWidth, renderHeight;
  15176. var scope = this;
  15177. var device = null;
  15178. var frameData = null;
  15179. var poseTarget = null;
  15180. var controllers = [];
  15181. var standingMatrix = new Matrix4();
  15182. var standingMatrixInverse = new Matrix4();
  15183. var framebufferScaleFactor = 1.0;
  15184. var referenceSpaceType = 'local-floor';
  15185. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  15186. frameData = new window.VRFrameData();
  15187. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  15188. }
  15189. var matrixWorldInverse = new Matrix4();
  15190. var tempQuaternion = new Quaternion();
  15191. var tempPosition = new Vector3();
  15192. var cameraL = new PerspectiveCamera();
  15193. cameraL.viewport = new Vector4();
  15194. cameraL.layers.enable(1);
  15195. var cameraR = new PerspectiveCamera();
  15196. cameraR.viewport = new Vector4();
  15197. cameraR.layers.enable(2);
  15198. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15199. cameraVR.layers.enable(1);
  15200. cameraVR.layers.enable(2); //
  15201. function isPresenting() {
  15202. return device !== null && device.isPresenting === true;
  15203. }
  15204. var currentSize = new Vector2(),
  15205. currentPixelRatio;
  15206. function onVRDisplayPresentChange() {
  15207. if (isPresenting()) {
  15208. var eyeParameters = device.getEyeParameters('left');
  15209. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  15210. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  15211. currentPixelRatio = renderer.getPixelRatio();
  15212. renderer.getSize(currentSize);
  15213. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  15214. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  15215. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  15216. animation.start();
  15217. scope.dispatchEvent({
  15218. type: 'sessionstart'
  15219. });
  15220. } else {
  15221. if (scope.enabled) {
  15222. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  15223. }
  15224. animation.stop();
  15225. scope.dispatchEvent({
  15226. type: 'sessionend'
  15227. });
  15228. }
  15229. } //
  15230. var triggers = [];
  15231. function findGamepad(id) {
  15232. var gamepads = navigator.getGamepads && navigator.getGamepads();
  15233. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  15234. var gamepad = gamepads[i];
  15235. if (gamepad && (gamepad.id === 'Daydream Controller' || gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith('Oculus Touch') || gamepad.id.startsWith('HTC Vive Focus') || gamepad.id.startsWith('Spatial Controller'))) {
  15236. if (j === id) return gamepad;
  15237. j++;
  15238. }
  15239. }
  15240. }
  15241. function updateControllers() {
  15242. for (var i = 0; i < controllers.length; i++) {
  15243. var controller = controllers[i];
  15244. var gamepad = findGamepad(i);
  15245. if (gamepad !== undefined && gamepad.pose !== undefined) {
  15246. if (gamepad.pose === null) return; // Pose
  15247. var pose = gamepad.pose;
  15248. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  15249. if (pose.position !== null) controller.position.fromArray(pose.position);
  15250. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  15251. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  15252. controller.matrix.premultiply(standingMatrix);
  15253. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  15254. controller.matrixWorldNeedsUpdate = true;
  15255. controller.visible = true; // Trigger
  15256. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  15257. if (triggers[i] === undefined) triggers[i] = false;
  15258. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  15259. triggers[i] = gamepad.buttons[buttonId].pressed;
  15260. if (triggers[i] === true) {
  15261. controller.dispatchEvent({
  15262. type: 'selectstart'
  15263. });
  15264. } else {
  15265. controller.dispatchEvent({
  15266. type: 'selectend'
  15267. });
  15268. controller.dispatchEvent({
  15269. type: 'select'
  15270. });
  15271. }
  15272. }
  15273. } else {
  15274. controller.visible = false;
  15275. }
  15276. }
  15277. }
  15278. function updateViewportFromBounds(viewport, bounds) {
  15279. if (bounds !== null && bounds.length === 4) {
  15280. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  15281. }
  15282. } //
  15283. this.enabled = false;
  15284. this.getController = function (id) {
  15285. var controller = controllers[id];
  15286. if (controller === undefined) {
  15287. controller = new Group();
  15288. controller.matrixAutoUpdate = false;
  15289. controller.visible = false;
  15290. controllers[id] = controller;
  15291. }
  15292. return controller;
  15293. };
  15294. this.getDevice = function () {
  15295. return device;
  15296. };
  15297. this.setDevice = function (value) {
  15298. if (value !== undefined) device = value;
  15299. animation.setContext(value);
  15300. };
  15301. this.setFramebufferScaleFactor = function (value) {
  15302. framebufferScaleFactor = value;
  15303. };
  15304. this.setReferenceSpaceType = function (value) {
  15305. referenceSpaceType = value;
  15306. };
  15307. this.setPoseTarget = function (object) {
  15308. if (object !== undefined) poseTarget = object;
  15309. };
  15310. this.getCamera = function (camera) {
  15311. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  15312. if (isPresenting() === false) {
  15313. camera.position.set(0, userHeight, 0);
  15314. camera.rotation.set(0, 0, 0);
  15315. return camera;
  15316. }
  15317. device.depthNear = camera.near;
  15318. device.depthFar = camera.far;
  15319. device.getFrameData(frameData); //
  15320. if (referenceSpaceType === 'local-floor') {
  15321. var stageParameters = device.stageParameters;
  15322. if (stageParameters) {
  15323. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  15324. } else {
  15325. standingMatrix.makeTranslation(0, userHeight, 0);
  15326. }
  15327. }
  15328. var pose = frameData.pose;
  15329. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  15330. poseObject.matrix.copy(standingMatrix);
  15331. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  15332. if (pose.orientation !== null) {
  15333. tempQuaternion.fromArray(pose.orientation);
  15334. poseObject.quaternion.multiply(tempQuaternion);
  15335. }
  15336. if (pose.position !== null) {
  15337. tempQuaternion.setFromRotationMatrix(standingMatrix);
  15338. tempPosition.fromArray(pose.position);
  15339. tempPosition.applyQuaternion(tempQuaternion);
  15340. poseObject.position.add(tempPosition);
  15341. }
  15342. poseObject.updateMatrixWorld(); //
  15343. cameraL.near = camera.near;
  15344. cameraR.near = camera.near;
  15345. cameraL.far = camera.far;
  15346. cameraR.far = camera.far;
  15347. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  15348. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  15349. standingMatrixInverse.getInverse(standingMatrix);
  15350. if (referenceSpaceType === 'local-floor') {
  15351. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  15352. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  15353. }
  15354. var parent = poseObject.parent;
  15355. if (parent !== null) {
  15356. matrixWorldInverse.getInverse(parent.matrixWorld);
  15357. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  15358. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  15359. } // envMap and Mirror needs camera.matrixWorld
  15360. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  15361. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  15362. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  15363. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  15364. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  15365. var layers = device.getLayers();
  15366. if (layers.length) {
  15367. var layer = layers[0];
  15368. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  15369. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  15370. }
  15371. updateControllers();
  15372. return cameraVR;
  15373. };
  15374. this.getStandingMatrix = function () {
  15375. return standingMatrix;
  15376. };
  15377. this.isPresenting = isPresenting; // Animation Loop
  15378. var animation = new WebGLAnimation();
  15379. this.setAnimationLoop = function (callback) {
  15380. animation.setAnimationLoop(callback);
  15381. if (isPresenting()) animation.start();
  15382. };
  15383. this.submitFrame = function () {
  15384. if (isPresenting()) device.submitFrame();
  15385. };
  15386. this.dispose = function () {
  15387. if (typeof window !== 'undefined') {
  15388. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  15389. }
  15390. }; // DEPRECATED
  15391. this.setFrameOfReferenceType = function () {
  15392. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  15393. };
  15394. }
  15395. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  15396. /**
  15397. * @author mrdoob / http://mrdoob.com/
  15398. */
  15399. function WebXRManager(renderer, gl) {
  15400. var scope = this;
  15401. var session = null; // var framebufferScaleFactor = 1.0;
  15402. var referenceSpace = null;
  15403. var referenceSpaceType = 'local-floor';
  15404. var pose = null;
  15405. var controllers = [];
  15406. var inputSources = [];
  15407. function isPresenting() {
  15408. return session !== null && referenceSpace !== null;
  15409. } //
  15410. var cameraL = new PerspectiveCamera();
  15411. cameraL.layers.enable(1);
  15412. cameraL.viewport = new Vector4();
  15413. var cameraR = new PerspectiveCamera();
  15414. cameraR.layers.enable(2);
  15415. cameraR.viewport = new Vector4();
  15416. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15417. cameraVR.layers.enable(1);
  15418. cameraVR.layers.enable(2); //
  15419. this.enabled = false;
  15420. this.getController = function (id) {
  15421. var controller = controllers[id];
  15422. if (controller === undefined) {
  15423. controller = new Group();
  15424. controller.matrixAutoUpdate = false;
  15425. controller.visible = false;
  15426. controllers[id] = controller;
  15427. }
  15428. return controller;
  15429. }; //
  15430. function onSessionEvent(event) {
  15431. for (var i = 0; i < controllers.length; i++) {
  15432. if (inputSources[i] === event.inputSource) {
  15433. controllers[i].dispatchEvent({
  15434. type: event.type
  15435. });
  15436. }
  15437. }
  15438. }
  15439. function onSessionEnd() {
  15440. renderer.setFramebuffer(null);
  15441. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  15442. animation.stop();
  15443. scope.dispatchEvent({
  15444. type: 'sessionend'
  15445. });
  15446. }
  15447. function onRequestReferenceSpace(value) {
  15448. referenceSpace = value;
  15449. animation.setContext(session);
  15450. animation.start();
  15451. scope.dispatchEvent({
  15452. type: 'sessionstart'
  15453. });
  15454. }
  15455. this.setFramebufferScaleFactor = function ()
  15456. /* value */
  15457. {// framebufferScaleFactor = value;
  15458. };
  15459. this.setReferenceSpaceType = function (value) {
  15460. referenceSpaceType = value;
  15461. };
  15462. this.getSession = function () {
  15463. return session;
  15464. };
  15465. this.setSession = function (value) {
  15466. session = value;
  15467. if (session !== null) {
  15468. session.addEventListener('select', onSessionEvent);
  15469. session.addEventListener('selectstart', onSessionEvent);
  15470. session.addEventListener('selectend', onSessionEvent);
  15471. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  15472. session.updateRenderState({
  15473. baseLayer: new XRWebGLLayer(session, gl)
  15474. });
  15475. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  15476. inputSources = session.inputSources;
  15477. session.addEventListener('inputsourceschange', function () {
  15478. inputSources = session.inputSources;
  15479. console.log(inputSources);
  15480. for (var i = 0; i < controllers.length; i++) {
  15481. var controller = controllers[i];
  15482. controller.userData.inputSource = inputSources[i];
  15483. }
  15484. });
  15485. }
  15486. };
  15487. function updateCamera(camera, parent) {
  15488. if (parent === null) {
  15489. camera.matrixWorld.copy(camera.matrix);
  15490. } else {
  15491. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15492. }
  15493. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  15494. }
  15495. this.getCamera = function (camera) {
  15496. if (isPresenting()) {
  15497. var parent = camera.parent;
  15498. var cameras = cameraVR.cameras;
  15499. updateCamera(cameraVR, parent);
  15500. for (var i = 0; i < cameras.length; i++) {
  15501. updateCamera(cameras[i], parent);
  15502. } // update camera and its children
  15503. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15504. var children = camera.children;
  15505. for (var i = 0, l = children.length; i < l; i++) {
  15506. children[i].updateMatrixWorld(true);
  15507. }
  15508. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15509. return cameraVR;
  15510. }
  15511. return camera;
  15512. };
  15513. this.isPresenting = isPresenting; // Animation Loop
  15514. var onAnimationFrameCallback = null;
  15515. function onAnimationFrame(time, frame) {
  15516. pose = frame.getViewerPose(referenceSpace);
  15517. if (pose !== null) {
  15518. var views = pose.views;
  15519. var baseLayer = session.renderState.baseLayer;
  15520. renderer.setFramebuffer(baseLayer.framebuffer);
  15521. for (var i = 0; i < views.length; i++) {
  15522. var view = views[i];
  15523. var viewport = baseLayer.getViewport(view);
  15524. var viewMatrix = view.transform.inverse.matrix;
  15525. var camera = cameraVR.cameras[i];
  15526. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  15527. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15528. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15529. if (i === 0) {
  15530. cameraVR.matrix.copy(camera.matrix);
  15531. }
  15532. }
  15533. } //
  15534. for (var i = 0; i < controllers.length; i++) {
  15535. var controller = controllers[i];
  15536. var inputSource = inputSources[i];
  15537. if (inputSource) {
  15538. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15539. if (inputPose !== null) {
  15540. controller.matrix.fromArray(inputPose.transform.matrix);
  15541. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  15542. controller.visible = true;
  15543. continue;
  15544. }
  15545. }
  15546. controller.visible = false;
  15547. }
  15548. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15549. }
  15550. var animation = new WebGLAnimation();
  15551. animation.setAnimationLoop(onAnimationFrame);
  15552. this.setAnimationLoop = function (callback) {
  15553. onAnimationFrameCallback = callback;
  15554. };
  15555. this.dispose = function () {}; // DEPRECATED
  15556. this.getStandingMatrix = function () {
  15557. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  15558. return new Matrix4();
  15559. };
  15560. this.getDevice = function () {
  15561. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  15562. };
  15563. this.setDevice = function () {
  15564. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  15565. };
  15566. this.setFrameOfReferenceType = function () {
  15567. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  15568. };
  15569. this.submitFrame = function () {};
  15570. }
  15571. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  15572. /**
  15573. * @author supereggbert / http://www.paulbrunt.co.uk/
  15574. * @author mrdoob / http://mrdoob.com/
  15575. * @author alteredq / http://alteredqualia.com/
  15576. * @author szimek / https://github.com/szimek/
  15577. * @author tschw
  15578. */
  15579. function WebGLRenderer(parameters) {
  15580. parameters = parameters || {};
  15581. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  15582. _context = parameters.context !== undefined ? parameters.context : null,
  15583. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15584. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15585. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15586. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15587. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15588. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15589. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15590. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15591. var currentRenderList = null;
  15592. var currentRenderState = null; // public properties
  15593. this.domElement = _canvas; // Debug configuration container
  15594. this.debug = {
  15595. /**
  15596. * Enables error checking and reporting when shader programs are being compiled
  15597. * @type {boolean}
  15598. */
  15599. checkShaderErrors: true
  15600. }; // clearing
  15601. this.autoClear = true;
  15602. this.autoClearColor = true;
  15603. this.autoClearDepth = true;
  15604. this.autoClearStencil = true; // scene graph
  15605. this.sortObjects = true; // user-defined clipping
  15606. this.clippingPlanes = [];
  15607. this.localClippingEnabled = false; // physically based shading
  15608. this.gammaFactor = 2.0; // for backwards compatibility
  15609. this.gammaInput = false;
  15610. this.gammaOutput = false; // physical lights
  15611. this.physicallyCorrectLights = false; // tone mapping
  15612. this.toneMapping = LinearToneMapping;
  15613. this.toneMappingExposure = 1.0;
  15614. this.toneMappingWhitePoint = 1.0; // morphs
  15615. this.maxMorphTargets = 8;
  15616. this.maxMorphNormals = 4; // internal properties
  15617. var _this = this,
  15618. _isContextLost = false,
  15619. // internal state cache
  15620. _framebuffer = null,
  15621. _currentActiveCubeFace = 0,
  15622. _currentActiveMipmapLevel = 0,
  15623. _currentRenderTarget = null,
  15624. _currentFramebuffer = null,
  15625. _currentMaterialId = -1,
  15626. // geometry and program caching
  15627. _currentGeometryProgram = {
  15628. geometry: null,
  15629. program: null,
  15630. wireframe: false
  15631. },
  15632. _currentCamera = null,
  15633. _currentArrayCamera = null,
  15634. _currentViewport = new Vector4(),
  15635. _currentScissor = new Vector4(),
  15636. _currentScissorTest = null,
  15637. //
  15638. _width = _canvas.width,
  15639. _height = _canvas.height,
  15640. _pixelRatio = 1,
  15641. _viewport = new Vector4(0, 0, _width, _height),
  15642. _scissor = new Vector4(0, 0, _width, _height),
  15643. _scissorTest = false,
  15644. // frustum
  15645. _frustum = new Frustum(),
  15646. // clipping
  15647. _clipping = new WebGLClipping(),
  15648. _clippingEnabled = false,
  15649. _localClippingEnabled = false,
  15650. // camera matrices cache
  15651. _projScreenMatrix = new Matrix4(),
  15652. _vector3 = new Vector3();
  15653. function getTargetPixelRatio() {
  15654. return _currentRenderTarget === null ? _pixelRatio : 1;
  15655. } // initialize
  15656. var _gl;
  15657. try {
  15658. var contextAttributes = {
  15659. alpha: _alpha,
  15660. depth: _depth,
  15661. stencil: _stencil,
  15662. antialias: _antialias,
  15663. premultipliedAlpha: _premultipliedAlpha,
  15664. preserveDrawingBuffer: _preserveDrawingBuffer,
  15665. powerPreference: _powerPreference,
  15666. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  15667. xrCompatible: true
  15668. }; // event listeners must be registered before WebGL context is created, see #12753
  15669. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15670. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15671. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  15672. if (_gl === null) {
  15673. if (_canvas.getContext('webgl') !== null) {
  15674. throw new Error('Error creating WebGL context with your selected attributes.');
  15675. } else {
  15676. throw new Error('Error creating WebGL context.');
  15677. }
  15678. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15679. if (_gl.getShaderPrecisionFormat === undefined) {
  15680. _gl.getShaderPrecisionFormat = function () {
  15681. return {
  15682. 'rangeMin': 1,
  15683. 'rangeMax': 1,
  15684. 'precision': 1
  15685. };
  15686. };
  15687. }
  15688. } catch (error) {
  15689. console.error('THREE.WebGLRenderer: ' + error.message);
  15690. throw error;
  15691. }
  15692. var extensions, capabilities, state, info;
  15693. var properties, textures, attributes, geometries, objects;
  15694. var programCache, renderLists, renderStates;
  15695. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15696. var utils;
  15697. function initGLContext() {
  15698. extensions = new WebGLExtensions(_gl);
  15699. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15700. if (capabilities.isWebGL2 === false) {
  15701. extensions.get('WEBGL_depth_texture');
  15702. extensions.get('OES_texture_float');
  15703. extensions.get('OES_texture_half_float');
  15704. extensions.get('OES_texture_half_float_linear');
  15705. extensions.get('OES_standard_derivatives');
  15706. extensions.get('OES_element_index_uint');
  15707. extensions.get('ANGLE_instanced_arrays');
  15708. }
  15709. extensions.get('OES_texture_float_linear');
  15710. utils = new WebGLUtils(_gl, extensions, capabilities);
  15711. state = new WebGLState(_gl, extensions, utils, capabilities);
  15712. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15713. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15714. info = new WebGLInfo(_gl);
  15715. properties = new WebGLProperties();
  15716. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15717. attributes = new WebGLAttributes(_gl);
  15718. geometries = new WebGLGeometries(_gl, attributes, info);
  15719. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15720. morphtargets = new WebGLMorphtargets(_gl);
  15721. programCache = new WebGLPrograms(_this, extensions, capabilities);
  15722. renderLists = new WebGLRenderLists();
  15723. renderStates = new WebGLRenderStates();
  15724. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  15725. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15726. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15727. info.programs = programCache.programs;
  15728. _this.capabilities = capabilities;
  15729. _this.extensions = extensions;
  15730. _this.properties = properties;
  15731. _this.renderLists = renderLists;
  15732. _this.state = state;
  15733. _this.info = info;
  15734. }
  15735. initGLContext(); // vr
  15736. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  15737. this.vr = vr; // Multiview
  15738. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  15739. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  15740. this.shadowMap = shadowMap; // API
  15741. this.getContext = function () {
  15742. return _gl;
  15743. };
  15744. this.getContextAttributes = function () {
  15745. return _gl.getContextAttributes();
  15746. };
  15747. this.forceContextLoss = function () {
  15748. var extension = extensions.get('WEBGL_lose_context');
  15749. if (extension) extension.loseContext();
  15750. };
  15751. this.forceContextRestore = function () {
  15752. var extension = extensions.get('WEBGL_lose_context');
  15753. if (extension) extension.restoreContext();
  15754. };
  15755. this.getPixelRatio = function () {
  15756. return _pixelRatio;
  15757. };
  15758. this.setPixelRatio = function (value) {
  15759. if (value === undefined) return;
  15760. _pixelRatio = value;
  15761. this.setSize(_width, _height, false);
  15762. };
  15763. this.getSize = function (target) {
  15764. if (target === undefined) {
  15765. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  15766. target = new Vector2();
  15767. }
  15768. return target.set(_width, _height);
  15769. };
  15770. this.setSize = function (width, height, updateStyle) {
  15771. if (vr.isPresenting()) {
  15772. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15773. return;
  15774. }
  15775. _width = width;
  15776. _height = height;
  15777. _canvas.width = Math.floor(width * _pixelRatio);
  15778. _canvas.height = Math.floor(height * _pixelRatio);
  15779. if (updateStyle !== false) {
  15780. _canvas.style.width = width + 'px';
  15781. _canvas.style.height = height + 'px';
  15782. }
  15783. this.setViewport(0, 0, width, height);
  15784. };
  15785. this.getDrawingBufferSize = function (target) {
  15786. if (target === undefined) {
  15787. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  15788. target = new Vector2();
  15789. }
  15790. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15791. };
  15792. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15793. _width = width;
  15794. _height = height;
  15795. _pixelRatio = pixelRatio;
  15796. _canvas.width = Math.floor(width * pixelRatio);
  15797. _canvas.height = Math.floor(height * pixelRatio);
  15798. this.setViewport(0, 0, width, height);
  15799. };
  15800. this.getCurrentViewport = function (target) {
  15801. if (target === undefined) {
  15802. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  15803. target = new Vector4();
  15804. }
  15805. return target.copy(_currentViewport);
  15806. };
  15807. this.getViewport = function (target) {
  15808. return target.copy(_viewport);
  15809. };
  15810. this.setViewport = function (x, y, width, height) {
  15811. if (x.isVector4) {
  15812. _viewport.set(x.x, x.y, x.z, x.w);
  15813. } else {
  15814. _viewport.set(x, y, width, height);
  15815. }
  15816. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15817. };
  15818. this.getScissor = function (target) {
  15819. return target.copy(_scissor);
  15820. };
  15821. this.setScissor = function (x, y, width, height) {
  15822. if (x.isVector4) {
  15823. _scissor.set(x.x, x.y, x.z, x.w);
  15824. } else {
  15825. _scissor.set(x, y, width, height);
  15826. }
  15827. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15828. };
  15829. this.getScissorTest = function () {
  15830. return _scissorTest;
  15831. };
  15832. this.setScissorTest = function (boolean) {
  15833. state.setScissorTest(_scissorTest = boolean);
  15834. }; // Clearing
  15835. this.getClearColor = function () {
  15836. return background.getClearColor();
  15837. };
  15838. this.setClearColor = function () {
  15839. background.setClearColor.apply(background, arguments);
  15840. };
  15841. this.getClearAlpha = function () {
  15842. return background.getClearAlpha();
  15843. };
  15844. this.setClearAlpha = function () {
  15845. background.setClearAlpha.apply(background, arguments);
  15846. };
  15847. this.clear = function (color, depth, stencil) {
  15848. var bits = 0;
  15849. if (color === undefined || color) bits |= 16384;
  15850. if (depth === undefined || depth) bits |= 256;
  15851. if (stencil === undefined || stencil) bits |= 1024;
  15852. _gl.clear(bits);
  15853. };
  15854. this.clearColor = function () {
  15855. this.clear(true, false, false);
  15856. };
  15857. this.clearDepth = function () {
  15858. this.clear(false, true, false);
  15859. };
  15860. this.clearStencil = function () {
  15861. this.clear(false, false, true);
  15862. }; //
  15863. this.dispose = function () {
  15864. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15865. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15866. renderLists.dispose();
  15867. renderStates.dispose();
  15868. properties.dispose();
  15869. objects.dispose();
  15870. vr.dispose();
  15871. animation.stop();
  15872. }; // Events
  15873. function onContextLost(event) {
  15874. event.preventDefault();
  15875. console.log('THREE.WebGLRenderer: Context Lost.');
  15876. _isContextLost = true;
  15877. }
  15878. function onContextRestore()
  15879. /* event */
  15880. {
  15881. console.log('THREE.WebGLRenderer: Context Restored.');
  15882. _isContextLost = false;
  15883. initGLContext();
  15884. }
  15885. function onMaterialDispose(event) {
  15886. var material = event.target;
  15887. material.removeEventListener('dispose', onMaterialDispose);
  15888. deallocateMaterial(material);
  15889. } // Buffer deallocation
  15890. function deallocateMaterial(material) {
  15891. releaseMaterialProgramReference(material);
  15892. properties.remove(material);
  15893. }
  15894. function releaseMaterialProgramReference(material) {
  15895. var programInfo = properties.get(material).program;
  15896. material.program = undefined;
  15897. if (programInfo !== undefined) {
  15898. programCache.releaseProgram(programInfo);
  15899. }
  15900. } // Buffer rendering
  15901. function renderObjectImmediate(object, program) {
  15902. object.render(function (object) {
  15903. _this.renderBufferImmediate(object, program);
  15904. });
  15905. }
  15906. this.renderBufferImmediate = function (object, program) {
  15907. state.initAttributes();
  15908. var buffers = properties.get(object);
  15909. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15910. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15911. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15912. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15913. var programAttributes = program.getAttributes();
  15914. if (object.hasPositions) {
  15915. _gl.bindBuffer(34962, buffers.position);
  15916. _gl.bufferData(34962, object.positionArray, 35048);
  15917. state.enableAttribute(programAttributes.position);
  15918. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  15919. }
  15920. if (object.hasNormals) {
  15921. _gl.bindBuffer(34962, buffers.normal);
  15922. _gl.bufferData(34962, object.normalArray, 35048);
  15923. state.enableAttribute(programAttributes.normal);
  15924. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  15925. }
  15926. if (object.hasUvs) {
  15927. _gl.bindBuffer(34962, buffers.uv);
  15928. _gl.bufferData(34962, object.uvArray, 35048);
  15929. state.enableAttribute(programAttributes.uv);
  15930. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  15931. }
  15932. if (object.hasColors) {
  15933. _gl.bindBuffer(34962, buffers.color);
  15934. _gl.bufferData(34962, object.colorArray, 35048);
  15935. state.enableAttribute(programAttributes.color);
  15936. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  15937. }
  15938. state.disableUnusedAttributes();
  15939. _gl.drawArrays(4, 0, object.count);
  15940. object.count = 0;
  15941. };
  15942. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  15943. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15944. state.setMaterial(material, frontFaceCW);
  15945. var program = setProgram(camera, fog, material, object);
  15946. var updateBuffers = false;
  15947. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  15948. _currentGeometryProgram.geometry = geometry.id;
  15949. _currentGeometryProgram.program = program.id;
  15950. _currentGeometryProgram.wireframe = material.wireframe === true;
  15951. updateBuffers = true;
  15952. }
  15953. if (object.morphTargetInfluences) {
  15954. morphtargets.update(object, geometry, material, program);
  15955. updateBuffers = true;
  15956. } //
  15957. var index = geometry.index;
  15958. var position = geometry.attributes.position;
  15959. var rangeFactor = 1;
  15960. if (material.wireframe === true) {
  15961. index = geometries.getWireframeAttribute(geometry);
  15962. rangeFactor = 2;
  15963. }
  15964. var attribute;
  15965. var renderer = bufferRenderer;
  15966. if (index !== null) {
  15967. attribute = attributes.get(index);
  15968. renderer = indexedBufferRenderer;
  15969. renderer.setIndex(attribute);
  15970. }
  15971. if (updateBuffers) {
  15972. setupVertexAttributes(object, geometry, material, program);
  15973. if (index !== null) {
  15974. _gl.bindBuffer(34963, attribute.buffer);
  15975. }
  15976. } //
  15977. var dataCount = Infinity;
  15978. if (index !== null) {
  15979. dataCount = index.count;
  15980. } else if (position !== undefined) {
  15981. dataCount = position.count;
  15982. }
  15983. var rangeStart = geometry.drawRange.start * rangeFactor;
  15984. var rangeCount = geometry.drawRange.count * rangeFactor;
  15985. var groupStart = group !== null ? group.start * rangeFactor : 0;
  15986. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15987. var drawStart = Math.max(rangeStart, groupStart);
  15988. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15989. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  15990. if (drawCount === 0) return; //
  15991. if (object.isMesh) {
  15992. if (material.wireframe === true) {
  15993. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15994. renderer.setMode(1);
  15995. } else {
  15996. switch (object.drawMode) {
  15997. case TrianglesDrawMode:
  15998. renderer.setMode(4);
  15999. break;
  16000. case TriangleStripDrawMode:
  16001. renderer.setMode(5);
  16002. break;
  16003. case TriangleFanDrawMode:
  16004. renderer.setMode(6);
  16005. break;
  16006. }
  16007. }
  16008. } else if (object.isLine) {
  16009. var lineWidth = material.linewidth;
  16010. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16011. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16012. if (object.isLineSegments) {
  16013. renderer.setMode(1);
  16014. } else if (object.isLineLoop) {
  16015. renderer.setMode(2);
  16016. } else {
  16017. renderer.setMode(3);
  16018. }
  16019. } else if (object.isPoints) {
  16020. renderer.setMode(0);
  16021. } else if (object.isSprite) {
  16022. renderer.setMode(4);
  16023. }
  16024. if (object.isInstancedMesh) {
  16025. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  16026. } else if (geometry.isInstancedBufferGeometry) {
  16027. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  16028. } else {
  16029. renderer.render(drawStart, drawCount);
  16030. }
  16031. };
  16032. function setupVertexAttributes(object, geometry, material, program) {
  16033. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  16034. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  16035. }
  16036. state.initAttributes();
  16037. var geometryAttributes = geometry.attributes;
  16038. var programAttributes = program.getAttributes();
  16039. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16040. for (var name in programAttributes) {
  16041. var programAttribute = programAttributes[name];
  16042. if (programAttribute >= 0) {
  16043. var geometryAttribute = geometryAttributes[name];
  16044. if (geometryAttribute !== undefined) {
  16045. var normalized = geometryAttribute.normalized;
  16046. var size = geometryAttribute.itemSize;
  16047. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  16048. if (attribute === undefined) continue;
  16049. var buffer = attribute.buffer;
  16050. var type = attribute.type;
  16051. var bytesPerElement = attribute.bytesPerElement;
  16052. if (geometryAttribute.isInterleavedBufferAttribute) {
  16053. var data = geometryAttribute.data;
  16054. var stride = data.stride;
  16055. var offset = geometryAttribute.offset;
  16056. if (data && data.isInstancedInterleavedBuffer) {
  16057. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  16058. if (geometry.maxInstancedCount === undefined) {
  16059. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16060. }
  16061. } else {
  16062. state.enableAttribute(programAttribute);
  16063. }
  16064. _gl.bindBuffer(34962, buffer);
  16065. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  16066. } else {
  16067. if (geometryAttribute.isInstancedBufferAttribute) {
  16068. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  16069. if (geometry.maxInstancedCount === undefined) {
  16070. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16071. }
  16072. } else {
  16073. state.enableAttribute(programAttribute);
  16074. }
  16075. _gl.bindBuffer(34962, buffer);
  16076. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  16077. }
  16078. } else if (name === 'instanceMatrix') {
  16079. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  16080. if (attribute === undefined) continue;
  16081. var buffer = attribute.buffer;
  16082. var type = attribute.type;
  16083. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  16084. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  16085. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  16086. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  16087. _gl.bindBuffer(34962, buffer);
  16088. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  16089. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  16090. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  16091. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  16092. } else if (materialDefaultAttributeValues !== undefined) {
  16093. var value = materialDefaultAttributeValues[name];
  16094. if (value !== undefined) {
  16095. switch (value.length) {
  16096. case 2:
  16097. _gl.vertexAttrib2fv(programAttribute, value);
  16098. break;
  16099. case 3:
  16100. _gl.vertexAttrib3fv(programAttribute, value);
  16101. break;
  16102. case 4:
  16103. _gl.vertexAttrib4fv(programAttribute, value);
  16104. break;
  16105. default:
  16106. _gl.vertexAttrib1fv(programAttribute, value);
  16107. }
  16108. }
  16109. }
  16110. }
  16111. }
  16112. state.disableUnusedAttributes();
  16113. } // Compile
  16114. this.compile = function (scene, camera) {
  16115. currentRenderState = renderStates.get(scene, camera);
  16116. currentRenderState.init();
  16117. scene.traverse(function (object) {
  16118. if (object.isLight) {
  16119. currentRenderState.pushLight(object);
  16120. if (object.castShadow) {
  16121. currentRenderState.pushShadow(object);
  16122. }
  16123. }
  16124. });
  16125. currentRenderState.setupLights(camera);
  16126. scene.traverse(function (object) {
  16127. if (object.material) {
  16128. if (Array.isArray(object.material)) {
  16129. for (var i = 0; i < object.material.length; i++) {
  16130. initMaterial(object.material[i], scene.fog, object);
  16131. }
  16132. } else {
  16133. initMaterial(object.material, scene.fog, object);
  16134. }
  16135. }
  16136. });
  16137. }; // Animation Loop
  16138. var onAnimationFrameCallback = null;
  16139. function onAnimationFrame(time) {
  16140. if (vr.isPresenting()) return;
  16141. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16142. }
  16143. var animation = new WebGLAnimation();
  16144. animation.setAnimationLoop(onAnimationFrame);
  16145. if (typeof window !== 'undefined') animation.setContext(window);
  16146. this.setAnimationLoop = function (callback) {
  16147. onAnimationFrameCallback = callback;
  16148. vr.setAnimationLoop(callback);
  16149. animation.start();
  16150. }; // Rendering
  16151. this.render = function (scene, camera) {
  16152. var renderTarget, forceClear;
  16153. if (arguments[2] !== undefined) {
  16154. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  16155. renderTarget = arguments[2];
  16156. }
  16157. if (arguments[3] !== undefined) {
  16158. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  16159. forceClear = arguments[3];
  16160. }
  16161. if (!(camera && camera.isCamera)) {
  16162. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16163. return;
  16164. }
  16165. if (_isContextLost) return; // reset caching for this frame
  16166. _currentGeometryProgram.geometry = null;
  16167. _currentGeometryProgram.program = null;
  16168. _currentGeometryProgram.wireframe = false;
  16169. _currentMaterialId = -1;
  16170. _currentCamera = null; // update scene graph
  16171. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16172. if (camera.parent === null) camera.updateMatrixWorld();
  16173. if (vr.enabled) {
  16174. camera = vr.getCamera(camera);
  16175. } //
  16176. currentRenderState = renderStates.get(scene, camera);
  16177. currentRenderState.init();
  16178. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  16179. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16180. _frustum.setFromMatrix(_projScreenMatrix);
  16181. _localClippingEnabled = this.localClippingEnabled;
  16182. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16183. currentRenderList = renderLists.get(scene, camera);
  16184. currentRenderList.init();
  16185. projectObject(scene, camera, 0, _this.sortObjects);
  16186. if (_this.sortObjects === true) {
  16187. currentRenderList.sort();
  16188. } //
  16189. if (_clippingEnabled) _clipping.beginShadows();
  16190. var shadowsArray = currentRenderState.state.shadowsArray;
  16191. shadowMap.render(shadowsArray, scene, camera);
  16192. currentRenderState.setupLights(camera);
  16193. if (_clippingEnabled) _clipping.endShadows(); //
  16194. if (this.info.autoReset) this.info.reset();
  16195. if (renderTarget !== undefined) {
  16196. this.setRenderTarget(renderTarget);
  16197. }
  16198. if (vr.enabled && multiview.isAvailable()) {
  16199. multiview.attachCamera(camera);
  16200. } //
  16201. background.render(currentRenderList, scene, camera, forceClear); // render scene
  16202. var opaqueObjects = currentRenderList.opaque;
  16203. var transparentObjects = currentRenderList.transparent;
  16204. if (scene.overrideMaterial) {
  16205. var overrideMaterial = scene.overrideMaterial;
  16206. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  16207. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  16208. } else {
  16209. // opaque pass (front-to-back order)
  16210. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  16211. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  16212. } //
  16213. scene.onAfterRender(_this, scene, camera); //
  16214. if (_currentRenderTarget !== null) {
  16215. // Generate mipmap if we're using any kind of mipmap filtering
  16216. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  16217. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16218. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  16219. state.buffers.depth.setTest(true);
  16220. state.buffers.depth.setMask(true);
  16221. state.buffers.color.setMask(true);
  16222. state.setPolygonOffset(false);
  16223. if (vr.enabled) {
  16224. if (multiview.isAvailable()) {
  16225. multiview.detachCamera(camera);
  16226. }
  16227. vr.submitFrame();
  16228. } // _gl.finish();
  16229. currentRenderList = null;
  16230. currentRenderState = null;
  16231. };
  16232. function projectObject(object, camera, groupOrder, sortObjects) {
  16233. if (object.visible === false) return;
  16234. var visible = object.layers.test(camera.layers);
  16235. if (visible) {
  16236. if (object.isGroup) {
  16237. groupOrder = object.renderOrder;
  16238. } else if (object.isLOD) {
  16239. if (object.autoUpdate === true) object.update(camera);
  16240. } else if (object.isLight) {
  16241. currentRenderState.pushLight(object);
  16242. if (object.castShadow) {
  16243. currentRenderState.pushShadow(object);
  16244. }
  16245. } else if (object.isSprite) {
  16246. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16247. if (sortObjects) {
  16248. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16249. }
  16250. var geometry = objects.update(object);
  16251. var material = object.material;
  16252. if (material.visible) {
  16253. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16254. }
  16255. }
  16256. } else if (object.isImmediateRenderObject) {
  16257. if (sortObjects) {
  16258. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16259. }
  16260. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  16261. } else if (object.isMesh || object.isLine || object.isPoints) {
  16262. if (object.isSkinnedMesh) {
  16263. // update skeleton only once in a frame
  16264. if (object.skeleton.frame !== info.render.frame) {
  16265. object.skeleton.update();
  16266. object.skeleton.frame = info.render.frame;
  16267. }
  16268. }
  16269. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16270. if (sortObjects) {
  16271. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16272. }
  16273. var geometry = objects.update(object);
  16274. var material = object.material;
  16275. if (Array.isArray(material)) {
  16276. var groups = geometry.groups;
  16277. for (var i = 0, l = groups.length; i < l; i++) {
  16278. var group = groups[i];
  16279. var groupMaterial = material[group.materialIndex];
  16280. if (groupMaterial && groupMaterial.visible) {
  16281. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16282. }
  16283. }
  16284. } else if (material.visible) {
  16285. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16286. }
  16287. }
  16288. }
  16289. }
  16290. var children = object.children;
  16291. for (var i = 0, l = children.length; i < l; i++) {
  16292. projectObject(children[i], camera, groupOrder, sortObjects);
  16293. }
  16294. }
  16295. function renderObjects(renderList, scene, camera, overrideMaterial) {
  16296. for (var i = 0, l = renderList.length; i < l; i++) {
  16297. var renderItem = renderList[i];
  16298. var object = renderItem.object;
  16299. var geometry = renderItem.geometry;
  16300. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16301. var group = renderItem.group;
  16302. if (camera.isArrayCamera) {
  16303. _currentArrayCamera = camera;
  16304. if (vr.enabled && multiview.isAvailable()) {
  16305. renderObject(object, scene, camera, geometry, material, group);
  16306. } else {
  16307. var cameras = camera.cameras;
  16308. for (var j = 0, jl = cameras.length; j < jl; j++) {
  16309. var camera2 = cameras[j];
  16310. if (object.layers.test(camera2.layers)) {
  16311. state.viewport(_currentViewport.copy(camera2.viewport));
  16312. currentRenderState.setupLights(camera2);
  16313. renderObject(object, scene, camera2, geometry, material, group);
  16314. }
  16315. }
  16316. }
  16317. } else {
  16318. _currentArrayCamera = null;
  16319. renderObject(object, scene, camera, geometry, material, group);
  16320. }
  16321. }
  16322. }
  16323. function renderObject(object, scene, camera, geometry, material, group) {
  16324. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16325. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16326. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16327. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16328. if (object.isImmediateRenderObject) {
  16329. state.setMaterial(material);
  16330. var program = setProgram(camera, scene.fog, material, object);
  16331. _currentGeometryProgram.geometry = null;
  16332. _currentGeometryProgram.program = null;
  16333. _currentGeometryProgram.wireframe = false;
  16334. renderObjectImmediate(object, program);
  16335. } else {
  16336. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  16337. }
  16338. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16339. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16340. }
  16341. function initMaterial(material, fog, object) {
  16342. var materialProperties = properties.get(material);
  16343. var lights = currentRenderState.state.lights;
  16344. var shadowsArray = currentRenderState.state.shadowsArray;
  16345. var lightsStateVersion = lights.state.version;
  16346. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  16347. var code = programCache.getProgramCode(material, parameters);
  16348. var program = materialProperties.program;
  16349. var programChange = true;
  16350. if (program === undefined) {
  16351. // new material
  16352. material.addEventListener('dispose', onMaterialDispose);
  16353. } else if (program.code !== code) {
  16354. // changed glsl or parameters
  16355. releaseMaterialProgramReference(material);
  16356. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  16357. materialProperties.lightsStateVersion = lightsStateVersion;
  16358. programChange = false;
  16359. } else if (parameters.shaderID !== undefined) {
  16360. // same glsl and uniform list
  16361. return;
  16362. } else {
  16363. // only rebuild uniform list
  16364. programChange = false;
  16365. }
  16366. if (programChange) {
  16367. if (parameters.shaderID) {
  16368. var shader = ShaderLib[parameters.shaderID];
  16369. materialProperties.shader = {
  16370. name: material.type,
  16371. uniforms: cloneUniforms(shader.uniforms),
  16372. vertexShader: shader.vertexShader,
  16373. fragmentShader: shader.fragmentShader
  16374. };
  16375. } else {
  16376. materialProperties.shader = {
  16377. name: material.type,
  16378. uniforms: material.uniforms,
  16379. vertexShader: material.vertexShader,
  16380. fragmentShader: material.fragmentShader
  16381. };
  16382. }
  16383. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  16384. code = programCache.getProgramCode(material, parameters);
  16385. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  16386. materialProperties.program = program;
  16387. material.program = program;
  16388. }
  16389. var programAttributes = program.getAttributes();
  16390. if (material.morphTargets) {
  16391. material.numSupportedMorphTargets = 0;
  16392. for (var i = 0; i < _this.maxMorphTargets; i++) {
  16393. if (programAttributes['morphTarget' + i] >= 0) {
  16394. material.numSupportedMorphTargets++;
  16395. }
  16396. }
  16397. }
  16398. if (material.morphNormals) {
  16399. material.numSupportedMorphNormals = 0;
  16400. for (var i = 0; i < _this.maxMorphNormals; i++) {
  16401. if (programAttributes['morphNormal' + i] >= 0) {
  16402. material.numSupportedMorphNormals++;
  16403. }
  16404. }
  16405. }
  16406. var uniforms = materialProperties.shader.uniforms;
  16407. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16408. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16409. materialProperties.numIntersection = _clipping.numIntersection;
  16410. uniforms.clippingPlanes = _clipping.uniform;
  16411. }
  16412. materialProperties.fog = fog; // store the light setup it was created for
  16413. materialProperties.needsLights = materialNeedsLights(material);
  16414. materialProperties.lightsStateVersion = lightsStateVersion;
  16415. if (materialProperties.needsLights) {
  16416. // wire up the material to this renderer's lighting state
  16417. uniforms.ambientLightColor.value = lights.state.ambient;
  16418. uniforms.lightProbe.value = lights.state.probe;
  16419. uniforms.directionalLights.value = lights.state.directional;
  16420. uniforms.spotLights.value = lights.state.spot;
  16421. uniforms.rectAreaLights.value = lights.state.rectArea;
  16422. uniforms.pointLights.value = lights.state.point;
  16423. uniforms.hemisphereLights.value = lights.state.hemi;
  16424. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16425. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16426. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16427. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16428. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16429. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16430. }
  16431. var progUniforms = materialProperties.program.getUniforms(),
  16432. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16433. materialProperties.uniformsList = uniformsList;
  16434. }
  16435. function setProgram(camera, fog, material, object) {
  16436. textures.resetTextureUnits();
  16437. var materialProperties = properties.get(material);
  16438. var lights = currentRenderState.state.lights;
  16439. if (_clippingEnabled) {
  16440. if (_localClippingEnabled || camera !== _currentCamera) {
  16441. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16442. // object instead of the material, once it becomes feasible
  16443. // (#8465, #8379)
  16444. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  16445. }
  16446. }
  16447. if (material.needsUpdate === false) {
  16448. if (materialProperties.program === undefined) {
  16449. material.needsUpdate = true;
  16450. } else if (material.fog && materialProperties.fog !== fog) {
  16451. material.needsUpdate = true;
  16452. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16453. material.needsUpdate = true;
  16454. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  16455. material.needsUpdate = true;
  16456. }
  16457. }
  16458. if (material.needsUpdate) {
  16459. initMaterial(material, fog, object);
  16460. material.needsUpdate = false;
  16461. }
  16462. var refreshProgram = false;
  16463. var refreshMaterial = false;
  16464. var refreshLights = false;
  16465. var program = materialProperties.program,
  16466. p_uniforms = program.getUniforms(),
  16467. m_uniforms = materialProperties.shader.uniforms;
  16468. if (state.useProgram(program.program)) {
  16469. refreshProgram = true;
  16470. refreshMaterial = true;
  16471. refreshLights = true;
  16472. }
  16473. if (material.id !== _currentMaterialId) {
  16474. _currentMaterialId = material.id;
  16475. refreshMaterial = true;
  16476. }
  16477. if (refreshProgram || _currentCamera !== camera) {
  16478. if (program.numMultiviewViews > 0) {
  16479. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  16480. } else {
  16481. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16482. }
  16483. if (capabilities.logarithmicDepthBuffer) {
  16484. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16485. }
  16486. if (_currentCamera !== camera) {
  16487. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16488. // now, in case this material supports lights - or later, when
  16489. // the next material that does gets activated:
  16490. refreshMaterial = true; // set to true on material change
  16491. refreshLights = true; // remains set until update done
  16492. } // load material specific uniforms
  16493. // (shader material also gets them for the sake of genericity)
  16494. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  16495. var uCamPos = p_uniforms.map.cameraPosition;
  16496. if (uCamPos !== undefined) {
  16497. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16498. }
  16499. }
  16500. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  16501. if (program.numMultiviewViews > 0) {
  16502. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  16503. } else {
  16504. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16505. }
  16506. }
  16507. } // skinning uniforms must be set even if material didn't change
  16508. // auto-setting of texture unit for bone texture must go before other textures
  16509. // not sure why, but otherwise weird things happen
  16510. if (material.skinning) {
  16511. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16512. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16513. var skeleton = object.skeleton;
  16514. if (skeleton) {
  16515. var bones = skeleton.bones;
  16516. if (capabilities.floatVertexTextures) {
  16517. if (skeleton.boneTexture === undefined) {
  16518. // layout (1 matrix = 4 pixels)
  16519. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16520. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16521. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16522. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16523. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16524. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  16525. size = _Math.ceilPowerOfTwo(size);
  16526. size = Math.max(size, 4);
  16527. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16528. boneMatrices.set(skeleton.boneMatrices); // copy current values
  16529. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16530. skeleton.boneMatrices = boneMatrices;
  16531. skeleton.boneTexture = boneTexture;
  16532. skeleton.boneTextureSize = size;
  16533. }
  16534. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16535. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16536. } else {
  16537. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16538. }
  16539. }
  16540. }
  16541. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16542. materialProperties.receiveShadow = object.receiveShadow;
  16543. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16544. }
  16545. if (refreshMaterial) {
  16546. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16547. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  16548. if (materialProperties.needsLights) {
  16549. // the current material requires lighting info
  16550. // note: all lighting uniforms are always set correctly
  16551. // they simply reference the renderer's state for their
  16552. // values
  16553. //
  16554. // use the current material's .needsUpdate flags to set
  16555. // the GL state when required
  16556. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16557. } // refresh uniforms common to several materials
  16558. if (fog && material.fog) {
  16559. refreshUniformsFog(m_uniforms, fog);
  16560. }
  16561. if (material.isMeshBasicMaterial) {
  16562. refreshUniformsCommon(m_uniforms, material);
  16563. } else if (material.isMeshLambertMaterial) {
  16564. refreshUniformsCommon(m_uniforms, material);
  16565. refreshUniformsLambert(m_uniforms, material);
  16566. } else if (material.isMeshPhongMaterial) {
  16567. refreshUniformsCommon(m_uniforms, material);
  16568. if (material.isMeshToonMaterial) {
  16569. refreshUniformsToon(m_uniforms, material);
  16570. } else {
  16571. refreshUniformsPhong(m_uniforms, material);
  16572. }
  16573. } else if (material.isMeshStandardMaterial) {
  16574. refreshUniformsCommon(m_uniforms, material);
  16575. if (material.isMeshPhysicalMaterial) {
  16576. refreshUniformsPhysical(m_uniforms, material);
  16577. } else {
  16578. refreshUniformsStandard(m_uniforms, material);
  16579. }
  16580. } else if (material.isMeshMatcapMaterial) {
  16581. refreshUniformsCommon(m_uniforms, material);
  16582. refreshUniformsMatcap(m_uniforms, material);
  16583. } else if (material.isMeshDepthMaterial) {
  16584. refreshUniformsCommon(m_uniforms, material);
  16585. refreshUniformsDepth(m_uniforms, material);
  16586. } else if (material.isMeshDistanceMaterial) {
  16587. refreshUniformsCommon(m_uniforms, material);
  16588. refreshUniformsDistance(m_uniforms, material);
  16589. } else if (material.isMeshNormalMaterial) {
  16590. refreshUniformsCommon(m_uniforms, material);
  16591. refreshUniformsNormal(m_uniforms, material);
  16592. } else if (material.isLineBasicMaterial) {
  16593. refreshUniformsLine(m_uniforms, material);
  16594. if (material.isLineDashedMaterial) {
  16595. refreshUniformsDash(m_uniforms, material);
  16596. }
  16597. } else if (material.isPointsMaterial) {
  16598. refreshUniformsPoints(m_uniforms, material);
  16599. } else if (material.isSpriteMaterial) {
  16600. refreshUniformsSprites(m_uniforms, material);
  16601. } else if (material.isShadowMaterial) {
  16602. m_uniforms.color.value.copy(material.color);
  16603. m_uniforms.opacity.value = material.opacity;
  16604. } // RectAreaLight Texture
  16605. // TODO (mrdoob): Find a nicer implementation
  16606. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  16607. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  16608. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16609. }
  16610. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16611. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16612. material.uniformsNeedUpdate = false;
  16613. }
  16614. if (material.isSpriteMaterial) {
  16615. p_uniforms.setValue(_gl, 'center', object.center);
  16616. } // common matrices
  16617. if (program.numMultiviewViews > 0) {
  16618. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  16619. } else {
  16620. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16621. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16622. }
  16623. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16624. return program;
  16625. } // Uniforms (refresh uniforms objects)
  16626. function refreshUniformsCommon(uniforms, material) {
  16627. uniforms.opacity.value = material.opacity;
  16628. if (material.color) {
  16629. uniforms.diffuse.value.copy(material.color);
  16630. }
  16631. if (material.emissive) {
  16632. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  16633. }
  16634. if (material.map) {
  16635. uniforms.map.value = material.map;
  16636. }
  16637. if (material.alphaMap) {
  16638. uniforms.alphaMap.value = material.alphaMap;
  16639. }
  16640. if (material.specularMap) {
  16641. uniforms.specularMap.value = material.specularMap;
  16642. }
  16643. if (material.envMap) {
  16644. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  16645. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16646. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16647. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16648. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  16649. uniforms.reflectivity.value = material.reflectivity;
  16650. uniforms.refractionRatio.value = material.refractionRatio;
  16651. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  16652. }
  16653. if (material.lightMap) {
  16654. uniforms.lightMap.value = material.lightMap;
  16655. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16656. }
  16657. if (material.aoMap) {
  16658. uniforms.aoMap.value = material.aoMap;
  16659. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16660. } // uv repeat and offset setting priorities
  16661. // 1. color map
  16662. // 2. specular map
  16663. // 3. normal map
  16664. // 4. bump map
  16665. // 5. alpha map
  16666. // 6. emissive map
  16667. var uvScaleMap;
  16668. if (material.map) {
  16669. uvScaleMap = material.map;
  16670. } else if (material.specularMap) {
  16671. uvScaleMap = material.specularMap;
  16672. } else if (material.displacementMap) {
  16673. uvScaleMap = material.displacementMap;
  16674. } else if (material.normalMap) {
  16675. uvScaleMap = material.normalMap;
  16676. } else if (material.bumpMap) {
  16677. uvScaleMap = material.bumpMap;
  16678. } else if (material.roughnessMap) {
  16679. uvScaleMap = material.roughnessMap;
  16680. } else if (material.metalnessMap) {
  16681. uvScaleMap = material.metalnessMap;
  16682. } else if (material.alphaMap) {
  16683. uvScaleMap = material.alphaMap;
  16684. } else if (material.emissiveMap) {
  16685. uvScaleMap = material.emissiveMap;
  16686. }
  16687. if (uvScaleMap !== undefined) {
  16688. // backwards compatibility
  16689. if (uvScaleMap.isWebGLRenderTarget) {
  16690. uvScaleMap = uvScaleMap.texture;
  16691. }
  16692. if (uvScaleMap.matrixAutoUpdate === true) {
  16693. uvScaleMap.updateMatrix();
  16694. }
  16695. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16696. }
  16697. }
  16698. function refreshUniformsLine(uniforms, material) {
  16699. uniforms.diffuse.value.copy(material.color);
  16700. uniforms.opacity.value = material.opacity;
  16701. }
  16702. function refreshUniformsDash(uniforms, material) {
  16703. uniforms.dashSize.value = material.dashSize;
  16704. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16705. uniforms.scale.value = material.scale;
  16706. }
  16707. function refreshUniformsPoints(uniforms, material) {
  16708. uniforms.diffuse.value.copy(material.color);
  16709. uniforms.opacity.value = material.opacity;
  16710. uniforms.size.value = material.size * _pixelRatio;
  16711. uniforms.scale.value = _height * 0.5;
  16712. uniforms.map.value = material.map;
  16713. if (material.map !== null) {
  16714. if (material.map.matrixAutoUpdate === true) {
  16715. material.map.updateMatrix();
  16716. }
  16717. uniforms.uvTransform.value.copy(material.map.matrix);
  16718. }
  16719. }
  16720. function refreshUniformsSprites(uniforms, material) {
  16721. uniforms.diffuse.value.copy(material.color);
  16722. uniforms.opacity.value = material.opacity;
  16723. uniforms.rotation.value = material.rotation;
  16724. uniforms.map.value = material.map;
  16725. if (material.map !== null) {
  16726. if (material.map.matrixAutoUpdate === true) {
  16727. material.map.updateMatrix();
  16728. }
  16729. uniforms.uvTransform.value.copy(material.map.matrix);
  16730. }
  16731. }
  16732. function refreshUniformsFog(uniforms, fog) {
  16733. uniforms.fogColor.value.copy(fog.color);
  16734. if (fog.isFog) {
  16735. uniforms.fogNear.value = fog.near;
  16736. uniforms.fogFar.value = fog.far;
  16737. } else if (fog.isFogExp2) {
  16738. uniforms.fogDensity.value = fog.density;
  16739. }
  16740. }
  16741. function refreshUniformsLambert(uniforms, material) {
  16742. if (material.emissiveMap) {
  16743. uniforms.emissiveMap.value = material.emissiveMap;
  16744. }
  16745. }
  16746. function refreshUniformsPhong(uniforms, material) {
  16747. uniforms.specular.value.copy(material.specular);
  16748. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16749. if (material.emissiveMap) {
  16750. uniforms.emissiveMap.value = material.emissiveMap;
  16751. }
  16752. if (material.bumpMap) {
  16753. uniforms.bumpMap.value = material.bumpMap;
  16754. uniforms.bumpScale.value = material.bumpScale;
  16755. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16756. }
  16757. if (material.normalMap) {
  16758. uniforms.normalMap.value = material.normalMap;
  16759. uniforms.normalScale.value.copy(material.normalScale);
  16760. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16761. }
  16762. if (material.displacementMap) {
  16763. uniforms.displacementMap.value = material.displacementMap;
  16764. uniforms.displacementScale.value = material.displacementScale;
  16765. uniforms.displacementBias.value = material.displacementBias;
  16766. }
  16767. }
  16768. function refreshUniformsToon(uniforms, material) {
  16769. refreshUniformsPhong(uniforms, material);
  16770. if (material.gradientMap) {
  16771. uniforms.gradientMap.value = material.gradientMap;
  16772. }
  16773. }
  16774. function refreshUniformsStandard(uniforms, material) {
  16775. uniforms.roughness.value = material.roughness;
  16776. uniforms.metalness.value = material.metalness;
  16777. if (material.roughnessMap) {
  16778. uniforms.roughnessMap.value = material.roughnessMap;
  16779. }
  16780. if (material.metalnessMap) {
  16781. uniforms.metalnessMap.value = material.metalnessMap;
  16782. }
  16783. if (material.emissiveMap) {
  16784. uniforms.emissiveMap.value = material.emissiveMap;
  16785. }
  16786. if (material.bumpMap) {
  16787. uniforms.bumpMap.value = material.bumpMap;
  16788. uniforms.bumpScale.value = material.bumpScale;
  16789. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16790. }
  16791. if (material.normalMap) {
  16792. uniforms.normalMap.value = material.normalMap;
  16793. uniforms.normalScale.value.copy(material.normalScale);
  16794. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16795. }
  16796. if (material.displacementMap) {
  16797. uniforms.displacementMap.value = material.displacementMap;
  16798. uniforms.displacementScale.value = material.displacementScale;
  16799. uniforms.displacementBias.value = material.displacementBias;
  16800. }
  16801. if (material.envMap) {
  16802. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16803. uniforms.envMapIntensity.value = material.envMapIntensity;
  16804. }
  16805. }
  16806. function refreshUniformsPhysical(uniforms, material) {
  16807. refreshUniformsStandard(uniforms, material);
  16808. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  16809. uniforms.clearcoat.value = material.clearcoat;
  16810. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16811. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  16812. if (material.clearcoatNormalMap) {
  16813. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16814. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16815. if (material.side === BackSide) {
  16816. uniforms.clearcoatNormalScale.value.negate();
  16817. }
  16818. }
  16819. uniforms.transparency.value = material.transparency;
  16820. }
  16821. function refreshUniformsMatcap(uniforms, material) {
  16822. if (material.matcap) {
  16823. uniforms.matcap.value = material.matcap;
  16824. }
  16825. if (material.bumpMap) {
  16826. uniforms.bumpMap.value = material.bumpMap;
  16827. uniforms.bumpScale.value = material.bumpScale;
  16828. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16829. }
  16830. if (material.normalMap) {
  16831. uniforms.normalMap.value = material.normalMap;
  16832. uniforms.normalScale.value.copy(material.normalScale);
  16833. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16834. }
  16835. if (material.displacementMap) {
  16836. uniforms.displacementMap.value = material.displacementMap;
  16837. uniforms.displacementScale.value = material.displacementScale;
  16838. uniforms.displacementBias.value = material.displacementBias;
  16839. }
  16840. }
  16841. function refreshUniformsDepth(uniforms, material) {
  16842. if (material.displacementMap) {
  16843. uniforms.displacementMap.value = material.displacementMap;
  16844. uniforms.displacementScale.value = material.displacementScale;
  16845. uniforms.displacementBias.value = material.displacementBias;
  16846. }
  16847. }
  16848. function refreshUniformsDistance(uniforms, material) {
  16849. if (material.displacementMap) {
  16850. uniforms.displacementMap.value = material.displacementMap;
  16851. uniforms.displacementScale.value = material.displacementScale;
  16852. uniforms.displacementBias.value = material.displacementBias;
  16853. }
  16854. uniforms.referencePosition.value.copy(material.referencePosition);
  16855. uniforms.nearDistance.value = material.nearDistance;
  16856. uniforms.farDistance.value = material.farDistance;
  16857. }
  16858. function refreshUniformsNormal(uniforms, material) {
  16859. if (material.bumpMap) {
  16860. uniforms.bumpMap.value = material.bumpMap;
  16861. uniforms.bumpScale.value = material.bumpScale;
  16862. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16863. }
  16864. if (material.normalMap) {
  16865. uniforms.normalMap.value = material.normalMap;
  16866. uniforms.normalScale.value.copy(material.normalScale);
  16867. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16868. }
  16869. if (material.displacementMap) {
  16870. uniforms.displacementMap.value = material.displacementMap;
  16871. uniforms.displacementScale.value = material.displacementScale;
  16872. uniforms.displacementBias.value = material.displacementBias;
  16873. }
  16874. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16875. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16876. uniforms.ambientLightColor.needsUpdate = value;
  16877. uniforms.lightProbe.needsUpdate = value;
  16878. uniforms.directionalLights.needsUpdate = value;
  16879. uniforms.pointLights.needsUpdate = value;
  16880. uniforms.spotLights.needsUpdate = value;
  16881. uniforms.rectAreaLights.needsUpdate = value;
  16882. uniforms.hemisphereLights.needsUpdate = value;
  16883. }
  16884. function materialNeedsLights(material) {
  16885. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16886. } //
  16887. this.setFramebuffer = function (value) {
  16888. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  16889. _framebuffer = value;
  16890. };
  16891. this.getActiveCubeFace = function () {
  16892. return _currentActiveCubeFace;
  16893. };
  16894. this.getActiveMipmapLevel = function () {
  16895. return _currentActiveMipmapLevel;
  16896. };
  16897. this.getRenderTarget = function () {
  16898. return _currentRenderTarget;
  16899. };
  16900. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  16901. _currentRenderTarget = renderTarget;
  16902. _currentActiveCubeFace = activeCubeFace;
  16903. _currentActiveMipmapLevel = activeMipmapLevel;
  16904. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16905. textures.setupRenderTarget(renderTarget);
  16906. }
  16907. var framebuffer = _framebuffer;
  16908. var isCube = false;
  16909. if (renderTarget) {
  16910. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16911. if (renderTarget.isWebGLRenderTargetCube) {
  16912. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  16913. isCube = true;
  16914. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16915. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16916. } else {
  16917. framebuffer = __webglFramebuffer;
  16918. }
  16919. _currentViewport.copy(renderTarget.viewport);
  16920. _currentScissor.copy(renderTarget.scissor);
  16921. _currentScissorTest = renderTarget.scissorTest;
  16922. } else {
  16923. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16924. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16925. _currentScissorTest = _scissorTest;
  16926. }
  16927. if (_currentFramebuffer !== framebuffer) {
  16928. _gl.bindFramebuffer(36160, framebuffer);
  16929. _currentFramebuffer = framebuffer;
  16930. }
  16931. state.viewport(_currentViewport);
  16932. state.scissor(_currentScissor);
  16933. state.setScissorTest(_currentScissorTest);
  16934. if (isCube) {
  16935. var textureProperties = properties.get(renderTarget.texture);
  16936. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  16937. }
  16938. };
  16939. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16940. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16941. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16942. return;
  16943. }
  16944. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16945. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  16946. framebuffer = framebuffer[activeCubeFaceIndex];
  16947. }
  16948. if (framebuffer) {
  16949. var restore = false;
  16950. if (framebuffer !== _currentFramebuffer) {
  16951. _gl.bindFramebuffer(36160, framebuffer);
  16952. restore = true;
  16953. }
  16954. try {
  16955. var texture = renderTarget.texture;
  16956. var textureFormat = texture.format;
  16957. var textureType = texture.type;
  16958. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16959. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16960. return;
  16961. }
  16962. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16963. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16964. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16965. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16966. return;
  16967. }
  16968. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16969. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16970. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16971. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16972. }
  16973. } else {
  16974. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16975. }
  16976. } finally {
  16977. if (restore) {
  16978. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16979. }
  16980. }
  16981. }
  16982. };
  16983. this.copyFramebufferToTexture = function (position, texture, level) {
  16984. var width = texture.image.width;
  16985. var height = texture.image.height;
  16986. var glFormat = utils.convert(texture.format);
  16987. textures.setTexture2D(texture, 0);
  16988. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  16989. };
  16990. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16991. var width = srcTexture.image.width;
  16992. var height = srcTexture.image.height;
  16993. var glFormat = utils.convert(dstTexture.format);
  16994. var glType = utils.convert(dstTexture.type);
  16995. textures.setTexture2D(dstTexture, 0);
  16996. if (srcTexture.isDataTexture) {
  16997. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16998. } else {
  16999. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  17000. }
  17001. };
  17002. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17003. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17004. detail: this
  17005. })); // eslint-disable-line no-undef
  17006. }
  17007. }
  17008. /**
  17009. * @author mrdoob / http://mrdoob.com/
  17010. * @author alteredq / http://alteredqualia.com/
  17011. */
  17012. function FogExp2(color, density) {
  17013. this.name = '';
  17014. this.color = new Color(color);
  17015. this.density = density !== undefined ? density : 0.00025;
  17016. }
  17017. Object.assign(FogExp2.prototype, {
  17018. isFogExp2: true,
  17019. clone: function () {
  17020. return new FogExp2(this.color, this.density);
  17021. },
  17022. toJSON: function ()
  17023. /* meta */
  17024. {
  17025. return {
  17026. type: 'FogExp2',
  17027. color: this.color.getHex(),
  17028. density: this.density
  17029. };
  17030. }
  17031. });
  17032. /**
  17033. * @author mrdoob / http://mrdoob.com/
  17034. * @author alteredq / http://alteredqualia.com/
  17035. */
  17036. function Fog(color, near, far) {
  17037. this.name = '';
  17038. this.color = new Color(color);
  17039. this.near = near !== undefined ? near : 1;
  17040. this.far = far !== undefined ? far : 1000;
  17041. }
  17042. Object.assign(Fog.prototype, {
  17043. isFog: true,
  17044. clone: function () {
  17045. return new Fog(this.color, this.near, this.far);
  17046. },
  17047. toJSON: function ()
  17048. /* meta */
  17049. {
  17050. return {
  17051. type: 'Fog',
  17052. color: this.color.getHex(),
  17053. near: this.near,
  17054. far: this.far
  17055. };
  17056. }
  17057. });
  17058. /**
  17059. * @author benaadams / https://twitter.com/ben_a_adams
  17060. */
  17061. function InterleavedBuffer(array, stride) {
  17062. this.array = array;
  17063. this.stride = stride;
  17064. this.count = array !== undefined ? array.length / stride : 0;
  17065. this.dynamic = false;
  17066. this.updateRange = {
  17067. offset: 0,
  17068. count: -1
  17069. };
  17070. this.version = 0;
  17071. }
  17072. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  17073. set: function (value) {
  17074. if (value === true) this.version++;
  17075. }
  17076. });
  17077. Object.assign(InterleavedBuffer.prototype, {
  17078. isInterleavedBuffer: true,
  17079. onUploadCallback: function () {},
  17080. setDynamic: function (value) {
  17081. this.dynamic = value;
  17082. return this;
  17083. },
  17084. copy: function (source) {
  17085. this.array = new source.array.constructor(source.array);
  17086. this.count = source.count;
  17087. this.stride = source.stride;
  17088. this.dynamic = source.dynamic;
  17089. return this;
  17090. },
  17091. copyAt: function (index1, attribute, index2) {
  17092. index1 *= this.stride;
  17093. index2 *= attribute.stride;
  17094. for (var i = 0, l = this.stride; i < l; i++) {
  17095. this.array[index1 + i] = attribute.array[index2 + i];
  17096. }
  17097. return this;
  17098. },
  17099. set: function (value, offset) {
  17100. if (offset === undefined) offset = 0;
  17101. this.array.set(value, offset);
  17102. return this;
  17103. },
  17104. clone: function () {
  17105. return new this.constructor().copy(this);
  17106. },
  17107. onUpload: function (callback) {
  17108. this.onUploadCallback = callback;
  17109. return this;
  17110. }
  17111. });
  17112. /**
  17113. * @author benaadams / https://twitter.com/ben_a_adams
  17114. */
  17115. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  17116. this.data = interleavedBuffer;
  17117. this.itemSize = itemSize;
  17118. this.offset = offset;
  17119. this.normalized = normalized === true;
  17120. }
  17121. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  17122. count: {
  17123. get: function () {
  17124. return this.data.count;
  17125. }
  17126. },
  17127. array: {
  17128. get: function () {
  17129. return this.data.array;
  17130. }
  17131. }
  17132. });
  17133. Object.assign(InterleavedBufferAttribute.prototype, {
  17134. isInterleavedBufferAttribute: true,
  17135. setX: function (index, x) {
  17136. this.data.array[index * this.data.stride + this.offset] = x;
  17137. return this;
  17138. },
  17139. setY: function (index, y) {
  17140. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17141. return this;
  17142. },
  17143. setZ: function (index, z) {
  17144. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17145. return this;
  17146. },
  17147. setW: function (index, w) {
  17148. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17149. return this;
  17150. },
  17151. getX: function (index) {
  17152. return this.data.array[index * this.data.stride + this.offset];
  17153. },
  17154. getY: function (index) {
  17155. return this.data.array[index * this.data.stride + this.offset + 1];
  17156. },
  17157. getZ: function (index) {
  17158. return this.data.array[index * this.data.stride + this.offset + 2];
  17159. },
  17160. getW: function (index) {
  17161. return this.data.array[index * this.data.stride + this.offset + 3];
  17162. },
  17163. setXY: function (index, x, y) {
  17164. index = index * this.data.stride + this.offset;
  17165. this.data.array[index + 0] = x;
  17166. this.data.array[index + 1] = y;
  17167. return this;
  17168. },
  17169. setXYZ: function (index, x, y, z) {
  17170. index = index * this.data.stride + this.offset;
  17171. this.data.array[index + 0] = x;
  17172. this.data.array[index + 1] = y;
  17173. this.data.array[index + 2] = z;
  17174. return this;
  17175. },
  17176. setXYZW: function (index, x, y, z, w) {
  17177. index = index * this.data.stride + this.offset;
  17178. this.data.array[index + 0] = x;
  17179. this.data.array[index + 1] = y;
  17180. this.data.array[index + 2] = z;
  17181. this.data.array[index + 3] = w;
  17182. return this;
  17183. }
  17184. });
  17185. /**
  17186. * @author alteredq / http://alteredqualia.com/
  17187. *
  17188. * parameters = {
  17189. * color: <hex>,
  17190. * map: new THREE.Texture( <Image> ),
  17191. * rotation: <float>,
  17192. * sizeAttenuation: <bool>
  17193. * }
  17194. */
  17195. function SpriteMaterial(parameters) {
  17196. Material.call(this);
  17197. this.type = 'SpriteMaterial';
  17198. this.color = new Color(0xffffff);
  17199. this.map = null;
  17200. this.rotation = 0;
  17201. this.sizeAttenuation = true;
  17202. this.transparent = true;
  17203. this.setValues(parameters);
  17204. }
  17205. SpriteMaterial.prototype = Object.create(Material.prototype);
  17206. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17207. SpriteMaterial.prototype.isSpriteMaterial = true;
  17208. SpriteMaterial.prototype.copy = function (source) {
  17209. Material.prototype.copy.call(this, source);
  17210. this.color.copy(source.color);
  17211. this.map = source.map;
  17212. this.rotation = source.rotation;
  17213. this.sizeAttenuation = source.sizeAttenuation;
  17214. return this;
  17215. };
  17216. /**
  17217. * @author mikael emtinger / http://gomo.se/
  17218. * @author alteredq / http://alteredqualia.com/
  17219. */
  17220. var _geometry;
  17221. var _intersectPoint = new Vector3();
  17222. var _worldScale = new Vector3();
  17223. var _mvPosition = new Vector3();
  17224. var _alignedPosition = new Vector2();
  17225. var _rotatedPosition = new Vector2();
  17226. var _viewWorldMatrix = new Matrix4();
  17227. var _vA$1 = new Vector3();
  17228. var _vB$1 = new Vector3();
  17229. var _vC$1 = new Vector3();
  17230. var _uvA$1 = new Vector2();
  17231. var _uvB$1 = new Vector2();
  17232. var _uvC$1 = new Vector2();
  17233. function Sprite(material) {
  17234. Object3D.call(this);
  17235. this.type = 'Sprite';
  17236. if (_geometry === undefined) {
  17237. _geometry = new BufferGeometry();
  17238. 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]);
  17239. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17240. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17241. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17242. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17243. }
  17244. this.geometry = _geometry;
  17245. this.material = material !== undefined ? material : new SpriteMaterial();
  17246. this.center = new Vector2(0.5, 0.5);
  17247. }
  17248. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  17249. constructor: Sprite,
  17250. isSprite: true,
  17251. raycast: function (raycaster, intersects) {
  17252. if (raycaster.camera === null) {
  17253. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17254. }
  17255. _worldScale.setFromMatrixScale(this.matrixWorld);
  17256. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17257. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17258. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17259. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17260. _worldScale.multiplyScalar(-_mvPosition.z);
  17261. }
  17262. var rotation = this.material.rotation;
  17263. var sin, cos;
  17264. if (rotation !== 0) {
  17265. cos = Math.cos(rotation);
  17266. sin = Math.sin(rotation);
  17267. }
  17268. var center = this.center;
  17269. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17270. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17271. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17272. _uvA$1.set(0, 0);
  17273. _uvB$1.set(1, 0);
  17274. _uvC$1.set(1, 1); // check first triangle
  17275. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  17276. if (intersect === null) {
  17277. // check second triangle
  17278. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17279. _uvB$1.set(0, 1);
  17280. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  17281. if (intersect === null) {
  17282. return;
  17283. }
  17284. }
  17285. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17286. if (distance < raycaster.near || distance > raycaster.far) return;
  17287. intersects.push({
  17288. distance: distance,
  17289. point: _intersectPoint.clone(),
  17290. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  17291. face: null,
  17292. object: this
  17293. });
  17294. },
  17295. clone: function () {
  17296. return new this.constructor(this.material).copy(this);
  17297. },
  17298. copy: function (source) {
  17299. Object3D.prototype.copy.call(this, source);
  17300. if (source.center !== undefined) this.center.copy(source.center);
  17301. return this;
  17302. }
  17303. });
  17304. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17305. // compute position in camera space
  17306. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17307. if (sin !== undefined) {
  17308. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17309. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17310. } else {
  17311. _rotatedPosition.copy(_alignedPosition);
  17312. }
  17313. vertexPosition.copy(mvPosition);
  17314. vertexPosition.x += _rotatedPosition.x;
  17315. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17316. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17317. }
  17318. /**
  17319. * @author mikael emtinger / http://gomo.se/
  17320. * @author alteredq / http://alteredqualia.com/
  17321. * @author mrdoob / http://mrdoob.com/
  17322. */
  17323. var _v1$4 = new Vector3();
  17324. var _v2$2 = new Vector3();
  17325. function LOD() {
  17326. Object3D.call(this);
  17327. this.type = 'LOD';
  17328. Object.defineProperties(this, {
  17329. levels: {
  17330. enumerable: true,
  17331. value: []
  17332. }
  17333. });
  17334. this.autoUpdate = true;
  17335. }
  17336. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  17337. constructor: LOD,
  17338. isLOD: true,
  17339. copy: function (source) {
  17340. Object3D.prototype.copy.call(this, source, false);
  17341. var levels = source.levels;
  17342. for (var i = 0, l = levels.length; i < l; i++) {
  17343. var level = levels[i];
  17344. this.addLevel(level.object.clone(), level.distance);
  17345. }
  17346. return this;
  17347. },
  17348. addLevel: function (object, distance) {
  17349. if (distance === undefined) distance = 0;
  17350. distance = Math.abs(distance);
  17351. var levels = this.levels;
  17352. for (var l = 0; l < levels.length; l++) {
  17353. if (distance < levels[l].distance) {
  17354. break;
  17355. }
  17356. }
  17357. levels.splice(l, 0, {
  17358. distance: distance,
  17359. object: object
  17360. });
  17361. this.add(object);
  17362. return this;
  17363. },
  17364. getObjectForDistance: function (distance) {
  17365. var levels = this.levels;
  17366. for (var i = 1, l = levels.length; i < l; i++) {
  17367. if (distance < levels[i].distance) {
  17368. break;
  17369. }
  17370. }
  17371. return levels[i - 1].object;
  17372. },
  17373. raycast: function (raycaster, intersects) {
  17374. _v1$4.setFromMatrixPosition(this.matrixWorld);
  17375. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  17376. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17377. },
  17378. update: function (camera) {
  17379. var levels = this.levels;
  17380. if (levels.length > 1) {
  17381. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  17382. _v2$2.setFromMatrixPosition(this.matrixWorld);
  17383. var distance = _v1$4.distanceTo(_v2$2);
  17384. levels[0].object.visible = true;
  17385. for (var i = 1, l = levels.length; i < l; i++) {
  17386. if (distance >= levels[i].distance) {
  17387. levels[i - 1].object.visible = false;
  17388. levels[i].object.visible = true;
  17389. } else {
  17390. break;
  17391. }
  17392. }
  17393. for (; i < l; i++) {
  17394. levels[i].object.visible = false;
  17395. }
  17396. }
  17397. },
  17398. toJSON: function (meta) {
  17399. var data = Object3D.prototype.toJSON.call(this, meta);
  17400. data.object.levels = [];
  17401. var levels = this.levels;
  17402. for (var i = 0, l = levels.length; i < l; i++) {
  17403. var level = levels[i];
  17404. data.object.levels.push({
  17405. object: level.object.uuid,
  17406. distance: level.distance
  17407. });
  17408. }
  17409. return data;
  17410. }
  17411. });
  17412. /**
  17413. * @author mikael emtinger / http://gomo.se/
  17414. * @author alteredq / http://alteredqualia.com/
  17415. * @author ikerr / http://verold.com
  17416. */
  17417. function SkinnedMesh(geometry, material) {
  17418. if (geometry && geometry.isGeometry) {
  17419. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17420. }
  17421. Mesh.call(this, geometry, material);
  17422. this.type = 'SkinnedMesh';
  17423. this.bindMode = 'attached';
  17424. this.bindMatrix = new Matrix4();
  17425. this.bindMatrixInverse = new Matrix4();
  17426. }
  17427. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17428. constructor: SkinnedMesh,
  17429. isSkinnedMesh: true,
  17430. bind: function (skeleton, bindMatrix) {
  17431. this.skeleton = skeleton;
  17432. if (bindMatrix === undefined) {
  17433. this.updateMatrixWorld(true);
  17434. this.skeleton.calculateInverses();
  17435. bindMatrix = this.matrixWorld;
  17436. }
  17437. this.bindMatrix.copy(bindMatrix);
  17438. this.bindMatrixInverse.getInverse(bindMatrix);
  17439. },
  17440. pose: function () {
  17441. this.skeleton.pose();
  17442. },
  17443. normalizeSkinWeights: function () {
  17444. var vector = new Vector4();
  17445. var skinWeight = this.geometry.attributes.skinWeight;
  17446. for (var i = 0, l = skinWeight.count; i < l; i++) {
  17447. vector.x = skinWeight.getX(i);
  17448. vector.y = skinWeight.getY(i);
  17449. vector.z = skinWeight.getZ(i);
  17450. vector.w = skinWeight.getW(i);
  17451. var scale = 1.0 / vector.manhattanLength();
  17452. if (scale !== Infinity) {
  17453. vector.multiplyScalar(scale);
  17454. } else {
  17455. vector.set(1, 0, 0, 0); // do something reasonable
  17456. }
  17457. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17458. }
  17459. },
  17460. updateMatrixWorld: function (force) {
  17461. Mesh.prototype.updateMatrixWorld.call(this, force);
  17462. if (this.bindMode === 'attached') {
  17463. this.bindMatrixInverse.getInverse(this.matrixWorld);
  17464. } else if (this.bindMode === 'detached') {
  17465. this.bindMatrixInverse.getInverse(this.bindMatrix);
  17466. } else {
  17467. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17468. }
  17469. },
  17470. clone: function () {
  17471. return new this.constructor(this.geometry, this.material).copy(this);
  17472. }
  17473. });
  17474. /**
  17475. * @author mikael emtinger / http://gomo.se/
  17476. * @author alteredq / http://alteredqualia.com/
  17477. * @author michael guerrero / http://realitymeltdown.com
  17478. * @author ikerr / http://verold.com
  17479. */
  17480. var _offsetMatrix = new Matrix4();
  17481. var _identityMatrix = new Matrix4();
  17482. function Skeleton(bones, boneInverses) {
  17483. // copy the bone array
  17484. bones = bones || [];
  17485. this.bones = bones.slice(0);
  17486. this.boneMatrices = new Float32Array(this.bones.length * 16);
  17487. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  17488. if (boneInverses === undefined) {
  17489. this.calculateInverses();
  17490. } else {
  17491. if (this.bones.length === boneInverses.length) {
  17492. this.boneInverses = boneInverses.slice(0);
  17493. } else {
  17494. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  17495. this.boneInverses = [];
  17496. for (var i = 0, il = this.bones.length; i < il; i++) {
  17497. this.boneInverses.push(new Matrix4());
  17498. }
  17499. }
  17500. }
  17501. }
  17502. Object.assign(Skeleton.prototype, {
  17503. calculateInverses: function () {
  17504. this.boneInverses = [];
  17505. for (var i = 0, il = this.bones.length; i < il; i++) {
  17506. var inverse = new Matrix4();
  17507. if (this.bones[i]) {
  17508. inverse.getInverse(this.bones[i].matrixWorld);
  17509. }
  17510. this.boneInverses.push(inverse);
  17511. }
  17512. },
  17513. pose: function () {
  17514. var bone, i, il; // recover the bind-time world matrices
  17515. for (i = 0, il = this.bones.length; i < il; i++) {
  17516. bone = this.bones[i];
  17517. if (bone) {
  17518. bone.matrixWorld.getInverse(this.boneInverses[i]);
  17519. }
  17520. } // compute the local matrices, positions, rotations and scales
  17521. for (i = 0, il = this.bones.length; i < il; i++) {
  17522. bone = this.bones[i];
  17523. if (bone) {
  17524. if (bone.parent && bone.parent.isBone) {
  17525. bone.matrix.getInverse(bone.parent.matrixWorld);
  17526. bone.matrix.multiply(bone.matrixWorld);
  17527. } else {
  17528. bone.matrix.copy(bone.matrixWorld);
  17529. }
  17530. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17531. }
  17532. }
  17533. },
  17534. update: function () {
  17535. var bones = this.bones;
  17536. var boneInverses = this.boneInverses;
  17537. var boneMatrices = this.boneMatrices;
  17538. var boneTexture = this.boneTexture; // flatten bone matrices to array
  17539. for (var i = 0, il = bones.length; i < il; i++) {
  17540. // compute the offset between the current and the original transform
  17541. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17542. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17543. _offsetMatrix.toArray(boneMatrices, i * 16);
  17544. }
  17545. if (boneTexture !== undefined) {
  17546. boneTexture.needsUpdate = true;
  17547. }
  17548. },
  17549. clone: function () {
  17550. return new Skeleton(this.bones, this.boneInverses);
  17551. },
  17552. getBoneByName: function (name) {
  17553. for (var i = 0, il = this.bones.length; i < il; i++) {
  17554. var bone = this.bones[i];
  17555. if (bone.name === name) {
  17556. return bone;
  17557. }
  17558. }
  17559. return undefined;
  17560. }
  17561. });
  17562. /**
  17563. * @author mikael emtinger / http://gomo.se/
  17564. * @author alteredq / http://alteredqualia.com/
  17565. * @author ikerr / http://verold.com
  17566. */
  17567. function Bone() {
  17568. Object3D.call(this);
  17569. this.type = 'Bone';
  17570. }
  17571. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  17572. constructor: Bone,
  17573. isBone: true
  17574. });
  17575. /**
  17576. * @author mrdoob / http://mrdoob.com/
  17577. */
  17578. function InstancedMesh(geometry, material, count) {
  17579. Mesh.call(this, geometry, material);
  17580. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  17581. this.count = count;
  17582. }
  17583. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17584. constructor: InstancedMesh,
  17585. isInstancedMesh: true,
  17586. raycast: function () {},
  17587. setMatrixAt: function (index, matrix) {
  17588. matrix.toArray(this.instanceMatrix.array, index * 16);
  17589. },
  17590. updateMorphTargets: function () {}
  17591. });
  17592. /**
  17593. * @author mrdoob / http://mrdoob.com/
  17594. * @author alteredq / http://alteredqualia.com/
  17595. *
  17596. * parameters = {
  17597. * color: <hex>,
  17598. * opacity: <float>,
  17599. *
  17600. * linewidth: <float>,
  17601. * linecap: "round",
  17602. * linejoin: "round"
  17603. * }
  17604. */
  17605. function LineBasicMaterial(parameters) {
  17606. Material.call(this);
  17607. this.type = 'LineBasicMaterial';
  17608. this.color = new Color(0xffffff);
  17609. this.linewidth = 1;
  17610. this.linecap = 'round';
  17611. this.linejoin = 'round';
  17612. this.setValues(parameters);
  17613. }
  17614. LineBasicMaterial.prototype = Object.create(Material.prototype);
  17615. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  17616. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17617. LineBasicMaterial.prototype.copy = function (source) {
  17618. Material.prototype.copy.call(this, source);
  17619. this.color.copy(source.color);
  17620. this.linewidth = source.linewidth;
  17621. this.linecap = source.linecap;
  17622. this.linejoin = source.linejoin;
  17623. return this;
  17624. };
  17625. /**
  17626. * @author mrdoob / http://mrdoob.com/
  17627. */
  17628. var _start = new Vector3();
  17629. var _end = new Vector3();
  17630. var _inverseMatrix$1 = new Matrix4();
  17631. var _ray$1 = new Ray();
  17632. var _sphere$2 = new Sphere();
  17633. function Line(geometry, material, mode) {
  17634. if (mode === 1) {
  17635. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  17636. }
  17637. Object3D.call(this);
  17638. this.type = 'Line';
  17639. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17640. this.material = material !== undefined ? material : new LineBasicMaterial({
  17641. color: Math.random() * 0xffffff
  17642. });
  17643. }
  17644. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  17645. constructor: Line,
  17646. isLine: true,
  17647. computeLineDistances: function () {
  17648. var geometry = this.geometry;
  17649. if (geometry.isBufferGeometry) {
  17650. // we assume non-indexed geometry
  17651. if (geometry.index === null) {
  17652. var positionAttribute = geometry.attributes.position;
  17653. var lineDistances = [0];
  17654. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  17655. _start.fromBufferAttribute(positionAttribute, i - 1);
  17656. _end.fromBufferAttribute(positionAttribute, i);
  17657. lineDistances[i] = lineDistances[i - 1];
  17658. lineDistances[i] += _start.distanceTo(_end);
  17659. }
  17660. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17661. } else {
  17662. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17663. }
  17664. } else if (geometry.isGeometry) {
  17665. var vertices = geometry.vertices;
  17666. var lineDistances = geometry.lineDistances;
  17667. lineDistances[0] = 0;
  17668. for (var i = 1, l = vertices.length; i < l; i++) {
  17669. lineDistances[i] = lineDistances[i - 1];
  17670. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  17671. }
  17672. }
  17673. return this;
  17674. },
  17675. raycast: function (raycaster, intersects) {
  17676. var precision = raycaster.linePrecision;
  17677. var geometry = this.geometry;
  17678. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  17679. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17680. _sphere$2.copy(geometry.boundingSphere);
  17681. _sphere$2.applyMatrix4(matrixWorld);
  17682. _sphere$2.radius += precision;
  17683. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  17684. _inverseMatrix$1.getInverse(matrixWorld);
  17685. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17686. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17687. var localPrecisionSq = localPrecision * localPrecision;
  17688. var vStart = new Vector3();
  17689. var vEnd = new Vector3();
  17690. var interSegment = new Vector3();
  17691. var interRay = new Vector3();
  17692. var step = this && this.isLineSegments ? 2 : 1;
  17693. if (geometry.isBufferGeometry) {
  17694. var index = geometry.index;
  17695. var attributes = geometry.attributes;
  17696. var positions = attributes.position.array;
  17697. if (index !== null) {
  17698. var indices = index.array;
  17699. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  17700. var a = indices[i];
  17701. var b = indices[i + 1];
  17702. vStart.fromArray(positions, a * 3);
  17703. vEnd.fromArray(positions, b * 3);
  17704. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17705. if (distSq > localPrecisionSq) continue;
  17706. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17707. var distance = raycaster.ray.origin.distanceTo(interRay);
  17708. if (distance < raycaster.near || distance > raycaster.far) continue;
  17709. intersects.push({
  17710. distance: distance,
  17711. // What do we want? intersection point on the ray or on the segment??
  17712. // point: raycaster.ray.at( distance ),
  17713. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17714. index: i,
  17715. face: null,
  17716. faceIndex: null,
  17717. object: this
  17718. });
  17719. }
  17720. } else {
  17721. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  17722. vStart.fromArray(positions, 3 * i);
  17723. vEnd.fromArray(positions, 3 * i + 3);
  17724. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17725. if (distSq > localPrecisionSq) continue;
  17726. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17727. var distance = raycaster.ray.origin.distanceTo(interRay);
  17728. if (distance < raycaster.near || distance > raycaster.far) continue;
  17729. intersects.push({
  17730. distance: distance,
  17731. // What do we want? intersection point on the ray or on the segment??
  17732. // point: raycaster.ray.at( distance ),
  17733. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17734. index: i,
  17735. face: null,
  17736. faceIndex: null,
  17737. object: this
  17738. });
  17739. }
  17740. }
  17741. } else if (geometry.isGeometry) {
  17742. var vertices = geometry.vertices;
  17743. var nbVertices = vertices.length;
  17744. for (var i = 0; i < nbVertices - 1; i += step) {
  17745. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  17746. if (distSq > localPrecisionSq) continue;
  17747. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17748. var distance = raycaster.ray.origin.distanceTo(interRay);
  17749. if (distance < raycaster.near || distance > raycaster.far) continue;
  17750. intersects.push({
  17751. distance: distance,
  17752. // What do we want? intersection point on the ray or on the segment??
  17753. // point: raycaster.ray.at( distance ),
  17754. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17755. index: i,
  17756. face: null,
  17757. faceIndex: null,
  17758. object: this
  17759. });
  17760. }
  17761. }
  17762. },
  17763. clone: function () {
  17764. return new this.constructor(this.geometry, this.material).copy(this);
  17765. }
  17766. });
  17767. /**
  17768. * @author mrdoob / http://mrdoob.com/
  17769. */
  17770. var _start$1 = new Vector3();
  17771. var _end$1 = new Vector3();
  17772. function LineSegments(geometry, material) {
  17773. Line.call(this, geometry, material);
  17774. this.type = 'LineSegments';
  17775. }
  17776. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  17777. constructor: LineSegments,
  17778. isLineSegments: true,
  17779. computeLineDistances: function () {
  17780. var geometry = this.geometry;
  17781. if (geometry.isBufferGeometry) {
  17782. // we assume non-indexed geometry
  17783. if (geometry.index === null) {
  17784. var positionAttribute = geometry.attributes.position;
  17785. var lineDistances = [];
  17786. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  17787. _start$1.fromBufferAttribute(positionAttribute, i);
  17788. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  17789. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17790. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17791. }
  17792. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17793. } else {
  17794. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17795. }
  17796. } else if (geometry.isGeometry) {
  17797. var vertices = geometry.vertices;
  17798. var lineDistances = geometry.lineDistances;
  17799. for (var i = 0, l = vertices.length; i < l; i += 2) {
  17800. _start$1.copy(vertices[i]);
  17801. _end$1.copy(vertices[i + 1]);
  17802. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17803. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17804. }
  17805. }
  17806. return this;
  17807. }
  17808. });
  17809. /**
  17810. * @author mgreter / http://github.com/mgreter
  17811. */
  17812. function LineLoop(geometry, material) {
  17813. Line.call(this, geometry, material);
  17814. this.type = 'LineLoop';
  17815. }
  17816. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  17817. constructor: LineLoop,
  17818. isLineLoop: true
  17819. });
  17820. /**
  17821. * @author mrdoob / http://mrdoob.com/
  17822. * @author alteredq / http://alteredqualia.com/
  17823. *
  17824. * parameters = {
  17825. * color: <hex>,
  17826. * opacity: <float>,
  17827. * map: new THREE.Texture( <Image> ),
  17828. *
  17829. * size: <float>,
  17830. * sizeAttenuation: <bool>
  17831. *
  17832. * morphTargets: <bool>
  17833. * }
  17834. */
  17835. function PointsMaterial(parameters) {
  17836. Material.call(this);
  17837. this.type = 'PointsMaterial';
  17838. this.color = new Color(0xffffff);
  17839. this.map = null;
  17840. this.size = 1;
  17841. this.sizeAttenuation = true;
  17842. this.morphTargets = false;
  17843. this.setValues(parameters);
  17844. }
  17845. PointsMaterial.prototype = Object.create(Material.prototype);
  17846. PointsMaterial.prototype.constructor = PointsMaterial;
  17847. PointsMaterial.prototype.isPointsMaterial = true;
  17848. PointsMaterial.prototype.copy = function (source) {
  17849. Material.prototype.copy.call(this, source);
  17850. this.color.copy(source.color);
  17851. this.map = source.map;
  17852. this.size = source.size;
  17853. this.sizeAttenuation = source.sizeAttenuation;
  17854. this.morphTargets = source.morphTargets;
  17855. return this;
  17856. };
  17857. /**
  17858. * @author alteredq / http://alteredqualia.com/
  17859. */
  17860. var _inverseMatrix$2 = new Matrix4();
  17861. var _ray$2 = new Ray();
  17862. var _sphere$3 = new Sphere();
  17863. var _position$1 = new Vector3();
  17864. function Points(geometry, material) {
  17865. Object3D.call(this);
  17866. this.type = 'Points';
  17867. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17868. this.material = material !== undefined ? material : new PointsMaterial({
  17869. color: Math.random() * 0xffffff
  17870. });
  17871. this.updateMorphTargets();
  17872. }
  17873. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  17874. constructor: Points,
  17875. isPoints: true,
  17876. raycast: function (raycaster, intersects) {
  17877. var geometry = this.geometry;
  17878. var matrixWorld = this.matrixWorld;
  17879. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  17880. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17881. _sphere$3.copy(geometry.boundingSphere);
  17882. _sphere$3.applyMatrix4(matrixWorld);
  17883. _sphere$3.radius += threshold;
  17884. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  17885. _inverseMatrix$2.getInverse(matrixWorld);
  17886. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  17887. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17888. var localThresholdSq = localThreshold * localThreshold;
  17889. if (geometry.isBufferGeometry) {
  17890. var index = geometry.index;
  17891. var attributes = geometry.attributes;
  17892. var positions = attributes.position.array;
  17893. if (index !== null) {
  17894. var indices = index.array;
  17895. for (var i = 0, il = indices.length; i < il; i++) {
  17896. var a = indices[i];
  17897. _position$1.fromArray(positions, a * 3);
  17898. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17899. }
  17900. } else {
  17901. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17902. _position$1.fromArray(positions, i * 3);
  17903. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17904. }
  17905. }
  17906. } else {
  17907. var vertices = geometry.vertices;
  17908. for (var i = 0, l = vertices.length; i < l; i++) {
  17909. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17910. }
  17911. }
  17912. },
  17913. updateMorphTargets: function () {
  17914. var geometry = this.geometry;
  17915. var m, ml, name;
  17916. if (geometry.isBufferGeometry) {
  17917. var morphAttributes = geometry.morphAttributes;
  17918. var keys = Object.keys(morphAttributes);
  17919. if (keys.length > 0) {
  17920. var morphAttribute = morphAttributes[keys[0]];
  17921. if (morphAttribute !== undefined) {
  17922. this.morphTargetInfluences = [];
  17923. this.morphTargetDictionary = {};
  17924. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17925. name = morphAttribute[m].name || String(m);
  17926. this.morphTargetInfluences.push(0);
  17927. this.morphTargetDictionary[name] = m;
  17928. }
  17929. }
  17930. }
  17931. } else {
  17932. var morphTargets = geometry.morphTargets;
  17933. if (morphTargets !== undefined && morphTargets.length > 0) {
  17934. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17935. }
  17936. }
  17937. },
  17938. clone: function () {
  17939. return new this.constructor(this.geometry, this.material).copy(this);
  17940. }
  17941. });
  17942. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17943. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17944. if (rayPointDistanceSq < localThresholdSq) {
  17945. var intersectPoint = new Vector3();
  17946. _ray$2.closestPointToPoint(point, intersectPoint);
  17947. intersectPoint.applyMatrix4(matrixWorld);
  17948. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17949. if (distance < raycaster.near || distance > raycaster.far) return;
  17950. intersects.push({
  17951. distance: distance,
  17952. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17953. point: intersectPoint,
  17954. index: index,
  17955. face: null,
  17956. object: object
  17957. });
  17958. }
  17959. }
  17960. /**
  17961. * @author mrdoob / http://mrdoob.com/
  17962. */
  17963. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17964. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17965. this.format = format !== undefined ? format : RGBFormat;
  17966. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17967. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17968. this.generateMipmaps = false;
  17969. }
  17970. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17971. constructor: VideoTexture,
  17972. isVideoTexture: true,
  17973. update: function () {
  17974. var video = this.image;
  17975. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17976. this.needsUpdate = true;
  17977. }
  17978. }
  17979. });
  17980. /**
  17981. * @author alteredq / http://alteredqualia.com/
  17982. */
  17983. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17984. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17985. this.image = {
  17986. width: width,
  17987. height: height
  17988. };
  17989. this.mipmaps = mipmaps; // no flipping for cube textures
  17990. // (also flipping doesn't work for compressed textures )
  17991. this.flipY = false; // can't generate mipmaps for compressed textures
  17992. // mips must be embedded in DDS files
  17993. this.generateMipmaps = false;
  17994. }
  17995. CompressedTexture.prototype = Object.create(Texture.prototype);
  17996. CompressedTexture.prototype.constructor = CompressedTexture;
  17997. CompressedTexture.prototype.isCompressedTexture = true;
  17998. /**
  17999. * @author mrdoob / http://mrdoob.com/
  18000. */
  18001. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18002. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18003. this.needsUpdate = true;
  18004. }
  18005. CanvasTexture.prototype = Object.create(Texture.prototype);
  18006. CanvasTexture.prototype.constructor = CanvasTexture;
  18007. CanvasTexture.prototype.isCanvasTexture = true;
  18008. /**
  18009. * @author Matt DesLauriers / @mattdesl
  18010. * @author atix / arthursilber.de
  18011. */
  18012. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  18013. format = format !== undefined ? format : DepthFormat;
  18014. if (format !== DepthFormat && format !== DepthStencilFormat) {
  18015. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  18016. }
  18017. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  18018. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  18019. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18020. this.image = {
  18021. width: width,
  18022. height: height
  18023. };
  18024. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18025. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18026. this.flipY = false;
  18027. this.generateMipmaps = false;
  18028. }
  18029. DepthTexture.prototype = Object.create(Texture.prototype);
  18030. DepthTexture.prototype.constructor = DepthTexture;
  18031. DepthTexture.prototype.isDepthTexture = true;
  18032. /**
  18033. * @author mrdoob / http://mrdoob.com/
  18034. * @author Mugen87 / https://github.com/Mugen87
  18035. */
  18036. function WireframeGeometry(geometry) {
  18037. BufferGeometry.call(this);
  18038. this.type = 'WireframeGeometry'; // buffer
  18039. var vertices = []; // helper variables
  18040. var i, j, l, o, ol;
  18041. var edge = [0, 0],
  18042. edges = {},
  18043. e,
  18044. edge1,
  18045. edge2;
  18046. var key,
  18047. keys = ['a', 'b', 'c'];
  18048. var vertex; // different logic for Geometry and BufferGeometry
  18049. if (geometry && geometry.isGeometry) {
  18050. // create a data structure that contains all edges without duplicates
  18051. var faces = geometry.faces;
  18052. for (i = 0, l = faces.length; i < l; i++) {
  18053. var face = faces[i];
  18054. for (j = 0; j < 3; j++) {
  18055. edge1 = face[keys[j]];
  18056. edge2 = face[keys[(j + 1) % 3]];
  18057. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18058. edge[1] = Math.max(edge1, edge2);
  18059. key = edge[0] + ',' + edge[1];
  18060. if (edges[key] === undefined) {
  18061. edges[key] = {
  18062. index1: edge[0],
  18063. index2: edge[1]
  18064. };
  18065. }
  18066. }
  18067. } // generate vertices
  18068. for (key in edges) {
  18069. e = edges[key];
  18070. vertex = geometry.vertices[e.index1];
  18071. vertices.push(vertex.x, vertex.y, vertex.z);
  18072. vertex = geometry.vertices[e.index2];
  18073. vertices.push(vertex.x, vertex.y, vertex.z);
  18074. }
  18075. } else if (geometry && geometry.isBufferGeometry) {
  18076. var position, indices, groups;
  18077. var group, start, count;
  18078. var index1, index2;
  18079. vertex = new Vector3();
  18080. if (geometry.index !== null) {
  18081. // indexed BufferGeometry
  18082. position = geometry.attributes.position;
  18083. indices = geometry.index;
  18084. groups = geometry.groups;
  18085. if (groups.length === 0) {
  18086. groups = [{
  18087. start: 0,
  18088. count: indices.count,
  18089. materialIndex: 0
  18090. }];
  18091. } // create a data structure that contains all eges without duplicates
  18092. for (o = 0, ol = groups.length; o < ol; ++o) {
  18093. group = groups[o];
  18094. start = group.start;
  18095. count = group.count;
  18096. for (i = start, l = start + count; i < l; i += 3) {
  18097. for (j = 0; j < 3; j++) {
  18098. edge1 = indices.getX(i + j);
  18099. edge2 = indices.getX(i + (j + 1) % 3);
  18100. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18101. edge[1] = Math.max(edge1, edge2);
  18102. key = edge[0] + ',' + edge[1];
  18103. if (edges[key] === undefined) {
  18104. edges[key] = {
  18105. index1: edge[0],
  18106. index2: edge[1]
  18107. };
  18108. }
  18109. }
  18110. }
  18111. } // generate vertices
  18112. for (key in edges) {
  18113. e = edges[key];
  18114. vertex.fromBufferAttribute(position, e.index1);
  18115. vertices.push(vertex.x, vertex.y, vertex.z);
  18116. vertex.fromBufferAttribute(position, e.index2);
  18117. vertices.push(vertex.x, vertex.y, vertex.z);
  18118. }
  18119. } else {
  18120. // non-indexed BufferGeometry
  18121. position = geometry.attributes.position;
  18122. for (i = 0, l = position.count / 3; i < l; i++) {
  18123. for (j = 0; j < 3; j++) {
  18124. // three edges per triangle, an edge is represented as (index1, index2)
  18125. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18126. index1 = 3 * i + j;
  18127. vertex.fromBufferAttribute(position, index1);
  18128. vertices.push(vertex.x, vertex.y, vertex.z);
  18129. index2 = 3 * i + (j + 1) % 3;
  18130. vertex.fromBufferAttribute(position, index2);
  18131. vertices.push(vertex.x, vertex.y, vertex.z);
  18132. }
  18133. }
  18134. }
  18135. } // build geometry
  18136. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18137. }
  18138. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  18139. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18140. /**
  18141. * @author zz85 / https://github.com/zz85
  18142. * @author Mugen87 / https://github.com/Mugen87
  18143. *
  18144. * Parametric Surfaces Geometry
  18145. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18146. */
  18147. // ParametricGeometry
  18148. function ParametricGeometry(func, slices, stacks) {
  18149. Geometry.call(this);
  18150. this.type = 'ParametricGeometry';
  18151. this.parameters = {
  18152. func: func,
  18153. slices: slices,
  18154. stacks: stacks
  18155. };
  18156. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  18157. this.mergeVertices();
  18158. }
  18159. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  18160. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  18161. function ParametricBufferGeometry(func, slices, stacks) {
  18162. BufferGeometry.call(this);
  18163. this.type = 'ParametricBufferGeometry';
  18164. this.parameters = {
  18165. func: func,
  18166. slices: slices,
  18167. stacks: stacks
  18168. }; // buffers
  18169. var indices = [];
  18170. var vertices = [];
  18171. var normals = [];
  18172. var uvs = [];
  18173. var EPS = 0.00001;
  18174. var normal = new Vector3();
  18175. var p0 = new Vector3(),
  18176. p1 = new Vector3();
  18177. var pu = new Vector3(),
  18178. pv = new Vector3();
  18179. var i, j;
  18180. if (func.length < 3) {
  18181. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18182. } // generate vertices, normals and uvs
  18183. var sliceCount = slices + 1;
  18184. for (i = 0; i <= stacks; i++) {
  18185. var v = i / stacks;
  18186. for (j = 0; j <= slices; j++) {
  18187. var u = j / slices; // vertex
  18188. func(u, v, p0);
  18189. vertices.push(p0.x, p0.y, p0.z); // normal
  18190. // approximate tangent vectors via finite differences
  18191. if (u - EPS >= 0) {
  18192. func(u - EPS, v, p1);
  18193. pu.subVectors(p0, p1);
  18194. } else {
  18195. func(u + EPS, v, p1);
  18196. pu.subVectors(p1, p0);
  18197. }
  18198. if (v - EPS >= 0) {
  18199. func(u, v - EPS, p1);
  18200. pv.subVectors(p0, p1);
  18201. } else {
  18202. func(u, v + EPS, p1);
  18203. pv.subVectors(p1, p0);
  18204. } // cross product of tangent vectors returns surface normal
  18205. normal.crossVectors(pu, pv).normalize();
  18206. normals.push(normal.x, normal.y, normal.z); // uv
  18207. uvs.push(u, v);
  18208. }
  18209. } // generate indices
  18210. for (i = 0; i < stacks; i++) {
  18211. for (j = 0; j < slices; j++) {
  18212. var a = i * sliceCount + j;
  18213. var b = i * sliceCount + j + 1;
  18214. var c = (i + 1) * sliceCount + j + 1;
  18215. var d = (i + 1) * sliceCount + j; // faces one and two
  18216. indices.push(a, b, d);
  18217. indices.push(b, c, d);
  18218. }
  18219. } // build geometry
  18220. this.setIndex(indices);
  18221. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18222. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18223. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18224. }
  18225. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18226. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18227. /**
  18228. * @author clockworkgeek / https://github.com/clockworkgeek
  18229. * @author timothypratley / https://github.com/timothypratley
  18230. * @author WestLangley / http://github.com/WestLangley
  18231. * @author Mugen87 / https://github.com/Mugen87
  18232. */
  18233. // PolyhedronGeometry
  18234. function PolyhedronGeometry(vertices, indices, radius, detail) {
  18235. Geometry.call(this);
  18236. this.type = 'PolyhedronGeometry';
  18237. this.parameters = {
  18238. vertices: vertices,
  18239. indices: indices,
  18240. radius: radius,
  18241. detail: detail
  18242. };
  18243. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  18244. this.mergeVertices();
  18245. }
  18246. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  18247. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  18248. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  18249. BufferGeometry.call(this);
  18250. this.type = 'PolyhedronBufferGeometry';
  18251. this.parameters = {
  18252. vertices: vertices,
  18253. indices: indices,
  18254. radius: radius,
  18255. detail: detail
  18256. };
  18257. radius = radius || 1;
  18258. detail = detail || 0; // default buffer data
  18259. var vertexBuffer = [];
  18260. var uvBuffer = []; // the subdivision creates the vertex buffer data
  18261. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18262. applyRadius(radius); // finally, create the uv data
  18263. generateUVs(); // build non-indexed geometry
  18264. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18265. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18266. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18267. if (detail === 0) {
  18268. this.computeVertexNormals(); // flat normals
  18269. } else {
  18270. this.normalizeNormals(); // smooth normals
  18271. } // helper functions
  18272. function subdivide(detail) {
  18273. var a = new Vector3();
  18274. var b = new Vector3();
  18275. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18276. for (var i = 0; i < indices.length; i += 3) {
  18277. // get the vertices of the face
  18278. getVertexByIndex(indices[i + 0], a);
  18279. getVertexByIndex(indices[i + 1], b);
  18280. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18281. subdivideFace(a, b, c, detail);
  18282. }
  18283. }
  18284. function subdivideFace(a, b, c, detail) {
  18285. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  18286. var v = [];
  18287. var i, j; // construct all of the vertices for this subdivision
  18288. for (i = 0; i <= cols; i++) {
  18289. v[i] = [];
  18290. var aj = a.clone().lerp(c, i / cols);
  18291. var bj = b.clone().lerp(c, i / cols);
  18292. var rows = cols - i;
  18293. for (j = 0; j <= rows; j++) {
  18294. if (j === 0 && i === cols) {
  18295. v[i][j] = aj;
  18296. } else {
  18297. v[i][j] = aj.clone().lerp(bj, j / rows);
  18298. }
  18299. }
  18300. } // construct all of the faces
  18301. for (i = 0; i < cols; i++) {
  18302. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  18303. var k = Math.floor(j / 2);
  18304. if (j % 2 === 0) {
  18305. pushVertex(v[i][k + 1]);
  18306. pushVertex(v[i + 1][k]);
  18307. pushVertex(v[i][k]);
  18308. } else {
  18309. pushVertex(v[i][k + 1]);
  18310. pushVertex(v[i + 1][k + 1]);
  18311. pushVertex(v[i + 1][k]);
  18312. }
  18313. }
  18314. }
  18315. }
  18316. function applyRadius(radius) {
  18317. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18318. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18319. vertex.x = vertexBuffer[i + 0];
  18320. vertex.y = vertexBuffer[i + 1];
  18321. vertex.z = vertexBuffer[i + 2];
  18322. vertex.normalize().multiplyScalar(radius);
  18323. vertexBuffer[i + 0] = vertex.x;
  18324. vertexBuffer[i + 1] = vertex.y;
  18325. vertexBuffer[i + 2] = vertex.z;
  18326. }
  18327. }
  18328. function generateUVs() {
  18329. var vertex = new Vector3();
  18330. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18331. vertex.x = vertexBuffer[i + 0];
  18332. vertex.y = vertexBuffer[i + 1];
  18333. vertex.z = vertexBuffer[i + 2];
  18334. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18335. var v = inclination(vertex) / Math.PI + 0.5;
  18336. uvBuffer.push(u, 1 - v);
  18337. }
  18338. correctUVs();
  18339. correctSeam();
  18340. }
  18341. function correctSeam() {
  18342. // handle case when face straddles the seam, see #3269
  18343. for (var i = 0; i < uvBuffer.length; i += 6) {
  18344. // uv data of a single face
  18345. var x0 = uvBuffer[i + 0];
  18346. var x1 = uvBuffer[i + 2];
  18347. var x2 = uvBuffer[i + 4];
  18348. var max = Math.max(x0, x1, x2);
  18349. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18350. if (max > 0.9 && min < 0.1) {
  18351. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18352. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18353. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18354. }
  18355. }
  18356. }
  18357. function pushVertex(vertex) {
  18358. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18359. }
  18360. function getVertexByIndex(index, vertex) {
  18361. var stride = index * 3;
  18362. vertex.x = vertices[stride + 0];
  18363. vertex.y = vertices[stride + 1];
  18364. vertex.z = vertices[stride + 2];
  18365. }
  18366. function correctUVs() {
  18367. var a = new Vector3();
  18368. var b = new Vector3();
  18369. var c = new Vector3();
  18370. var centroid = new Vector3();
  18371. var uvA = new Vector2();
  18372. var uvB = new Vector2();
  18373. var uvC = new Vector2();
  18374. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18375. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18376. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18377. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18378. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18379. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18380. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18381. centroid.copy(a).add(b).add(c).divideScalar(3);
  18382. var azi = azimuth(centroid);
  18383. correctUV(uvA, j + 0, a, azi);
  18384. correctUV(uvB, j + 2, b, azi);
  18385. correctUV(uvC, j + 4, c, azi);
  18386. }
  18387. }
  18388. function correctUV(uv, stride, vector, azimuth) {
  18389. if (azimuth < 0 && uv.x === 1) {
  18390. uvBuffer[stride] = uv.x - 1;
  18391. }
  18392. if (vector.x === 0 && vector.z === 0) {
  18393. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18394. }
  18395. } // Angle around the Y axis, counter-clockwise when looking from above.
  18396. function azimuth(vector) {
  18397. return Math.atan2(vector.z, -vector.x);
  18398. } // Angle above the XZ plane.
  18399. function inclination(vector) {
  18400. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18401. }
  18402. }
  18403. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18404. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18405. /**
  18406. * @author timothypratley / https://github.com/timothypratley
  18407. * @author Mugen87 / https://github.com/Mugen87
  18408. */
  18409. // TetrahedronGeometry
  18410. function TetrahedronGeometry(radius, detail) {
  18411. Geometry.call(this);
  18412. this.type = 'TetrahedronGeometry';
  18413. this.parameters = {
  18414. radius: radius,
  18415. detail: detail
  18416. };
  18417. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  18418. this.mergeVertices();
  18419. }
  18420. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  18421. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  18422. function TetrahedronBufferGeometry(radius, detail) {
  18423. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18424. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18425. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18426. this.type = 'TetrahedronBufferGeometry';
  18427. this.parameters = {
  18428. radius: radius,
  18429. detail: detail
  18430. };
  18431. }
  18432. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18433. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18434. /**
  18435. * @author timothypratley / https://github.com/timothypratley
  18436. * @author Mugen87 / https://github.com/Mugen87
  18437. */
  18438. // OctahedronGeometry
  18439. function OctahedronGeometry(radius, detail) {
  18440. Geometry.call(this);
  18441. this.type = 'OctahedronGeometry';
  18442. this.parameters = {
  18443. radius: radius,
  18444. detail: detail
  18445. };
  18446. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  18447. this.mergeVertices();
  18448. }
  18449. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  18450. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  18451. function OctahedronBufferGeometry(radius, detail) {
  18452. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18453. 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];
  18454. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18455. this.type = 'OctahedronBufferGeometry';
  18456. this.parameters = {
  18457. radius: radius,
  18458. detail: detail
  18459. };
  18460. }
  18461. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18462. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18463. /**
  18464. * @author timothypratley / https://github.com/timothypratley
  18465. * @author Mugen87 / https://github.com/Mugen87
  18466. */
  18467. // IcosahedronGeometry
  18468. function IcosahedronGeometry(radius, detail) {
  18469. Geometry.call(this);
  18470. this.type = 'IcosahedronGeometry';
  18471. this.parameters = {
  18472. radius: radius,
  18473. detail: detail
  18474. };
  18475. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  18476. this.mergeVertices();
  18477. }
  18478. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  18479. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  18480. function IcosahedronBufferGeometry(radius, detail) {
  18481. var t = (1 + Math.sqrt(5)) / 2;
  18482. 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];
  18483. 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];
  18484. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18485. this.type = 'IcosahedronBufferGeometry';
  18486. this.parameters = {
  18487. radius: radius,
  18488. detail: detail
  18489. };
  18490. }
  18491. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18492. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18493. /**
  18494. * @author Abe Pazos / https://hamoid.com
  18495. * @author Mugen87 / https://github.com/Mugen87
  18496. */
  18497. // DodecahedronGeometry
  18498. function DodecahedronGeometry(radius, detail) {
  18499. Geometry.call(this);
  18500. this.type = 'DodecahedronGeometry';
  18501. this.parameters = {
  18502. radius: radius,
  18503. detail: detail
  18504. };
  18505. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18506. this.mergeVertices();
  18507. }
  18508. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  18509. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  18510. function DodecahedronBufferGeometry(radius, detail) {
  18511. var t = (1 + Math.sqrt(5)) / 2;
  18512. var r = 1 / t;
  18513. var vertices = [// (±1, ±1, ±1)
  18514. -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/φ, ±φ)
  18515. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18516. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18517. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18518. 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];
  18519. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18520. this.type = 'DodecahedronBufferGeometry';
  18521. this.parameters = {
  18522. radius: radius,
  18523. detail: detail
  18524. };
  18525. }
  18526. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18527. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18528. /**
  18529. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18530. * @author WestLangley / https://github.com/WestLangley
  18531. * @author zz85 / https://github.com/zz85
  18532. * @author miningold / https://github.com/miningold
  18533. * @author jonobr1 / https://github.com/jonobr1
  18534. * @author Mugen87 / https://github.com/Mugen87
  18535. *
  18536. */
  18537. // TubeGeometry
  18538. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  18539. Geometry.call(this);
  18540. this.type = 'TubeGeometry';
  18541. this.parameters = {
  18542. path: path,
  18543. tubularSegments: tubularSegments,
  18544. radius: radius,
  18545. radialSegments: radialSegments,
  18546. closed: closed
  18547. };
  18548. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  18549. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  18550. this.tangents = bufferGeometry.tangents;
  18551. this.normals = bufferGeometry.normals;
  18552. this.binormals = bufferGeometry.binormals; // create geometry
  18553. this.fromBufferGeometry(bufferGeometry);
  18554. this.mergeVertices();
  18555. }
  18556. TubeGeometry.prototype = Object.create(Geometry.prototype);
  18557. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  18558. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  18559. BufferGeometry.call(this);
  18560. this.type = 'TubeBufferGeometry';
  18561. this.parameters = {
  18562. path: path,
  18563. tubularSegments: tubularSegments,
  18564. radius: radius,
  18565. radialSegments: radialSegments,
  18566. closed: closed
  18567. };
  18568. tubularSegments = tubularSegments || 64;
  18569. radius = radius || 1;
  18570. radialSegments = radialSegments || 8;
  18571. closed = closed || false;
  18572. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18573. this.tangents = frames.tangents;
  18574. this.normals = frames.normals;
  18575. this.binormals = frames.binormals; // helper variables
  18576. var vertex = new Vector3();
  18577. var normal = new Vector3();
  18578. var uv = new Vector2();
  18579. var P = new Vector3();
  18580. var i, j; // buffer
  18581. var vertices = [];
  18582. var normals = [];
  18583. var uvs = [];
  18584. var indices = []; // create buffer data
  18585. generateBufferData(); // build geometry
  18586. this.setIndex(indices);
  18587. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18588. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18589. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18590. function generateBufferData() {
  18591. for (i = 0; i < tubularSegments; i++) {
  18592. generateSegment(i);
  18593. } // if the geometry is not closed, generate the last row of vertices and normals
  18594. // at the regular position on the given path
  18595. //
  18596. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18597. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18598. // this makes it easy compute correct values for closed geometries
  18599. generateUVs(); // finally create faces
  18600. generateIndices();
  18601. }
  18602. function generateSegment(i) {
  18603. // we use getPointAt to sample evenly distributed points from the given path
  18604. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18605. var N = frames.normals[i];
  18606. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  18607. for (j = 0; j <= radialSegments; j++) {
  18608. var v = j / radialSegments * Math.PI * 2;
  18609. var sin = Math.sin(v);
  18610. var cos = -Math.cos(v); // normal
  18611. normal.x = cos * N.x + sin * B.x;
  18612. normal.y = cos * N.y + sin * B.y;
  18613. normal.z = cos * N.z + sin * B.z;
  18614. normal.normalize();
  18615. normals.push(normal.x, normal.y, normal.z); // vertex
  18616. vertex.x = P.x + radius * normal.x;
  18617. vertex.y = P.y + radius * normal.y;
  18618. vertex.z = P.z + radius * normal.z;
  18619. vertices.push(vertex.x, vertex.y, vertex.z);
  18620. }
  18621. }
  18622. function generateIndices() {
  18623. for (j = 1; j <= tubularSegments; j++) {
  18624. for (i = 1; i <= radialSegments; i++) {
  18625. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18626. var b = (radialSegments + 1) * j + (i - 1);
  18627. var c = (radialSegments + 1) * j + i;
  18628. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18629. indices.push(a, b, d);
  18630. indices.push(b, c, d);
  18631. }
  18632. }
  18633. }
  18634. function generateUVs() {
  18635. for (i = 0; i <= tubularSegments; i++) {
  18636. for (j = 0; j <= radialSegments; j++) {
  18637. uv.x = i / tubularSegments;
  18638. uv.y = j / radialSegments;
  18639. uvs.push(uv.x, uv.y);
  18640. }
  18641. }
  18642. }
  18643. }
  18644. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18645. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18646. TubeBufferGeometry.prototype.toJSON = function () {
  18647. var data = BufferGeometry.prototype.toJSON.call(this);
  18648. data.path = this.parameters.path.toJSON();
  18649. return data;
  18650. };
  18651. /**
  18652. * @author oosmoxiecode
  18653. * @author Mugen87 / https://github.com/Mugen87
  18654. *
  18655. * based on http://www.blackpawn.com/texts/pqtorus/
  18656. */
  18657. // TorusKnotGeometry
  18658. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  18659. Geometry.call(this);
  18660. this.type = 'TorusKnotGeometry';
  18661. this.parameters = {
  18662. radius: radius,
  18663. tube: tube,
  18664. tubularSegments: tubularSegments,
  18665. radialSegments: radialSegments,
  18666. p: p,
  18667. q: q
  18668. };
  18669. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  18670. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  18671. this.mergeVertices();
  18672. }
  18673. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  18674. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  18675. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  18676. BufferGeometry.call(this);
  18677. this.type = 'TorusKnotBufferGeometry';
  18678. this.parameters = {
  18679. radius: radius,
  18680. tube: tube,
  18681. tubularSegments: tubularSegments,
  18682. radialSegments: radialSegments,
  18683. p: p,
  18684. q: q
  18685. };
  18686. radius = radius || 1;
  18687. tube = tube || 0.4;
  18688. tubularSegments = Math.floor(tubularSegments) || 64;
  18689. radialSegments = Math.floor(radialSegments) || 8;
  18690. p = p || 2;
  18691. q = q || 3; // buffers
  18692. var indices = [];
  18693. var vertices = [];
  18694. var normals = [];
  18695. var uvs = []; // helper variables
  18696. var i, j;
  18697. var vertex = new Vector3();
  18698. var normal = new Vector3();
  18699. var P1 = new Vector3();
  18700. var P2 = new Vector3();
  18701. var B = new Vector3();
  18702. var T = new Vector3();
  18703. var N = new Vector3(); // generate vertices, normals and uvs
  18704. for (i = 0; i <= tubularSegments; ++i) {
  18705. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18706. 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.
  18707. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18708. calculatePositionOnCurve(u, p, q, radius, P1);
  18709. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18710. T.subVectors(P2, P1);
  18711. N.addVectors(P2, P1);
  18712. B.crossVectors(T, N);
  18713. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18714. B.normalize();
  18715. N.normalize();
  18716. for (j = 0; j <= radialSegments; ++j) {
  18717. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18718. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18719. var v = j / radialSegments * Math.PI * 2;
  18720. var cx = -tube * Math.cos(v);
  18721. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  18722. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18723. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18724. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18725. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18726. 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)
  18727. normal.subVectors(vertex, P1).normalize();
  18728. normals.push(normal.x, normal.y, normal.z); // uv
  18729. uvs.push(i / tubularSegments);
  18730. uvs.push(j / radialSegments);
  18731. }
  18732. } // generate indices
  18733. for (j = 1; j <= tubularSegments; j++) {
  18734. for (i = 1; i <= radialSegments; i++) {
  18735. // indices
  18736. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18737. var b = (radialSegments + 1) * j + (i - 1);
  18738. var c = (radialSegments + 1) * j + i;
  18739. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18740. indices.push(a, b, d);
  18741. indices.push(b, c, d);
  18742. }
  18743. } // build geometry
  18744. this.setIndex(indices);
  18745. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18746. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18747. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18748. function calculatePositionOnCurve(u, p, q, radius, position) {
  18749. var cu = Math.cos(u);
  18750. var su = Math.sin(u);
  18751. var quOverP = q / p * u;
  18752. var cs = Math.cos(quOverP);
  18753. position.x = radius * (2 + cs) * 0.5 * cu;
  18754. position.y = radius * (2 + cs) * su * 0.5;
  18755. position.z = radius * Math.sin(quOverP) * 0.5;
  18756. }
  18757. }
  18758. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18759. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  18760. /**
  18761. * @author oosmoxiecode
  18762. * @author mrdoob / http://mrdoob.com/
  18763. * @author Mugen87 / https://github.com/Mugen87
  18764. */
  18765. // TorusGeometry
  18766. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18767. Geometry.call(this);
  18768. this.type = 'TorusGeometry';
  18769. this.parameters = {
  18770. radius: radius,
  18771. tube: tube,
  18772. radialSegments: radialSegments,
  18773. tubularSegments: tubularSegments,
  18774. arc: arc
  18775. };
  18776. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  18777. this.mergeVertices();
  18778. }
  18779. TorusGeometry.prototype = Object.create(Geometry.prototype);
  18780. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  18781. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18782. BufferGeometry.call(this);
  18783. this.type = 'TorusBufferGeometry';
  18784. this.parameters = {
  18785. radius: radius,
  18786. tube: tube,
  18787. radialSegments: radialSegments,
  18788. tubularSegments: tubularSegments,
  18789. arc: arc
  18790. };
  18791. radius = radius || 1;
  18792. tube = tube || 0.4;
  18793. radialSegments = Math.floor(radialSegments) || 8;
  18794. tubularSegments = Math.floor(tubularSegments) || 6;
  18795. arc = arc || Math.PI * 2; // buffers
  18796. var indices = [];
  18797. var vertices = [];
  18798. var normals = [];
  18799. var uvs = []; // helper variables
  18800. var center = new Vector3();
  18801. var vertex = new Vector3();
  18802. var normal = new Vector3();
  18803. var j, i; // generate vertices, normals and uvs
  18804. for (j = 0; j <= radialSegments; j++) {
  18805. for (i = 0; i <= tubularSegments; i++) {
  18806. var u = i / tubularSegments * arc;
  18807. var v = j / radialSegments * Math.PI * 2; // vertex
  18808. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18809. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18810. vertex.z = tube * Math.sin(v);
  18811. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18812. center.x = radius * Math.cos(u);
  18813. center.y = radius * Math.sin(u);
  18814. normal.subVectors(vertex, center).normalize();
  18815. normals.push(normal.x, normal.y, normal.z); // uv
  18816. uvs.push(i / tubularSegments);
  18817. uvs.push(j / radialSegments);
  18818. }
  18819. } // generate indices
  18820. for (j = 1; j <= radialSegments; j++) {
  18821. for (i = 1; i <= tubularSegments; i++) {
  18822. // indices
  18823. var a = (tubularSegments + 1) * j + i - 1;
  18824. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  18825. var c = (tubularSegments + 1) * (j - 1) + i;
  18826. var d = (tubularSegments + 1) * j + i; // faces
  18827. indices.push(a, b, d);
  18828. indices.push(b, c, d);
  18829. }
  18830. } // build geometry
  18831. this.setIndex(indices);
  18832. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18833. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18834. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18835. }
  18836. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18837. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  18838. /**
  18839. * @author Mugen87 / https://github.com/Mugen87
  18840. * Port from https://github.com/mapbox/earcut (v2.1.5)
  18841. */
  18842. var Earcut = {
  18843. triangulate: function (data, holeIndices, dim) {
  18844. dim = dim || 2;
  18845. var hasHoles = holeIndices && holeIndices.length,
  18846. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  18847. outerNode = linkedList(data, 0, outerLen, dim, true),
  18848. triangles = [];
  18849. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18850. var minX, minY, maxX, maxY, x, y, invSize;
  18851. 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
  18852. if (data.length > 80 * dim) {
  18853. minX = maxX = data[0];
  18854. minY = maxY = data[1];
  18855. for (var i = dim; i < outerLen; i += dim) {
  18856. x = data[i];
  18857. y = data[i + 1];
  18858. if (x < minX) minX = x;
  18859. if (y < minY) minY = y;
  18860. if (x > maxX) maxX = x;
  18861. if (y > maxY) maxY = y;
  18862. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18863. invSize = Math.max(maxX - minX, maxY - minY);
  18864. invSize = invSize !== 0 ? 1 / invSize : 0;
  18865. }
  18866. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18867. return triangles;
  18868. }
  18869. }; // create a circular doubly linked list from polygon points in the specified winding order
  18870. function linkedList(data, start, end, dim, clockwise) {
  18871. var i, last;
  18872. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18873. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18874. } else {
  18875. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18876. }
  18877. if (last && equals(last, last.next)) {
  18878. removeNode(last);
  18879. last = last.next;
  18880. }
  18881. return last;
  18882. } // eliminate colinear or duplicate points
  18883. function filterPoints(start, end) {
  18884. if (!start) return start;
  18885. if (!end) end = start;
  18886. var p = start,
  18887. again;
  18888. do {
  18889. again = false;
  18890. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18891. removeNode(p);
  18892. p = end = p.prev;
  18893. if (p === p.next) break;
  18894. again = true;
  18895. } else {
  18896. p = p.next;
  18897. }
  18898. } while (again || p !== end);
  18899. return end;
  18900. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18901. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18902. if (!ear) return; // interlink polygon nodes in z-order
  18903. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18904. var stop = ear,
  18905. prev,
  18906. next; // iterate through ears, slicing them one by one
  18907. while (ear.prev !== ear.next) {
  18908. prev = ear.prev;
  18909. next = ear.next;
  18910. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18911. // cut off the triangle
  18912. triangles.push(prev.i / dim);
  18913. triangles.push(ear.i / dim);
  18914. triangles.push(next.i / dim);
  18915. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18916. ear = next.next;
  18917. stop = next.next;
  18918. continue;
  18919. }
  18920. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18921. if (ear === stop) {
  18922. // try filtering points and slicing again
  18923. if (!pass) {
  18924. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18925. } else if (pass === 1) {
  18926. ear = cureLocalIntersections(ear, triangles, dim);
  18927. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18928. } else if (pass === 2) {
  18929. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18930. }
  18931. break;
  18932. }
  18933. }
  18934. } // check whether a polygon node forms a valid ear with adjacent nodes
  18935. function isEar(ear) {
  18936. var a = ear.prev,
  18937. b = ear,
  18938. c = ear.next;
  18939. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18940. // now make sure we don't have other points inside the potential ear
  18941. var p = ear.next.next;
  18942. while (p !== ear.prev) {
  18943. 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;
  18944. p = p.next;
  18945. }
  18946. return true;
  18947. }
  18948. function isEarHashed(ear, minX, minY, invSize) {
  18949. var a = ear.prev,
  18950. b = ear,
  18951. c = ear.next;
  18952. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18953. // triangle bbox; min & max are calculated like this for speed
  18954. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18955. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18956. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18957. 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;
  18958. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18959. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18960. var p = ear.prevZ,
  18961. n = ear.nextZ; // look for points inside the triangle in both directions
  18962. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18963. 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;
  18964. p = p.prevZ;
  18965. 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;
  18966. n = n.nextZ;
  18967. } // look for remaining points in decreasing z-order
  18968. while (p && p.z >= minZ) {
  18969. 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;
  18970. p = p.prevZ;
  18971. } // look for remaining points in increasing z-order
  18972. while (n && n.z <= maxZ) {
  18973. 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;
  18974. n = n.nextZ;
  18975. }
  18976. return true;
  18977. } // go through all polygon nodes and cure small local self-intersections
  18978. function cureLocalIntersections(start, triangles, dim) {
  18979. var p = start;
  18980. do {
  18981. var a = p.prev,
  18982. b = p.next.next;
  18983. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18984. triangles.push(a.i / dim);
  18985. triangles.push(p.i / dim);
  18986. triangles.push(b.i / dim); // remove two nodes involved
  18987. removeNode(p);
  18988. removeNode(p.next);
  18989. p = start = b;
  18990. }
  18991. p = p.next;
  18992. } while (p !== start);
  18993. return p;
  18994. } // try splitting polygon into two and triangulate them independently
  18995. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18996. // look for a valid diagonal that divides the polygon into two
  18997. var a = start;
  18998. do {
  18999. var b = a.next.next;
  19000. while (b !== a.prev) {
  19001. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19002. // split the polygon in two by the diagonal
  19003. var c = splitPolygon(a, b); // filter colinear points around the cuts
  19004. a = filterPoints(a, a.next);
  19005. c = filterPoints(c, c.next); // run earcut on each half
  19006. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19007. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19008. return;
  19009. }
  19010. b = b.next;
  19011. }
  19012. a = a.next;
  19013. } while (a !== start);
  19014. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19015. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19016. var queue = [],
  19017. i,
  19018. len,
  19019. start,
  19020. end,
  19021. list;
  19022. for (i = 0, len = holeIndices.length; i < len; i++) {
  19023. start = holeIndices[i] * dim;
  19024. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19025. list = linkedList(data, start, end, dim, false);
  19026. if (list === list.next) list.steiner = true;
  19027. queue.push(getLeftmost(list));
  19028. }
  19029. queue.sort(compareX); // process holes from left to right
  19030. for (i = 0; i < queue.length; i++) {
  19031. eliminateHole(queue[i], outerNode);
  19032. outerNode = filterPoints(outerNode, outerNode.next);
  19033. }
  19034. return outerNode;
  19035. }
  19036. function compareX(a, b) {
  19037. return a.x - b.x;
  19038. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19039. function eliminateHole(hole, outerNode) {
  19040. outerNode = findHoleBridge(hole, outerNode);
  19041. if (outerNode) {
  19042. var b = splitPolygon(outerNode, hole);
  19043. filterPoints(b, b.next);
  19044. }
  19045. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19046. function findHoleBridge(hole, outerNode) {
  19047. var p = outerNode,
  19048. hx = hole.x,
  19049. hy = hole.y,
  19050. qx = -Infinity,
  19051. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19052. // segment's endpoint with lesser x will be potential connection point
  19053. do {
  19054. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19055. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19056. if (x <= hx && x > qx) {
  19057. qx = x;
  19058. if (x === hx) {
  19059. if (hy === p.y) return p;
  19060. if (hy === p.next.y) return p.next;
  19061. }
  19062. m = p.x < p.next.x ? p : p.next;
  19063. }
  19064. }
  19065. p = p.next;
  19066. } while (p !== outerNode);
  19067. if (!m) return null;
  19068. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  19069. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19070. // if there are no points found, we have a valid connection;
  19071. // otherwise choose the point of the minimum angle with the ray as connection point
  19072. var stop = m,
  19073. mx = m.x,
  19074. my = m.y,
  19075. tanMin = Infinity,
  19076. tan;
  19077. p = m.next;
  19078. while (p !== stop) {
  19079. 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)) {
  19080. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19081. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  19082. m = p;
  19083. tanMin = tan;
  19084. }
  19085. }
  19086. p = p.next;
  19087. }
  19088. return m;
  19089. } // interlink polygon nodes in z-order
  19090. function indexCurve(start, minX, minY, invSize) {
  19091. var p = start;
  19092. do {
  19093. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19094. p.prevZ = p.prev;
  19095. p.nextZ = p.next;
  19096. p = p.next;
  19097. } while (p !== start);
  19098. p.prevZ.nextZ = null;
  19099. p.prevZ = null;
  19100. sortLinked(p);
  19101. } // Simon Tatham's linked list merge sort algorithm
  19102. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19103. function sortLinked(list) {
  19104. var i,
  19105. p,
  19106. q,
  19107. e,
  19108. tail,
  19109. numMerges,
  19110. pSize,
  19111. qSize,
  19112. inSize = 1;
  19113. do {
  19114. p = list;
  19115. list = null;
  19116. tail = null;
  19117. numMerges = 0;
  19118. while (p) {
  19119. numMerges++;
  19120. q = p;
  19121. pSize = 0;
  19122. for (i = 0; i < inSize; i++) {
  19123. pSize++;
  19124. q = q.nextZ;
  19125. if (!q) break;
  19126. }
  19127. qSize = inSize;
  19128. while (pSize > 0 || qSize > 0 && q) {
  19129. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19130. e = p;
  19131. p = p.nextZ;
  19132. pSize--;
  19133. } else {
  19134. e = q;
  19135. q = q.nextZ;
  19136. qSize--;
  19137. }
  19138. if (tail) tail.nextZ = e;else list = e;
  19139. e.prevZ = tail;
  19140. tail = e;
  19141. }
  19142. p = q;
  19143. }
  19144. tail.nextZ = null;
  19145. inSize *= 2;
  19146. } while (numMerges > 1);
  19147. return list;
  19148. } // z-order of a point given coords and inverse of the longer side of data bbox
  19149. function zOrder(x, y, minX, minY, invSize) {
  19150. // coords are transformed into non-negative 15-bit integer range
  19151. x = 32767 * (x - minX) * invSize;
  19152. y = 32767 * (y - minY) * invSize;
  19153. x = (x | x << 8) & 0x00FF00FF;
  19154. x = (x | x << 4) & 0x0F0F0F0F;
  19155. x = (x | x << 2) & 0x33333333;
  19156. x = (x | x << 1) & 0x55555555;
  19157. y = (y | y << 8) & 0x00FF00FF;
  19158. y = (y | y << 4) & 0x0F0F0F0F;
  19159. y = (y | y << 2) & 0x33333333;
  19160. y = (y | y << 1) & 0x55555555;
  19161. return x | y << 1;
  19162. } // find the leftmost node of a polygon ring
  19163. function getLeftmost(start) {
  19164. var p = start,
  19165. leftmost = start;
  19166. do {
  19167. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19168. p = p.next;
  19169. } while (p !== start);
  19170. return leftmost;
  19171. } // check if a point lies within a convex triangle
  19172. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19173. 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;
  19174. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19175. function isValidDiagonal(a, b) {
  19176. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  19177. } // signed area of a triangle
  19178. function area(p, q, r) {
  19179. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19180. } // check if two points are equal
  19181. function equals(p1, p2) {
  19182. return p1.x === p2.x && p1.y === p2.y;
  19183. } // check if two segments intersect
  19184. function intersects(p1, q1, p2, q2) {
  19185. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  19186. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  19187. } // check if a polygon diagonal intersects any polygon segments
  19188. function intersectsPolygon(a, b) {
  19189. var p = a;
  19190. do {
  19191. 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;
  19192. p = p.next;
  19193. } while (p !== a);
  19194. return false;
  19195. } // check if a polygon diagonal is locally inside the polygon
  19196. function locallyInside(a, b) {
  19197. 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;
  19198. } // check if the middle point of a polygon diagonal is inside the polygon
  19199. function middleInside(a, b) {
  19200. var p = a,
  19201. inside = false,
  19202. px = (a.x + b.x) / 2,
  19203. py = (a.y + b.y) / 2;
  19204. do {
  19205. 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;
  19206. p = p.next;
  19207. } while (p !== a);
  19208. return inside;
  19209. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19210. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19211. function splitPolygon(a, b) {
  19212. var a2 = new Node(a.i, a.x, a.y),
  19213. b2 = new Node(b.i, b.x, b.y),
  19214. an = a.next,
  19215. bp = b.prev;
  19216. a.next = b;
  19217. b.prev = a;
  19218. a2.next = an;
  19219. an.prev = a2;
  19220. b2.next = a2;
  19221. a2.prev = b2;
  19222. bp.next = b2;
  19223. b2.prev = bp;
  19224. return b2;
  19225. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19226. function insertNode(i, x, y, last) {
  19227. var p = new Node(i, x, y);
  19228. if (!last) {
  19229. p.prev = p;
  19230. p.next = p;
  19231. } else {
  19232. p.next = last.next;
  19233. p.prev = last;
  19234. last.next.prev = p;
  19235. last.next = p;
  19236. }
  19237. return p;
  19238. }
  19239. function removeNode(p) {
  19240. p.next.prev = p.prev;
  19241. p.prev.next = p.next;
  19242. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19243. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19244. }
  19245. function Node(i, x, y) {
  19246. // vertex index in coordinates array
  19247. this.i = i; // vertex coordinates
  19248. this.x = x;
  19249. this.y = y; // previous and next vertex nodes in a polygon ring
  19250. this.prev = null;
  19251. this.next = null; // z-order curve value
  19252. this.z = null; // previous and next nodes in z-order
  19253. this.prevZ = null;
  19254. this.nextZ = null; // indicates whether this is a steiner point
  19255. this.steiner = false;
  19256. }
  19257. function signedArea(data, start, end, dim) {
  19258. var sum = 0;
  19259. for (var i = start, j = end - dim; i < end; i += dim) {
  19260. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19261. j = i;
  19262. }
  19263. return sum;
  19264. }
  19265. /**
  19266. * @author zz85 / http://www.lab4games.net/zz85/blog
  19267. */
  19268. var ShapeUtils = {
  19269. // calculate area of the contour polygon
  19270. area: function (contour) {
  19271. var n = contour.length;
  19272. var a = 0.0;
  19273. for (var p = n - 1, q = 0; q < n; p = q++) {
  19274. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19275. }
  19276. return a * 0.5;
  19277. },
  19278. isClockWise: function (pts) {
  19279. return ShapeUtils.area(pts) < 0;
  19280. },
  19281. triangulateShape: function (contour, holes) {
  19282. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19283. var holeIndices = []; // array of hole indices
  19284. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19285. removeDupEndPts(contour);
  19286. addContour(vertices, contour); //
  19287. var holeIndex = contour.length;
  19288. holes.forEach(removeDupEndPts);
  19289. for (var i = 0; i < holes.length; i++) {
  19290. holeIndices.push(holeIndex);
  19291. holeIndex += holes[i].length;
  19292. addContour(vertices, holes[i]);
  19293. } //
  19294. var triangles = Earcut.triangulate(vertices, holeIndices); //
  19295. for (var i = 0; i < triangles.length; i += 3) {
  19296. faces.push(triangles.slice(i, i + 3));
  19297. }
  19298. return faces;
  19299. }
  19300. };
  19301. exports.ShapeUtils = ShapeUtils;
  19302. function removeDupEndPts(points) {
  19303. var l = points.length;
  19304. if (l > 2 && points[l - 1].equals(points[0])) {
  19305. points.pop();
  19306. }
  19307. }
  19308. function addContour(vertices, contour) {
  19309. for (var i = 0; i < contour.length; i++) {
  19310. vertices.push(contour[i].x);
  19311. vertices.push(contour[i].y);
  19312. }
  19313. }
  19314. /**
  19315. * @author zz85 / http://www.lab4games.net/zz85/blog
  19316. *
  19317. * Creates extruded geometry from a path shape.
  19318. *
  19319. * parameters = {
  19320. *
  19321. * curveSegments: <int>, // number of points on the curves
  19322. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19323. * depth: <float>, // Depth to extrude the shape
  19324. *
  19325. * bevelEnabled: <bool>, // turn on bevel
  19326. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19327. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19328. * bevelOffset: <float>, // how far from shape outline does bevel start
  19329. * bevelSegments: <int>, // number of bevel layers
  19330. *
  19331. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19332. *
  19333. * UVGenerator: <Object> // object that provides UV generator functions
  19334. *
  19335. * }
  19336. */
  19337. // ExtrudeGeometry
  19338. function ExtrudeGeometry(shapes, options) {
  19339. Geometry.call(this);
  19340. this.type = 'ExtrudeGeometry';
  19341. this.parameters = {
  19342. shapes: shapes,
  19343. options: options
  19344. };
  19345. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19346. this.mergeVertices();
  19347. }
  19348. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  19349. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19350. ExtrudeGeometry.prototype.toJSON = function () {
  19351. var data = Geometry.prototype.toJSON.call(this);
  19352. var shapes = this.parameters.shapes;
  19353. var options = this.parameters.options;
  19354. return toJSON(shapes, options, data);
  19355. }; // ExtrudeBufferGeometry
  19356. function ExtrudeBufferGeometry(shapes, options) {
  19357. BufferGeometry.call(this);
  19358. this.type = 'ExtrudeBufferGeometry';
  19359. this.parameters = {
  19360. shapes: shapes,
  19361. options: options
  19362. };
  19363. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19364. var scope = this;
  19365. var verticesArray = [];
  19366. var uvArray = [];
  19367. for (var i = 0, l = shapes.length; i < l; i++) {
  19368. var shape = shapes[i];
  19369. addShape(shape);
  19370. } // build geometry
  19371. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19372. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19373. this.computeVertexNormals(); // functions
  19374. function addShape(shape) {
  19375. var placeholder = []; // options
  19376. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19377. var steps = options.steps !== undefined ? options.steps : 1;
  19378. var depth = options.depth !== undefined ? options.depth : 100;
  19379. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19380. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19381. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19382. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19383. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19384. var extrudePath = options.extrudePath;
  19385. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19386. if (options.amount !== undefined) {
  19387. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19388. depth = options.amount;
  19389. } //
  19390. var extrudePts,
  19391. extrudeByPath = false;
  19392. var splineTube, binormal, normal, position2;
  19393. if (extrudePath) {
  19394. extrudePts = extrudePath.getSpacedPoints(steps);
  19395. extrudeByPath = true;
  19396. bevelEnabled = false; // bevels not supported for path extrusion
  19397. // SETUP TNB variables
  19398. // TODO1 - have a .isClosed in spline?
  19399. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19400. binormal = new Vector3();
  19401. normal = new Vector3();
  19402. position2 = new Vector3();
  19403. } // Safeguards if bevels are not enabled
  19404. if (!bevelEnabled) {
  19405. bevelSegments = 0;
  19406. bevelThickness = 0;
  19407. bevelSize = 0;
  19408. bevelOffset = 0;
  19409. } // Variables initialization
  19410. var ahole, h, hl; // looping of holes
  19411. var shapePoints = shape.extractPoints(curveSegments);
  19412. var vertices = shapePoints.shape;
  19413. var holes = shapePoints.holes;
  19414. var reverse = !ShapeUtils.isClockWise(vertices);
  19415. if (reverse) {
  19416. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19417. for (h = 0, hl = holes.length; h < hl; h++) {
  19418. ahole = holes[h];
  19419. if (ShapeUtils.isClockWise(ahole)) {
  19420. holes[h] = ahole.reverse();
  19421. }
  19422. }
  19423. }
  19424. var faces = ShapeUtils.triangulateShape(vertices, holes);
  19425. /* Vertices */
  19426. var contour = vertices; // vertices has all points but contour has only points of circumference
  19427. for (h = 0, hl = holes.length; h < hl; h++) {
  19428. ahole = holes[h];
  19429. vertices = vertices.concat(ahole);
  19430. }
  19431. function scalePt2(pt, vec, size) {
  19432. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  19433. return vec.clone().multiplyScalar(size).add(pt);
  19434. }
  19435. var b,
  19436. bs,
  19437. t,
  19438. z,
  19439. vert,
  19440. vlen = vertices.length,
  19441. face,
  19442. flen = faces.length; // Find directions for point movement
  19443. function getBevelVec(inPt, inPrev, inNext) {
  19444. // computes for inPt the corresponding point inPt' on a new contour
  19445. // shifted by 1 unit (length of normalized vector) to the left
  19446. // if we walk along contour clockwise, this new contour is outside the old one
  19447. //
  19448. // inPt' is the intersection of the two lines parallel to the two
  19449. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19450. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19451. // good reading for geometry algorithms (here: line-line intersection)
  19452. // http://geomalgorithms.com/a05-_intersect-1.html
  19453. var v_prev_x = inPt.x - inPrev.x,
  19454. v_prev_y = inPt.y - inPrev.y;
  19455. var v_next_x = inNext.x - inPt.x,
  19456. v_next_y = inNext.y - inPt.y;
  19457. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19458. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19459. if (Math.abs(collinear0) > Number.EPSILON) {
  19460. // not collinear
  19461. // length of vectors for normalizing
  19462. var v_prev_len = Math.sqrt(v_prev_lensq);
  19463. 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
  19464. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19465. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19466. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19467. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19468. 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
  19469. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19470. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19471. // but prevent crazy spikes
  19472. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19473. if (v_trans_lensq <= 2) {
  19474. return new Vector2(v_trans_x, v_trans_y);
  19475. } else {
  19476. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19477. }
  19478. } else {
  19479. // handle special case of collinear edges
  19480. var direction_eq = false; // assumes: opposite
  19481. if (v_prev_x > Number.EPSILON) {
  19482. if (v_next_x > Number.EPSILON) {
  19483. direction_eq = true;
  19484. }
  19485. } else {
  19486. if (v_prev_x < -Number.EPSILON) {
  19487. if (v_next_x < -Number.EPSILON) {
  19488. direction_eq = true;
  19489. }
  19490. } else {
  19491. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19492. direction_eq = true;
  19493. }
  19494. }
  19495. }
  19496. if (direction_eq) {
  19497. // console.log("Warning: lines are a straight sequence");
  19498. v_trans_x = -v_prev_y;
  19499. v_trans_y = v_prev_x;
  19500. shrink_by = Math.sqrt(v_prev_lensq);
  19501. } else {
  19502. // console.log("Warning: lines are a straight spike");
  19503. v_trans_x = v_prev_x;
  19504. v_trans_y = v_prev_y;
  19505. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19506. }
  19507. }
  19508. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19509. }
  19510. var contourMovements = [];
  19511. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19512. if (j === il) j = 0;
  19513. if (k === il) k = 0; // (j)---(i)---(k)
  19514. // console.log('i,j,k', i, j , k)
  19515. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19516. }
  19517. var holesMovements = [],
  19518. oneHoleMovements,
  19519. verticesMovements = contourMovements.concat();
  19520. for (h = 0, hl = holes.length; h < hl; h++) {
  19521. ahole = holes[h];
  19522. oneHoleMovements = [];
  19523. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19524. if (j === il) j = 0;
  19525. if (k === il) k = 0; // (j)---(i)---(k)
  19526. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19527. }
  19528. holesMovements.push(oneHoleMovements);
  19529. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19530. } // Loop bevelSegments, 1 for the front, 1 for the back
  19531. for (b = 0; b < bevelSegments; b++) {
  19532. //for ( b = bevelSegments; b > 0; b -- ) {
  19533. t = b / bevelSegments;
  19534. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19535. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19536. for (i = 0, il = contour.length; i < il; i++) {
  19537. vert = scalePt2(contour[i], contourMovements[i], bs);
  19538. v(vert.x, vert.y, -z);
  19539. } // expand holes
  19540. for (h = 0, hl = holes.length; h < hl; h++) {
  19541. ahole = holes[h];
  19542. oneHoleMovements = holesMovements[h];
  19543. for (i = 0, il = ahole.length; i < il; i++) {
  19544. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19545. v(vert.x, vert.y, -z);
  19546. }
  19547. }
  19548. }
  19549. bs = bevelSize + bevelOffset; // Back facing vertices
  19550. for (i = 0; i < vlen; i++) {
  19551. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19552. if (!extrudeByPath) {
  19553. v(vert.x, vert.y, 0);
  19554. } else {
  19555. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19556. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19557. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19558. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19559. v(position2.x, position2.y, position2.z);
  19560. }
  19561. } // Add stepped vertices...
  19562. // Including front facing vertices
  19563. var s;
  19564. for (s = 1; s <= steps; s++) {
  19565. for (i = 0; i < vlen; i++) {
  19566. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19567. if (!extrudeByPath) {
  19568. v(vert.x, vert.y, depth / steps * s);
  19569. } else {
  19570. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19571. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19572. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19573. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19574. v(position2.x, position2.y, position2.z);
  19575. }
  19576. }
  19577. } // Add bevel segments planes
  19578. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19579. for (b = bevelSegments - 1; b >= 0; b--) {
  19580. t = b / bevelSegments;
  19581. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19582. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19583. for (i = 0, il = contour.length; i < il; i++) {
  19584. vert = scalePt2(contour[i], contourMovements[i], bs);
  19585. v(vert.x, vert.y, depth + z);
  19586. } // expand holes
  19587. for (h = 0, hl = holes.length; h < hl; h++) {
  19588. ahole = holes[h];
  19589. oneHoleMovements = holesMovements[h];
  19590. for (i = 0, il = ahole.length; i < il; i++) {
  19591. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19592. if (!extrudeByPath) {
  19593. v(vert.x, vert.y, depth + z);
  19594. } else {
  19595. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19596. }
  19597. }
  19598. }
  19599. }
  19600. /* Faces */
  19601. // Top and bottom faces
  19602. buildLidFaces(); // Sides faces
  19603. buildSideFaces(); ///// Internal functions
  19604. function buildLidFaces() {
  19605. var start = verticesArray.length / 3;
  19606. if (bevelEnabled) {
  19607. var layer = 0; // steps + 1
  19608. var offset = vlen * layer; // Bottom faces
  19609. for (i = 0; i < flen; i++) {
  19610. face = faces[i];
  19611. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19612. }
  19613. layer = steps + bevelSegments * 2;
  19614. offset = vlen * layer; // Top faces
  19615. for (i = 0; i < flen; i++) {
  19616. face = faces[i];
  19617. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19618. }
  19619. } else {
  19620. // Bottom faces
  19621. for (i = 0; i < flen; i++) {
  19622. face = faces[i];
  19623. f3(face[2], face[1], face[0]);
  19624. } // Top faces
  19625. for (i = 0; i < flen; i++) {
  19626. face = faces[i];
  19627. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19628. }
  19629. }
  19630. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19631. } // Create faces for the z-sides of the shape
  19632. function buildSideFaces() {
  19633. var start = verticesArray.length / 3;
  19634. var layeroffset = 0;
  19635. sidewalls(contour, layeroffset);
  19636. layeroffset += contour.length;
  19637. for (h = 0, hl = holes.length; h < hl; h++) {
  19638. ahole = holes[h];
  19639. sidewalls(ahole, layeroffset); //, true
  19640. layeroffset += ahole.length;
  19641. }
  19642. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19643. }
  19644. function sidewalls(contour, layeroffset) {
  19645. var j, k;
  19646. i = contour.length;
  19647. while (--i >= 0) {
  19648. j = i;
  19649. k = i - 1;
  19650. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19651. var s = 0,
  19652. sl = steps + bevelSegments * 2;
  19653. for (s = 0; s < sl; s++) {
  19654. var slen1 = vlen * s;
  19655. var slen2 = vlen * (s + 1);
  19656. var a = layeroffset + j + slen1,
  19657. b = layeroffset + k + slen1,
  19658. c = layeroffset + k + slen2,
  19659. d = layeroffset + j + slen2;
  19660. f4(a, b, c, d);
  19661. }
  19662. }
  19663. }
  19664. function v(x, y, z) {
  19665. placeholder.push(x);
  19666. placeholder.push(y);
  19667. placeholder.push(z);
  19668. }
  19669. function f3(a, b, c) {
  19670. addVertex(a);
  19671. addVertex(b);
  19672. addVertex(c);
  19673. var nextIndex = verticesArray.length / 3;
  19674. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19675. addUV(uvs[0]);
  19676. addUV(uvs[1]);
  19677. addUV(uvs[2]);
  19678. }
  19679. function f4(a, b, c, d) {
  19680. addVertex(a);
  19681. addVertex(b);
  19682. addVertex(d);
  19683. addVertex(b);
  19684. addVertex(c);
  19685. addVertex(d);
  19686. var nextIndex = verticesArray.length / 3;
  19687. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19688. addUV(uvs[0]);
  19689. addUV(uvs[1]);
  19690. addUV(uvs[3]);
  19691. addUV(uvs[1]);
  19692. addUV(uvs[2]);
  19693. addUV(uvs[3]);
  19694. }
  19695. function addVertex(index) {
  19696. verticesArray.push(placeholder[index * 3 + 0]);
  19697. verticesArray.push(placeholder[index * 3 + 1]);
  19698. verticesArray.push(placeholder[index * 3 + 2]);
  19699. }
  19700. function addUV(vector2) {
  19701. uvArray.push(vector2.x);
  19702. uvArray.push(vector2.y);
  19703. }
  19704. }
  19705. }
  19706. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19707. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  19708. ExtrudeBufferGeometry.prototype.toJSON = function () {
  19709. var data = BufferGeometry.prototype.toJSON.call(this);
  19710. var shapes = this.parameters.shapes;
  19711. var options = this.parameters.options;
  19712. return toJSON(shapes, options, data);
  19713. }; //
  19714. var WorldUVGenerator = {
  19715. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19716. var a_x = vertices[indexA * 3];
  19717. var a_y = vertices[indexA * 3 + 1];
  19718. var b_x = vertices[indexB * 3];
  19719. var b_y = vertices[indexB * 3 + 1];
  19720. var c_x = vertices[indexC * 3];
  19721. var c_y = vertices[indexC * 3 + 1];
  19722. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19723. },
  19724. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19725. var a_x = vertices[indexA * 3];
  19726. var a_y = vertices[indexA * 3 + 1];
  19727. var a_z = vertices[indexA * 3 + 2];
  19728. var b_x = vertices[indexB * 3];
  19729. var b_y = vertices[indexB * 3 + 1];
  19730. var b_z = vertices[indexB * 3 + 2];
  19731. var c_x = vertices[indexC * 3];
  19732. var c_y = vertices[indexC * 3 + 1];
  19733. var c_z = vertices[indexC * 3 + 2];
  19734. var d_x = vertices[indexD * 3];
  19735. var d_y = vertices[indexD * 3 + 1];
  19736. var d_z = vertices[indexD * 3 + 2];
  19737. if (Math.abs(a_y - b_y) < 0.01) {
  19738. 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)];
  19739. } else {
  19740. 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)];
  19741. }
  19742. }
  19743. };
  19744. function toJSON(shapes, options, data) {
  19745. //
  19746. data.shapes = [];
  19747. if (Array.isArray(shapes)) {
  19748. for (var i = 0, l = shapes.length; i < l; i++) {
  19749. var shape = shapes[i];
  19750. data.shapes.push(shape.uuid);
  19751. }
  19752. } else {
  19753. data.shapes.push(shapes.uuid);
  19754. } //
  19755. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19756. return data;
  19757. }
  19758. /**
  19759. * @author zz85 / http://www.lab4games.net/zz85/blog
  19760. * @author alteredq / http://alteredqualia.com/
  19761. *
  19762. * Text = 3D Text
  19763. *
  19764. * parameters = {
  19765. * font: <THREE.Font>, // font
  19766. *
  19767. * size: <float>, // size of the text
  19768. * height: <float>, // thickness to extrude text
  19769. * curveSegments: <int>, // number of points on the curves
  19770. *
  19771. * bevelEnabled: <bool>, // turn on bevel
  19772. * bevelThickness: <float>, // how deep into text bevel goes
  19773. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19774. * bevelOffset: <float> // how far from text outline does bevel start
  19775. * }
  19776. */
  19777. // TextGeometry
  19778. function TextGeometry(text, parameters) {
  19779. Geometry.call(this);
  19780. this.type = 'TextGeometry';
  19781. this.parameters = {
  19782. text: text,
  19783. parameters: parameters
  19784. };
  19785. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19786. this.mergeVertices();
  19787. }
  19788. TextGeometry.prototype = Object.create(Geometry.prototype);
  19789. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  19790. function TextBufferGeometry(text, parameters) {
  19791. parameters = parameters || {};
  19792. var font = parameters.font;
  19793. if (!(font && font.isFont)) {
  19794. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19795. return new Geometry();
  19796. }
  19797. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19798. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19799. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19800. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19801. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19802. ExtrudeBufferGeometry.call(this, shapes, parameters);
  19803. this.type = 'TextBufferGeometry';
  19804. }
  19805. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  19806. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  19807. /**
  19808. * @author mrdoob / http://mrdoob.com/
  19809. * @author benaadams / https://twitter.com/ben_a_adams
  19810. * @author Mugen87 / https://github.com/Mugen87
  19811. */
  19812. // SphereGeometry
  19813. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19814. Geometry.call(this);
  19815. this.type = 'SphereGeometry';
  19816. this.parameters = {
  19817. radius: radius,
  19818. widthSegments: widthSegments,
  19819. heightSegments: heightSegments,
  19820. phiStart: phiStart,
  19821. phiLength: phiLength,
  19822. thetaStart: thetaStart,
  19823. thetaLength: thetaLength
  19824. };
  19825. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19826. this.mergeVertices();
  19827. }
  19828. SphereGeometry.prototype = Object.create(Geometry.prototype);
  19829. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  19830. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19831. BufferGeometry.call(this);
  19832. this.type = 'SphereBufferGeometry';
  19833. this.parameters = {
  19834. radius: radius,
  19835. widthSegments: widthSegments,
  19836. heightSegments: heightSegments,
  19837. phiStart: phiStart,
  19838. phiLength: phiLength,
  19839. thetaStart: thetaStart,
  19840. thetaLength: thetaLength
  19841. };
  19842. radius = radius || 1;
  19843. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  19844. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  19845. phiStart = phiStart !== undefined ? phiStart : 0;
  19846. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19847. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19848. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19849. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19850. var ix, iy;
  19851. var index = 0;
  19852. var grid = [];
  19853. var vertex = new Vector3();
  19854. var normal = new Vector3(); // buffers
  19855. var indices = [];
  19856. var vertices = [];
  19857. var normals = [];
  19858. var uvs = []; // generate vertices, normals and uvs
  19859. for (iy = 0; iy <= heightSegments; iy++) {
  19860. var verticesRow = [];
  19861. var v = iy / heightSegments; // special case for the poles
  19862. var uOffset = 0;
  19863. if (iy == 0 && thetaStart == 0) {
  19864. uOffset = 0.5 / widthSegments;
  19865. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19866. uOffset = -0.5 / widthSegments;
  19867. }
  19868. for (ix = 0; ix <= widthSegments; ix++) {
  19869. var u = ix / widthSegments; // vertex
  19870. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19871. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19872. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19873. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19874. normal.copy(vertex).normalize();
  19875. normals.push(normal.x, normal.y, normal.z); // uv
  19876. uvs.push(u + uOffset, 1 - v);
  19877. verticesRow.push(index++);
  19878. }
  19879. grid.push(verticesRow);
  19880. } // indices
  19881. for (iy = 0; iy < heightSegments; iy++) {
  19882. for (ix = 0; ix < widthSegments; ix++) {
  19883. var a = grid[iy][ix + 1];
  19884. var b = grid[iy][ix];
  19885. var c = grid[iy + 1][ix];
  19886. var d = grid[iy + 1][ix + 1];
  19887. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19888. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19889. }
  19890. } // build geometry
  19891. this.setIndex(indices);
  19892. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19893. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19894. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19895. }
  19896. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19897. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19898. /**
  19899. * @author Kaleb Murphy
  19900. * @author Mugen87 / https://github.com/Mugen87
  19901. */
  19902. // RingGeometry
  19903. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19904. Geometry.call(this);
  19905. this.type = 'RingGeometry';
  19906. this.parameters = {
  19907. innerRadius: innerRadius,
  19908. outerRadius: outerRadius,
  19909. thetaSegments: thetaSegments,
  19910. phiSegments: phiSegments,
  19911. thetaStart: thetaStart,
  19912. thetaLength: thetaLength
  19913. };
  19914. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19915. this.mergeVertices();
  19916. }
  19917. RingGeometry.prototype = Object.create(Geometry.prototype);
  19918. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19919. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19920. BufferGeometry.call(this);
  19921. this.type = 'RingBufferGeometry';
  19922. this.parameters = {
  19923. innerRadius: innerRadius,
  19924. outerRadius: outerRadius,
  19925. thetaSegments: thetaSegments,
  19926. phiSegments: phiSegments,
  19927. thetaStart: thetaStart,
  19928. thetaLength: thetaLength
  19929. };
  19930. innerRadius = innerRadius || 0.5;
  19931. outerRadius = outerRadius || 1;
  19932. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19933. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19934. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19935. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19936. var indices = [];
  19937. var vertices = [];
  19938. var normals = [];
  19939. var uvs = []; // some helper variables
  19940. var segment;
  19941. var radius = innerRadius;
  19942. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19943. var vertex = new Vector3();
  19944. var uv = new Vector2();
  19945. var j, i; // generate vertices, normals and uvs
  19946. for (j = 0; j <= phiSegments; j++) {
  19947. for (i = 0; i <= thetaSegments; i++) {
  19948. // values are generate from the inside of the ring to the outside
  19949. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19950. vertex.x = radius * Math.cos(segment);
  19951. vertex.y = radius * Math.sin(segment);
  19952. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19953. normals.push(0, 0, 1); // uv
  19954. uv.x = (vertex.x / outerRadius + 1) / 2;
  19955. uv.y = (vertex.y / outerRadius + 1) / 2;
  19956. uvs.push(uv.x, uv.y);
  19957. } // increase the radius for next row of vertices
  19958. radius += radiusStep;
  19959. } // indices
  19960. for (j = 0; j < phiSegments; j++) {
  19961. var thetaSegmentLevel = j * (thetaSegments + 1);
  19962. for (i = 0; i < thetaSegments; i++) {
  19963. segment = i + thetaSegmentLevel;
  19964. var a = segment;
  19965. var b = segment + thetaSegments + 1;
  19966. var c = segment + thetaSegments + 2;
  19967. var d = segment + 1; // faces
  19968. indices.push(a, b, d);
  19969. indices.push(b, c, d);
  19970. }
  19971. } // build geometry
  19972. this.setIndex(indices);
  19973. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19974. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19975. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19976. }
  19977. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19978. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19979. /**
  19980. * @author zz85 / https://github.com/zz85
  19981. * @author bhouston / http://clara.io
  19982. * @author Mugen87 / https://github.com/Mugen87
  19983. */
  19984. // LatheGeometry
  19985. function LatheGeometry(points, segments, phiStart, phiLength) {
  19986. Geometry.call(this);
  19987. this.type = 'LatheGeometry';
  19988. this.parameters = {
  19989. points: points,
  19990. segments: segments,
  19991. phiStart: phiStart,
  19992. phiLength: phiLength
  19993. };
  19994. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19995. this.mergeVertices();
  19996. }
  19997. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19998. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19999. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  20000. BufferGeometry.call(this);
  20001. this.type = 'LatheBufferGeometry';
  20002. this.parameters = {
  20003. points: points,
  20004. segments: segments,
  20005. phiStart: phiStart,
  20006. phiLength: phiLength
  20007. };
  20008. segments = Math.floor(segments) || 12;
  20009. phiStart = phiStart || 0;
  20010. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  20011. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  20012. var indices = [];
  20013. var vertices = [];
  20014. var uvs = []; // helper variables
  20015. var base;
  20016. var inverseSegments = 1.0 / segments;
  20017. var vertex = new Vector3();
  20018. var uv = new Vector2();
  20019. var i, j; // generate vertices and uvs
  20020. for (i = 0; i <= segments; i++) {
  20021. var phi = phiStart + i * inverseSegments * phiLength;
  20022. var sin = Math.sin(phi);
  20023. var cos = Math.cos(phi);
  20024. for (j = 0; j <= points.length - 1; j++) {
  20025. // vertex
  20026. vertex.x = points[j].x * sin;
  20027. vertex.y = points[j].y;
  20028. vertex.z = points[j].x * cos;
  20029. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20030. uv.x = i / segments;
  20031. uv.y = j / (points.length - 1);
  20032. uvs.push(uv.x, uv.y);
  20033. }
  20034. } // indices
  20035. for (i = 0; i < segments; i++) {
  20036. for (j = 0; j < points.length - 1; j++) {
  20037. base = j + i * points.length;
  20038. var a = base;
  20039. var b = base + points.length;
  20040. var c = base + points.length + 1;
  20041. var d = base + 1; // faces
  20042. indices.push(a, b, d);
  20043. indices.push(b, c, d);
  20044. }
  20045. } // build geometry
  20046. this.setIndex(indices);
  20047. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20048. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20049. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20050. // because the corresponding vertices are identical (but still have different UVs).
  20051. if (phiLength === Math.PI * 2) {
  20052. var normals = this.attributes.normal.array;
  20053. var n1 = new Vector3();
  20054. var n2 = new Vector3();
  20055. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  20056. base = segments * points.length * 3;
  20057. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  20058. // select the normal of the vertex in the first line
  20059. n1.x = normals[j + 0];
  20060. n1.y = normals[j + 1];
  20061. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20062. n2.x = normals[base + j + 0];
  20063. n2.y = normals[base + j + 1];
  20064. n2.z = normals[base + j + 2]; // average normals
  20065. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20066. normals[j + 0] = normals[base + j + 0] = n.x;
  20067. normals[j + 1] = normals[base + j + 1] = n.y;
  20068. normals[j + 2] = normals[base + j + 2] = n.z;
  20069. }
  20070. }
  20071. }
  20072. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20073. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20074. /**
  20075. * @author jonobr1 / http://jonobr1.com
  20076. * @author Mugen87 / https://github.com/Mugen87
  20077. */
  20078. // ShapeGeometry
  20079. function ShapeGeometry(shapes, curveSegments) {
  20080. Geometry.call(this);
  20081. this.type = 'ShapeGeometry';
  20082. if (typeof curveSegments === 'object') {
  20083. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  20084. curveSegments = curveSegments.curveSegments;
  20085. }
  20086. this.parameters = {
  20087. shapes: shapes,
  20088. curveSegments: curveSegments
  20089. };
  20090. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  20091. this.mergeVertices();
  20092. }
  20093. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  20094. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20095. ShapeGeometry.prototype.toJSON = function () {
  20096. var data = Geometry.prototype.toJSON.call(this);
  20097. var shapes = this.parameters.shapes;
  20098. return toJSON$1(shapes, data);
  20099. }; // ShapeBufferGeometry
  20100. function ShapeBufferGeometry(shapes, curveSegments) {
  20101. BufferGeometry.call(this);
  20102. this.type = 'ShapeBufferGeometry';
  20103. this.parameters = {
  20104. shapes: shapes,
  20105. curveSegments: curveSegments
  20106. };
  20107. curveSegments = curveSegments || 12; // buffers
  20108. var indices = [];
  20109. var vertices = [];
  20110. var normals = [];
  20111. var uvs = []; // helper variables
  20112. var groupStart = 0;
  20113. var groupCount = 0; // allow single and array values for "shapes" parameter
  20114. if (Array.isArray(shapes) === false) {
  20115. addShape(shapes);
  20116. } else {
  20117. for (var i = 0; i < shapes.length; i++) {
  20118. addShape(shapes[i]);
  20119. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20120. groupStart += groupCount;
  20121. groupCount = 0;
  20122. }
  20123. } // build geometry
  20124. this.setIndex(indices);
  20125. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20126. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20127. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20128. function addShape(shape) {
  20129. var i, l, shapeHole;
  20130. var indexOffset = vertices.length / 3;
  20131. var points = shape.extractPoints(curveSegments);
  20132. var shapeVertices = points.shape;
  20133. var shapeHoles = points.holes; // check direction of vertices
  20134. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20135. shapeVertices = shapeVertices.reverse();
  20136. }
  20137. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20138. shapeHole = shapeHoles[i];
  20139. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20140. shapeHoles[i] = shapeHole.reverse();
  20141. }
  20142. }
  20143. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20144. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20145. shapeHole = shapeHoles[i];
  20146. shapeVertices = shapeVertices.concat(shapeHole);
  20147. } // vertices, normals, uvs
  20148. for (i = 0, l = shapeVertices.length; i < l; i++) {
  20149. var vertex = shapeVertices[i];
  20150. vertices.push(vertex.x, vertex.y, 0);
  20151. normals.push(0, 0, 1);
  20152. uvs.push(vertex.x, vertex.y); // world uvs
  20153. } // incides
  20154. for (i = 0, l = faces.length; i < l; i++) {
  20155. var face = faces[i];
  20156. var a = face[0] + indexOffset;
  20157. var b = face[1] + indexOffset;
  20158. var c = face[2] + indexOffset;
  20159. indices.push(a, b, c);
  20160. groupCount += 3;
  20161. }
  20162. }
  20163. }
  20164. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20165. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20166. ShapeBufferGeometry.prototype.toJSON = function () {
  20167. var data = BufferGeometry.prototype.toJSON.call(this);
  20168. var shapes = this.parameters.shapes;
  20169. return toJSON$1(shapes, data);
  20170. }; //
  20171. function toJSON$1(shapes, data) {
  20172. data.shapes = [];
  20173. if (Array.isArray(shapes)) {
  20174. for (var i = 0, l = shapes.length; i < l; i++) {
  20175. var shape = shapes[i];
  20176. data.shapes.push(shape.uuid);
  20177. }
  20178. } else {
  20179. data.shapes.push(shapes.uuid);
  20180. }
  20181. return data;
  20182. }
  20183. /**
  20184. * @author WestLangley / http://github.com/WestLangley
  20185. * @author Mugen87 / https://github.com/Mugen87
  20186. */
  20187. function EdgesGeometry(geometry, thresholdAngle) {
  20188. BufferGeometry.call(this);
  20189. this.type = 'EdgesGeometry';
  20190. this.parameters = {
  20191. thresholdAngle: thresholdAngle
  20192. };
  20193. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  20194. var vertices = []; // helper variables
  20195. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  20196. var edge = [0, 0],
  20197. edges = {},
  20198. edge1,
  20199. edge2;
  20200. var key,
  20201. keys = ['a', 'b', 'c']; // prepare source geometry
  20202. var geometry2;
  20203. if (geometry.isBufferGeometry) {
  20204. geometry2 = new Geometry();
  20205. geometry2.fromBufferGeometry(geometry);
  20206. } else {
  20207. geometry2 = geometry.clone();
  20208. }
  20209. geometry2.mergeVertices();
  20210. geometry2.computeFaceNormals();
  20211. var sourceVertices = geometry2.vertices;
  20212. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  20213. for (var i = 0, l = faces.length; i < l; i++) {
  20214. var face = faces[i];
  20215. for (var j = 0; j < 3; j++) {
  20216. edge1 = face[keys[j]];
  20217. edge2 = face[keys[(j + 1) % 3]];
  20218. edge[0] = Math.min(edge1, edge2);
  20219. edge[1] = Math.max(edge1, edge2);
  20220. key = edge[0] + ',' + edge[1];
  20221. if (edges[key] === undefined) {
  20222. edges[key] = {
  20223. index1: edge[0],
  20224. index2: edge[1],
  20225. face1: i,
  20226. face2: undefined
  20227. };
  20228. } else {
  20229. edges[key].face2 = i;
  20230. }
  20231. }
  20232. } // generate vertices
  20233. for (key in edges) {
  20234. 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.
  20235. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  20236. var vertex = sourceVertices[e.index1];
  20237. vertices.push(vertex.x, vertex.y, vertex.z);
  20238. vertex = sourceVertices[e.index2];
  20239. vertices.push(vertex.x, vertex.y, vertex.z);
  20240. }
  20241. } // build geometry
  20242. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20243. }
  20244. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  20245. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20246. /**
  20247. * @author mrdoob / http://mrdoob.com/
  20248. * @author Mugen87 / https://github.com/Mugen87
  20249. */
  20250. // CylinderGeometry
  20251. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20252. Geometry.call(this);
  20253. this.type = 'CylinderGeometry';
  20254. this.parameters = {
  20255. radiusTop: radiusTop,
  20256. radiusBottom: radiusBottom,
  20257. height: height,
  20258. radialSegments: radialSegments,
  20259. heightSegments: heightSegments,
  20260. openEnded: openEnded,
  20261. thetaStart: thetaStart,
  20262. thetaLength: thetaLength
  20263. };
  20264. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  20265. this.mergeVertices();
  20266. }
  20267. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  20268. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  20269. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20270. BufferGeometry.call(this);
  20271. this.type = 'CylinderBufferGeometry';
  20272. this.parameters = {
  20273. radiusTop: radiusTop,
  20274. radiusBottom: radiusBottom,
  20275. height: height,
  20276. radialSegments: radialSegments,
  20277. heightSegments: heightSegments,
  20278. openEnded: openEnded,
  20279. thetaStart: thetaStart,
  20280. thetaLength: thetaLength
  20281. };
  20282. var scope = this;
  20283. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  20284. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  20285. height = height || 1;
  20286. radialSegments = Math.floor(radialSegments) || 8;
  20287. heightSegments = Math.floor(heightSegments) || 1;
  20288. openEnded = openEnded !== undefined ? openEnded : false;
  20289. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20290. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20291. var indices = [];
  20292. var vertices = [];
  20293. var normals = [];
  20294. var uvs = []; // helper variables
  20295. var index = 0;
  20296. var indexArray = [];
  20297. var halfHeight = height / 2;
  20298. var groupStart = 0; // generate geometry
  20299. generateTorso();
  20300. if (openEnded === false) {
  20301. if (radiusTop > 0) generateCap(true);
  20302. if (radiusBottom > 0) generateCap(false);
  20303. } // build geometry
  20304. this.setIndex(indices);
  20305. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20306. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20307. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20308. function generateTorso() {
  20309. var x, y;
  20310. var normal = new Vector3();
  20311. var vertex = new Vector3();
  20312. var groupCount = 0; // this will be used to calculate the normal
  20313. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  20314. for (y = 0; y <= heightSegments; y++) {
  20315. var indexRow = [];
  20316. var v = y / heightSegments; // calculate the radius of the current row
  20317. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  20318. for (x = 0; x <= radialSegments; x++) {
  20319. var u = x / radialSegments;
  20320. var theta = u * thetaLength + thetaStart;
  20321. var sinTheta = Math.sin(theta);
  20322. var cosTheta = Math.cos(theta); // vertex
  20323. vertex.x = radius * sinTheta;
  20324. vertex.y = -v * height + halfHeight;
  20325. vertex.z = radius * cosTheta;
  20326. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20327. normal.set(sinTheta, slope, cosTheta).normalize();
  20328. normals.push(normal.x, normal.y, normal.z); // uv
  20329. uvs.push(u, 1 - v); // save index of vertex in respective row
  20330. indexRow.push(index++);
  20331. } // now save vertices of the row in our index array
  20332. indexArray.push(indexRow);
  20333. } // generate indices
  20334. for (x = 0; x < radialSegments; x++) {
  20335. for (y = 0; y < heightSegments; y++) {
  20336. // we use the index array to access the correct indices
  20337. var a = indexArray[y][x];
  20338. var b = indexArray[y + 1][x];
  20339. var c = indexArray[y + 1][x + 1];
  20340. var d = indexArray[y][x + 1]; // faces
  20341. indices.push(a, b, d);
  20342. indices.push(b, c, d); // update group counter
  20343. groupCount += 6;
  20344. }
  20345. } // add a group to the geometry. this will ensure multi material support
  20346. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  20347. groupStart += groupCount;
  20348. }
  20349. function generateCap(top) {
  20350. var x, centerIndexStart, centerIndexEnd;
  20351. var uv = new Vector2();
  20352. var vertex = new Vector3();
  20353. var groupCount = 0;
  20354. var radius = top === true ? radiusTop : radiusBottom;
  20355. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  20356. centerIndexStart = index; // first we generate the center vertex data of the cap.
  20357. // because the geometry needs one set of uvs per face,
  20358. // we must generate a center vertex per face/segment
  20359. for (x = 1; x <= radialSegments; x++) {
  20360. // vertex
  20361. vertices.push(0, halfHeight * sign, 0); // normal
  20362. normals.push(0, sign, 0); // uv
  20363. uvs.push(0.5, 0.5); // increase index
  20364. index++;
  20365. } // save the index of the last center vertex
  20366. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  20367. for (x = 0; x <= radialSegments; x++) {
  20368. var u = x / radialSegments;
  20369. var theta = u * thetaLength + thetaStart;
  20370. var cosTheta = Math.cos(theta);
  20371. var sinTheta = Math.sin(theta); // vertex
  20372. vertex.x = radius * sinTheta;
  20373. vertex.y = halfHeight * sign;
  20374. vertex.z = radius * cosTheta;
  20375. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20376. normals.push(0, sign, 0); // uv
  20377. uv.x = cosTheta * 0.5 + 0.5;
  20378. uv.y = sinTheta * 0.5 * sign + 0.5;
  20379. uvs.push(uv.x, uv.y); // increase index
  20380. index++;
  20381. } // generate indices
  20382. for (x = 0; x < radialSegments; x++) {
  20383. var c = centerIndexStart + x;
  20384. var i = centerIndexEnd + x;
  20385. if (top === true) {
  20386. // face top
  20387. indices.push(i, i + 1, c);
  20388. } else {
  20389. // face bottom
  20390. indices.push(i + 1, i, c);
  20391. }
  20392. groupCount += 3;
  20393. } // add a group to the geometry. this will ensure multi material support
  20394. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  20395. groupStart += groupCount;
  20396. }
  20397. }
  20398. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20399. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20400. /**
  20401. * @author abelnation / http://github.com/abelnation
  20402. */
  20403. // ConeGeometry
  20404. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20405. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20406. this.type = 'ConeGeometry';
  20407. this.parameters = {
  20408. radius: radius,
  20409. height: height,
  20410. radialSegments: radialSegments,
  20411. heightSegments: heightSegments,
  20412. openEnded: openEnded,
  20413. thetaStart: thetaStart,
  20414. thetaLength: thetaLength
  20415. };
  20416. }
  20417. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  20418. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  20419. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20420. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20421. this.type = 'ConeBufferGeometry';
  20422. this.parameters = {
  20423. radius: radius,
  20424. height: height,
  20425. radialSegments: radialSegments,
  20426. heightSegments: heightSegments,
  20427. openEnded: openEnded,
  20428. thetaStart: thetaStart,
  20429. thetaLength: thetaLength
  20430. };
  20431. }
  20432. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  20433. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20434. /**
  20435. * @author benaadams / https://twitter.com/ben_a_adams
  20436. * @author Mugen87 / https://github.com/Mugen87
  20437. * @author hughes
  20438. */
  20439. // CircleGeometry
  20440. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  20441. Geometry.call(this);
  20442. this.type = 'CircleGeometry';
  20443. this.parameters = {
  20444. radius: radius,
  20445. segments: segments,
  20446. thetaStart: thetaStart,
  20447. thetaLength: thetaLength
  20448. };
  20449. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  20450. this.mergeVertices();
  20451. }
  20452. CircleGeometry.prototype = Object.create(Geometry.prototype);
  20453. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  20454. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  20455. BufferGeometry.call(this);
  20456. this.type = 'CircleBufferGeometry';
  20457. this.parameters = {
  20458. radius: radius,
  20459. segments: segments,
  20460. thetaStart: thetaStart,
  20461. thetaLength: thetaLength
  20462. };
  20463. radius = radius || 1;
  20464. segments = segments !== undefined ? Math.max(3, segments) : 8;
  20465. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20466. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20467. var indices = [];
  20468. var vertices = [];
  20469. var normals = [];
  20470. var uvs = []; // helper variables
  20471. var i, s;
  20472. var vertex = new Vector3();
  20473. var uv = new Vector2(); // center point
  20474. vertices.push(0, 0, 0);
  20475. normals.push(0, 0, 1);
  20476. uvs.push(0.5, 0.5);
  20477. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  20478. var segment = thetaStart + s / segments * thetaLength; // vertex
  20479. vertex.x = radius * Math.cos(segment);
  20480. vertex.y = radius * Math.sin(segment);
  20481. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20482. normals.push(0, 0, 1); // uvs
  20483. uv.x = (vertices[i] / radius + 1) / 2;
  20484. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20485. uvs.push(uv.x, uv.y);
  20486. } // indices
  20487. for (i = 1; i <= segments; i++) {
  20488. indices.push(i, i + 1, 0);
  20489. } // build geometry
  20490. this.setIndex(indices);
  20491. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20492. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20493. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20494. }
  20495. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20496. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20497. var Geometries =
  20498. /*#__PURE__*/
  20499. Object.freeze({
  20500. WireframeGeometry: WireframeGeometry,
  20501. ParametricGeometry: ParametricGeometry,
  20502. ParametricBufferGeometry: ParametricBufferGeometry,
  20503. TetrahedronGeometry: TetrahedronGeometry,
  20504. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20505. OctahedronGeometry: OctahedronGeometry,
  20506. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20507. IcosahedronGeometry: IcosahedronGeometry,
  20508. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20509. DodecahedronGeometry: DodecahedronGeometry,
  20510. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20511. PolyhedronGeometry: PolyhedronGeometry,
  20512. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20513. TubeGeometry: TubeGeometry,
  20514. TubeBufferGeometry: TubeBufferGeometry,
  20515. TorusKnotGeometry: TorusKnotGeometry,
  20516. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20517. TorusGeometry: TorusGeometry,
  20518. TorusBufferGeometry: TorusBufferGeometry,
  20519. TextGeometry: TextGeometry,
  20520. TextBufferGeometry: TextBufferGeometry,
  20521. SphereGeometry: SphereGeometry,
  20522. SphereBufferGeometry: SphereBufferGeometry,
  20523. RingGeometry: RingGeometry,
  20524. RingBufferGeometry: RingBufferGeometry,
  20525. PlaneGeometry: PlaneGeometry,
  20526. PlaneBufferGeometry: PlaneBufferGeometry,
  20527. LatheGeometry: LatheGeometry,
  20528. LatheBufferGeometry: LatheBufferGeometry,
  20529. ShapeGeometry: ShapeGeometry,
  20530. ShapeBufferGeometry: ShapeBufferGeometry,
  20531. ExtrudeGeometry: ExtrudeGeometry,
  20532. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20533. EdgesGeometry: EdgesGeometry,
  20534. ConeGeometry: ConeGeometry,
  20535. ConeBufferGeometry: ConeBufferGeometry,
  20536. CylinderGeometry: CylinderGeometry,
  20537. CylinderBufferGeometry: CylinderBufferGeometry,
  20538. CircleGeometry: CircleGeometry,
  20539. CircleBufferGeometry: CircleBufferGeometry,
  20540. BoxGeometry: BoxGeometry,
  20541. BoxBufferGeometry: BoxBufferGeometry
  20542. });
  20543. /**
  20544. * @author mrdoob / http://mrdoob.com/
  20545. *
  20546. * parameters = {
  20547. * color: <THREE.Color>
  20548. * }
  20549. */
  20550. function ShadowMaterial(parameters) {
  20551. Material.call(this);
  20552. this.type = 'ShadowMaterial';
  20553. this.color = new Color(0x000000);
  20554. this.transparent = true;
  20555. this.setValues(parameters);
  20556. }
  20557. ShadowMaterial.prototype = Object.create(Material.prototype);
  20558. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20559. ShadowMaterial.prototype.isShadowMaterial = true;
  20560. ShadowMaterial.prototype.copy = function (source) {
  20561. Material.prototype.copy.call(this, source);
  20562. this.color.copy(source.color);
  20563. return this;
  20564. };
  20565. /**
  20566. * @author mrdoob / http://mrdoob.com/
  20567. */
  20568. function RawShaderMaterial(parameters) {
  20569. ShaderMaterial.call(this, parameters);
  20570. this.type = 'RawShaderMaterial';
  20571. }
  20572. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20573. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20574. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20575. /**
  20576. * @author WestLangley / http://github.com/WestLangley
  20577. *
  20578. * parameters = {
  20579. * color: <hex>,
  20580. * roughness: <float>,
  20581. * metalness: <float>,
  20582. * opacity: <float>,
  20583. *
  20584. * map: new THREE.Texture( <Image> ),
  20585. *
  20586. * lightMap: new THREE.Texture( <Image> ),
  20587. * lightMapIntensity: <float>
  20588. *
  20589. * aoMap: new THREE.Texture( <Image> ),
  20590. * aoMapIntensity: <float>
  20591. *
  20592. * emissive: <hex>,
  20593. * emissiveIntensity: <float>
  20594. * emissiveMap: new THREE.Texture( <Image> ),
  20595. *
  20596. * bumpMap: new THREE.Texture( <Image> ),
  20597. * bumpScale: <float>,
  20598. *
  20599. * normalMap: new THREE.Texture( <Image> ),
  20600. * normalMapType: THREE.TangentSpaceNormalMap,
  20601. * normalScale: <Vector2>,
  20602. *
  20603. * displacementMap: new THREE.Texture( <Image> ),
  20604. * displacementScale: <float>,
  20605. * displacementBias: <float>,
  20606. *
  20607. * roughnessMap: new THREE.Texture( <Image> ),
  20608. *
  20609. * metalnessMap: new THREE.Texture( <Image> ),
  20610. *
  20611. * alphaMap: new THREE.Texture( <Image> ),
  20612. *
  20613. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20614. * envMapIntensity: <float>
  20615. *
  20616. * refractionRatio: <float>,
  20617. *
  20618. * wireframe: <boolean>,
  20619. * wireframeLinewidth: <float>,
  20620. *
  20621. * skinning: <bool>,
  20622. * morphTargets: <bool>,
  20623. * morphNormals: <bool>
  20624. * }
  20625. */
  20626. function MeshStandardMaterial(parameters) {
  20627. Material.call(this);
  20628. this.defines = {
  20629. 'STANDARD': ''
  20630. };
  20631. this.type = 'MeshStandardMaterial';
  20632. this.color = new Color(0xffffff); // diffuse
  20633. this.roughness = 0.5;
  20634. this.metalness = 0.5;
  20635. this.map = null;
  20636. this.lightMap = null;
  20637. this.lightMapIntensity = 1.0;
  20638. this.aoMap = null;
  20639. this.aoMapIntensity = 1.0;
  20640. this.emissive = new Color(0x000000);
  20641. this.emissiveIntensity = 1.0;
  20642. this.emissiveMap = null;
  20643. this.bumpMap = null;
  20644. this.bumpScale = 1;
  20645. this.normalMap = null;
  20646. this.normalMapType = TangentSpaceNormalMap;
  20647. this.normalScale = new Vector2(1, 1);
  20648. this.displacementMap = null;
  20649. this.displacementScale = 1;
  20650. this.displacementBias = 0;
  20651. this.roughnessMap = null;
  20652. this.metalnessMap = null;
  20653. this.alphaMap = null;
  20654. this.envMap = null;
  20655. this.envMapIntensity = 1.0;
  20656. this.refractionRatio = 0.98;
  20657. this.wireframe = false;
  20658. this.wireframeLinewidth = 1;
  20659. this.wireframeLinecap = 'round';
  20660. this.wireframeLinejoin = 'round';
  20661. this.skinning = false;
  20662. this.morphTargets = false;
  20663. this.morphNormals = false;
  20664. this.setValues(parameters);
  20665. }
  20666. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20667. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20668. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20669. MeshStandardMaterial.prototype.copy = function (source) {
  20670. Material.prototype.copy.call(this, source);
  20671. this.defines = {
  20672. 'STANDARD': ''
  20673. };
  20674. this.color.copy(source.color);
  20675. this.roughness = source.roughness;
  20676. this.metalness = source.metalness;
  20677. this.map = source.map;
  20678. this.lightMap = source.lightMap;
  20679. this.lightMapIntensity = source.lightMapIntensity;
  20680. this.aoMap = source.aoMap;
  20681. this.aoMapIntensity = source.aoMapIntensity;
  20682. this.emissive.copy(source.emissive);
  20683. this.emissiveMap = source.emissiveMap;
  20684. this.emissiveIntensity = source.emissiveIntensity;
  20685. this.bumpMap = source.bumpMap;
  20686. this.bumpScale = source.bumpScale;
  20687. this.normalMap = source.normalMap;
  20688. this.normalMapType = source.normalMapType;
  20689. this.normalScale.copy(source.normalScale);
  20690. this.displacementMap = source.displacementMap;
  20691. this.displacementScale = source.displacementScale;
  20692. this.displacementBias = source.displacementBias;
  20693. this.roughnessMap = source.roughnessMap;
  20694. this.metalnessMap = source.metalnessMap;
  20695. this.alphaMap = source.alphaMap;
  20696. this.envMap = source.envMap;
  20697. this.envMapIntensity = source.envMapIntensity;
  20698. this.refractionRatio = source.refractionRatio;
  20699. this.wireframe = source.wireframe;
  20700. this.wireframeLinewidth = source.wireframeLinewidth;
  20701. this.wireframeLinecap = source.wireframeLinecap;
  20702. this.wireframeLinejoin = source.wireframeLinejoin;
  20703. this.skinning = source.skinning;
  20704. this.morphTargets = source.morphTargets;
  20705. this.morphNormals = source.morphNormals;
  20706. return this;
  20707. };
  20708. /**
  20709. * @author WestLangley / http://github.com/WestLangley
  20710. *
  20711. * parameters = {
  20712. * reflectivity: <float>
  20713. * clearcoat: <float>
  20714. * clearcoatRoughness: <float>
  20715. *
  20716. * sheen: <Color>
  20717. *
  20718. * clearcoatNormalScale: <Vector2>,
  20719. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20720. * }
  20721. */
  20722. function MeshPhysicalMaterial(parameters) {
  20723. MeshStandardMaterial.call(this);
  20724. this.defines = {
  20725. 'STANDARD': '',
  20726. 'PHYSICAL': ''
  20727. };
  20728. this.type = 'MeshPhysicalMaterial';
  20729. this.reflectivity = 0.5; // maps to F0 = 0.04
  20730. this.clearcoat = 0.0;
  20731. this.clearcoatRoughness = 0.0;
  20732. this.sheen = null; // null will disable sheen bsdf
  20733. this.clearcoatNormalScale = new Vector2(1, 1);
  20734. this.clearcoatNormalMap = null;
  20735. this.transparency = 0.0;
  20736. this.setValues(parameters);
  20737. }
  20738. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20739. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20740. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20741. MeshPhysicalMaterial.prototype.copy = function (source) {
  20742. MeshStandardMaterial.prototype.copy.call(this, source);
  20743. this.defines = {
  20744. 'STANDARD': '',
  20745. 'PHYSICAL': ''
  20746. };
  20747. this.reflectivity = source.reflectivity;
  20748. this.clearcoat = source.clearcoat;
  20749. this.clearcoatRoughness = source.clearcoatRoughness;
  20750. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  20751. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20752. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20753. this.transparency = source.transparency;
  20754. return this;
  20755. };
  20756. /**
  20757. * @author mrdoob / http://mrdoob.com/
  20758. * @author alteredq / http://alteredqualia.com/
  20759. *
  20760. * parameters = {
  20761. * color: <hex>,
  20762. * specular: <hex>,
  20763. * shininess: <float>,
  20764. * opacity: <float>,
  20765. *
  20766. * map: new THREE.Texture( <Image> ),
  20767. *
  20768. * lightMap: new THREE.Texture( <Image> ),
  20769. * lightMapIntensity: <float>
  20770. *
  20771. * aoMap: new THREE.Texture( <Image> ),
  20772. * aoMapIntensity: <float>
  20773. *
  20774. * emissive: <hex>,
  20775. * emissiveIntensity: <float>
  20776. * emissiveMap: new THREE.Texture( <Image> ),
  20777. *
  20778. * bumpMap: new THREE.Texture( <Image> ),
  20779. * bumpScale: <float>,
  20780. *
  20781. * normalMap: new THREE.Texture( <Image> ),
  20782. * normalMapType: THREE.TangentSpaceNormalMap,
  20783. * normalScale: <Vector2>,
  20784. *
  20785. * displacementMap: new THREE.Texture( <Image> ),
  20786. * displacementScale: <float>,
  20787. * displacementBias: <float>,
  20788. *
  20789. * specularMap: new THREE.Texture( <Image> ),
  20790. *
  20791. * alphaMap: new THREE.Texture( <Image> ),
  20792. *
  20793. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20794. * combine: THREE.Multiply,
  20795. * reflectivity: <float>,
  20796. * refractionRatio: <float>,
  20797. *
  20798. * wireframe: <boolean>,
  20799. * wireframeLinewidth: <float>,
  20800. *
  20801. * skinning: <bool>,
  20802. * morphTargets: <bool>,
  20803. * morphNormals: <bool>
  20804. * }
  20805. */
  20806. function MeshPhongMaterial(parameters) {
  20807. Material.call(this);
  20808. this.type = 'MeshPhongMaterial';
  20809. this.color = new Color(0xffffff); // diffuse
  20810. this.specular = new Color(0x111111);
  20811. this.shininess = 30;
  20812. this.map = null;
  20813. this.lightMap = null;
  20814. this.lightMapIntensity = 1.0;
  20815. this.aoMap = null;
  20816. this.aoMapIntensity = 1.0;
  20817. this.emissive = new Color(0x000000);
  20818. this.emissiveIntensity = 1.0;
  20819. this.emissiveMap = null;
  20820. this.bumpMap = null;
  20821. this.bumpScale = 1;
  20822. this.normalMap = null;
  20823. this.normalMapType = TangentSpaceNormalMap;
  20824. this.normalScale = new Vector2(1, 1);
  20825. this.displacementMap = null;
  20826. this.displacementScale = 1;
  20827. this.displacementBias = 0;
  20828. this.specularMap = null;
  20829. this.alphaMap = null;
  20830. this.envMap = null;
  20831. this.combine = MultiplyOperation;
  20832. this.reflectivity = 1;
  20833. this.refractionRatio = 0.98;
  20834. this.wireframe = false;
  20835. this.wireframeLinewidth = 1;
  20836. this.wireframeLinecap = 'round';
  20837. this.wireframeLinejoin = 'round';
  20838. this.skinning = false;
  20839. this.morphTargets = false;
  20840. this.morphNormals = false;
  20841. this.setValues(parameters);
  20842. }
  20843. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20844. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20845. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20846. MeshPhongMaterial.prototype.copy = function (source) {
  20847. Material.prototype.copy.call(this, source);
  20848. this.color.copy(source.color);
  20849. this.specular.copy(source.specular);
  20850. this.shininess = source.shininess;
  20851. this.map = source.map;
  20852. this.lightMap = source.lightMap;
  20853. this.lightMapIntensity = source.lightMapIntensity;
  20854. this.aoMap = source.aoMap;
  20855. this.aoMapIntensity = source.aoMapIntensity;
  20856. this.emissive.copy(source.emissive);
  20857. this.emissiveMap = source.emissiveMap;
  20858. this.emissiveIntensity = source.emissiveIntensity;
  20859. this.bumpMap = source.bumpMap;
  20860. this.bumpScale = source.bumpScale;
  20861. this.normalMap = source.normalMap;
  20862. this.normalMapType = source.normalMapType;
  20863. this.normalScale.copy(source.normalScale);
  20864. this.displacementMap = source.displacementMap;
  20865. this.displacementScale = source.displacementScale;
  20866. this.displacementBias = source.displacementBias;
  20867. this.specularMap = source.specularMap;
  20868. this.alphaMap = source.alphaMap;
  20869. this.envMap = source.envMap;
  20870. this.combine = source.combine;
  20871. this.reflectivity = source.reflectivity;
  20872. this.refractionRatio = source.refractionRatio;
  20873. this.wireframe = source.wireframe;
  20874. this.wireframeLinewidth = source.wireframeLinewidth;
  20875. this.wireframeLinecap = source.wireframeLinecap;
  20876. this.wireframeLinejoin = source.wireframeLinejoin;
  20877. this.skinning = source.skinning;
  20878. this.morphTargets = source.morphTargets;
  20879. this.morphNormals = source.morphNormals;
  20880. return this;
  20881. };
  20882. /**
  20883. * @author takahirox / http://github.com/takahirox
  20884. *
  20885. * parameters = {
  20886. * gradientMap: new THREE.Texture( <Image> )
  20887. * }
  20888. */
  20889. function MeshToonMaterial(parameters) {
  20890. MeshPhongMaterial.call(this);
  20891. this.defines = {
  20892. 'TOON': ''
  20893. };
  20894. this.type = 'MeshToonMaterial';
  20895. this.gradientMap = null;
  20896. this.setValues(parameters);
  20897. }
  20898. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  20899. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20900. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20901. MeshToonMaterial.prototype.copy = function (source) {
  20902. MeshPhongMaterial.prototype.copy.call(this, source);
  20903. this.gradientMap = source.gradientMap;
  20904. return this;
  20905. };
  20906. /**
  20907. * @author mrdoob / http://mrdoob.com/
  20908. * @author WestLangley / http://github.com/WestLangley
  20909. *
  20910. * parameters = {
  20911. * opacity: <float>,
  20912. *
  20913. * bumpMap: new THREE.Texture( <Image> ),
  20914. * bumpScale: <float>,
  20915. *
  20916. * normalMap: new THREE.Texture( <Image> ),
  20917. * normalMapType: THREE.TangentSpaceNormalMap,
  20918. * normalScale: <Vector2>,
  20919. *
  20920. * displacementMap: new THREE.Texture( <Image> ),
  20921. * displacementScale: <float>,
  20922. * displacementBias: <float>,
  20923. *
  20924. * wireframe: <boolean>,
  20925. * wireframeLinewidth: <float>
  20926. *
  20927. * skinning: <bool>,
  20928. * morphTargets: <bool>,
  20929. * morphNormals: <bool>
  20930. * }
  20931. */
  20932. function MeshNormalMaterial(parameters) {
  20933. Material.call(this);
  20934. this.type = 'MeshNormalMaterial';
  20935. this.bumpMap = null;
  20936. this.bumpScale = 1;
  20937. this.normalMap = null;
  20938. this.normalMapType = TangentSpaceNormalMap;
  20939. this.normalScale = new Vector2(1, 1);
  20940. this.displacementMap = null;
  20941. this.displacementScale = 1;
  20942. this.displacementBias = 0;
  20943. this.wireframe = false;
  20944. this.wireframeLinewidth = 1;
  20945. this.fog = false;
  20946. this.skinning = false;
  20947. this.morphTargets = false;
  20948. this.morphNormals = false;
  20949. this.setValues(parameters);
  20950. }
  20951. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20952. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20953. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20954. MeshNormalMaterial.prototype.copy = function (source) {
  20955. Material.prototype.copy.call(this, source);
  20956. this.bumpMap = source.bumpMap;
  20957. this.bumpScale = source.bumpScale;
  20958. this.normalMap = source.normalMap;
  20959. this.normalMapType = source.normalMapType;
  20960. this.normalScale.copy(source.normalScale);
  20961. this.displacementMap = source.displacementMap;
  20962. this.displacementScale = source.displacementScale;
  20963. this.displacementBias = source.displacementBias;
  20964. this.wireframe = source.wireframe;
  20965. this.wireframeLinewidth = source.wireframeLinewidth;
  20966. this.skinning = source.skinning;
  20967. this.morphTargets = source.morphTargets;
  20968. this.morphNormals = source.morphNormals;
  20969. return this;
  20970. };
  20971. /**
  20972. * @author mrdoob / http://mrdoob.com/
  20973. * @author alteredq / http://alteredqualia.com/
  20974. *
  20975. * parameters = {
  20976. * color: <hex>,
  20977. * opacity: <float>,
  20978. *
  20979. * map: new THREE.Texture( <Image> ),
  20980. *
  20981. * lightMap: new THREE.Texture( <Image> ),
  20982. * lightMapIntensity: <float>
  20983. *
  20984. * aoMap: new THREE.Texture( <Image> ),
  20985. * aoMapIntensity: <float>
  20986. *
  20987. * emissive: <hex>,
  20988. * emissiveIntensity: <float>
  20989. * emissiveMap: new THREE.Texture( <Image> ),
  20990. *
  20991. * specularMap: new THREE.Texture( <Image> ),
  20992. *
  20993. * alphaMap: new THREE.Texture( <Image> ),
  20994. *
  20995. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20996. * combine: THREE.Multiply,
  20997. * reflectivity: <float>,
  20998. * refractionRatio: <float>,
  20999. *
  21000. * wireframe: <boolean>,
  21001. * wireframeLinewidth: <float>,
  21002. *
  21003. * skinning: <bool>,
  21004. * morphTargets: <bool>,
  21005. * morphNormals: <bool>
  21006. * }
  21007. */
  21008. function MeshLambertMaterial(parameters) {
  21009. Material.call(this);
  21010. this.type = 'MeshLambertMaterial';
  21011. this.color = new Color(0xffffff); // diffuse
  21012. this.map = null;
  21013. this.lightMap = null;
  21014. this.lightMapIntensity = 1.0;
  21015. this.aoMap = null;
  21016. this.aoMapIntensity = 1.0;
  21017. this.emissive = new Color(0x000000);
  21018. this.emissiveIntensity = 1.0;
  21019. this.emissiveMap = null;
  21020. this.specularMap = null;
  21021. this.alphaMap = null;
  21022. this.envMap = null;
  21023. this.combine = MultiplyOperation;
  21024. this.reflectivity = 1;
  21025. this.refractionRatio = 0.98;
  21026. this.wireframe = false;
  21027. this.wireframeLinewidth = 1;
  21028. this.wireframeLinecap = 'round';
  21029. this.wireframeLinejoin = 'round';
  21030. this.skinning = false;
  21031. this.morphTargets = false;
  21032. this.morphNormals = false;
  21033. this.setValues(parameters);
  21034. }
  21035. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  21036. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21037. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21038. MeshLambertMaterial.prototype.copy = function (source) {
  21039. Material.prototype.copy.call(this, source);
  21040. this.color.copy(source.color);
  21041. this.map = source.map;
  21042. this.lightMap = source.lightMap;
  21043. this.lightMapIntensity = source.lightMapIntensity;
  21044. this.aoMap = source.aoMap;
  21045. this.aoMapIntensity = source.aoMapIntensity;
  21046. this.emissive.copy(source.emissive);
  21047. this.emissiveMap = source.emissiveMap;
  21048. this.emissiveIntensity = source.emissiveIntensity;
  21049. this.specularMap = source.specularMap;
  21050. this.alphaMap = source.alphaMap;
  21051. this.envMap = source.envMap;
  21052. this.combine = source.combine;
  21053. this.reflectivity = source.reflectivity;
  21054. this.refractionRatio = source.refractionRatio;
  21055. this.wireframe = source.wireframe;
  21056. this.wireframeLinewidth = source.wireframeLinewidth;
  21057. this.wireframeLinecap = source.wireframeLinecap;
  21058. this.wireframeLinejoin = source.wireframeLinejoin;
  21059. this.skinning = source.skinning;
  21060. this.morphTargets = source.morphTargets;
  21061. this.morphNormals = source.morphNormals;
  21062. return this;
  21063. };
  21064. /**
  21065. * @author WestLangley / http://github.com/WestLangley
  21066. *
  21067. * parameters = {
  21068. * color: <hex>,
  21069. * opacity: <float>,
  21070. *
  21071. * matcap: new THREE.Texture( <Image> ),
  21072. *
  21073. * map: new THREE.Texture( <Image> ),
  21074. *
  21075. * bumpMap: new THREE.Texture( <Image> ),
  21076. * bumpScale: <float>,
  21077. *
  21078. * normalMap: new THREE.Texture( <Image> ),
  21079. * normalMapType: THREE.TangentSpaceNormalMap,
  21080. * normalScale: <Vector2>,
  21081. *
  21082. * displacementMap: new THREE.Texture( <Image> ),
  21083. * displacementScale: <float>,
  21084. * displacementBias: <float>,
  21085. *
  21086. * alphaMap: new THREE.Texture( <Image> ),
  21087. *
  21088. * skinning: <bool>,
  21089. * morphTargets: <bool>,
  21090. * morphNormals: <bool>
  21091. * }
  21092. */
  21093. function MeshMatcapMaterial(parameters) {
  21094. Material.call(this);
  21095. this.defines = {
  21096. 'MATCAP': ''
  21097. };
  21098. this.type = 'MeshMatcapMaterial';
  21099. this.color = new Color(0xffffff); // diffuse
  21100. this.matcap = null;
  21101. this.map = null;
  21102. this.bumpMap = null;
  21103. this.bumpScale = 1;
  21104. this.normalMap = null;
  21105. this.normalMapType = TangentSpaceNormalMap;
  21106. this.normalScale = new Vector2(1, 1);
  21107. this.displacementMap = null;
  21108. this.displacementScale = 1;
  21109. this.displacementBias = 0;
  21110. this.alphaMap = null;
  21111. this.skinning = false;
  21112. this.morphTargets = false;
  21113. this.morphNormals = false;
  21114. this.setValues(parameters);
  21115. }
  21116. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  21117. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21118. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21119. MeshMatcapMaterial.prototype.copy = function (source) {
  21120. Material.prototype.copy.call(this, source);
  21121. this.defines = {
  21122. 'MATCAP': ''
  21123. };
  21124. this.color.copy(source.color);
  21125. this.matcap = source.matcap;
  21126. this.map = source.map;
  21127. this.bumpMap = source.bumpMap;
  21128. this.bumpScale = source.bumpScale;
  21129. this.normalMap = source.normalMap;
  21130. this.normalMapType = source.normalMapType;
  21131. this.normalScale.copy(source.normalScale);
  21132. this.displacementMap = source.displacementMap;
  21133. this.displacementScale = source.displacementScale;
  21134. this.displacementBias = source.displacementBias;
  21135. this.alphaMap = source.alphaMap;
  21136. this.skinning = source.skinning;
  21137. this.morphTargets = source.morphTargets;
  21138. this.morphNormals = source.morphNormals;
  21139. return this;
  21140. };
  21141. /**
  21142. * @author alteredq / http://alteredqualia.com/
  21143. *
  21144. * parameters = {
  21145. * color: <hex>,
  21146. * opacity: <float>,
  21147. *
  21148. * linewidth: <float>,
  21149. *
  21150. * scale: <float>,
  21151. * dashSize: <float>,
  21152. * gapSize: <float>
  21153. * }
  21154. */
  21155. function LineDashedMaterial(parameters) {
  21156. LineBasicMaterial.call(this);
  21157. this.type = 'LineDashedMaterial';
  21158. this.scale = 1;
  21159. this.dashSize = 3;
  21160. this.gapSize = 1;
  21161. this.setValues(parameters);
  21162. }
  21163. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  21164. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21165. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21166. LineDashedMaterial.prototype.copy = function (source) {
  21167. LineBasicMaterial.prototype.copy.call(this, source);
  21168. this.scale = source.scale;
  21169. this.dashSize = source.dashSize;
  21170. this.gapSize = source.gapSize;
  21171. return this;
  21172. };
  21173. var Materials =
  21174. /*#__PURE__*/
  21175. Object.freeze({
  21176. ShadowMaterial: ShadowMaterial,
  21177. SpriteMaterial: SpriteMaterial,
  21178. RawShaderMaterial: RawShaderMaterial,
  21179. ShaderMaterial: ShaderMaterial,
  21180. PointsMaterial: PointsMaterial,
  21181. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21182. MeshStandardMaterial: MeshStandardMaterial,
  21183. MeshPhongMaterial: MeshPhongMaterial,
  21184. MeshToonMaterial: MeshToonMaterial,
  21185. MeshNormalMaterial: MeshNormalMaterial,
  21186. MeshLambertMaterial: MeshLambertMaterial,
  21187. MeshDepthMaterial: MeshDepthMaterial,
  21188. MeshDistanceMaterial: MeshDistanceMaterial,
  21189. MeshBasicMaterial: MeshBasicMaterial,
  21190. MeshMatcapMaterial: MeshMatcapMaterial,
  21191. LineDashedMaterial: LineDashedMaterial,
  21192. LineBasicMaterial: LineBasicMaterial,
  21193. Material: Material
  21194. });
  21195. /**
  21196. * @author tschw
  21197. * @author Ben Houston / http://clara.io/
  21198. * @author David Sarno / http://lighthaus.us/
  21199. */
  21200. var AnimationUtils = {
  21201. // same as Array.prototype.slice, but also works on typed arrays
  21202. arraySlice: function (array, from, to) {
  21203. if (AnimationUtils.isTypedArray(array)) {
  21204. // in ios9 array.subarray(from, undefined) will return empty array
  21205. // but array.subarray(from) or array.subarray(from, len) is correct
  21206. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21207. }
  21208. return array.slice(from, to);
  21209. },
  21210. // converts an array to a specific type
  21211. convertArray: function (array, type, forceClone) {
  21212. if (!array || // let 'undefined' and 'null' pass
  21213. !forceClone && array.constructor === type) return array;
  21214. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21215. return new type(array); // create typed array
  21216. }
  21217. return Array.prototype.slice.call(array); // create Array
  21218. },
  21219. isTypedArray: function (object) {
  21220. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21221. },
  21222. // returns an array by which times and values can be sorted
  21223. getKeyframeOrder: function (times) {
  21224. function compareTime(i, j) {
  21225. return times[i] - times[j];
  21226. }
  21227. var n = times.length;
  21228. var result = new Array(n);
  21229. for (var i = 0; i !== n; ++i) result[i] = i;
  21230. result.sort(compareTime);
  21231. return result;
  21232. },
  21233. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21234. sortedArray: function (values, stride, order) {
  21235. var nValues = values.length;
  21236. var result = new values.constructor(nValues);
  21237. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21238. var srcOffset = order[i] * stride;
  21239. for (var j = 0; j !== stride; ++j) {
  21240. result[dstOffset++] = values[srcOffset + j];
  21241. }
  21242. }
  21243. return result;
  21244. },
  21245. // function for parsing AOS keyframe formats
  21246. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21247. var i = 1,
  21248. key = jsonKeys[0];
  21249. while (key !== undefined && key[valuePropertyName] === undefined) {
  21250. key = jsonKeys[i++];
  21251. }
  21252. if (key === undefined) return; // no data
  21253. var value = key[valuePropertyName];
  21254. if (value === undefined) return; // no data
  21255. if (Array.isArray(value)) {
  21256. do {
  21257. value = key[valuePropertyName];
  21258. if (value !== undefined) {
  21259. times.push(key.time);
  21260. values.push.apply(values, value); // push all elements
  21261. }
  21262. key = jsonKeys[i++];
  21263. } while (key !== undefined);
  21264. } else if (value.toArray !== undefined) {
  21265. // ...assume THREE.Math-ish
  21266. do {
  21267. value = key[valuePropertyName];
  21268. if (value !== undefined) {
  21269. times.push(key.time);
  21270. value.toArray(values, values.length);
  21271. }
  21272. key = jsonKeys[i++];
  21273. } while (key !== undefined);
  21274. } else {
  21275. // otherwise push as-is
  21276. do {
  21277. value = key[valuePropertyName];
  21278. if (value !== undefined) {
  21279. times.push(key.time);
  21280. values.push(value);
  21281. }
  21282. key = jsonKeys[i++];
  21283. } while (key !== undefined);
  21284. }
  21285. }
  21286. };
  21287. /**
  21288. * Abstract base class of interpolants over parametric samples.
  21289. *
  21290. * The parameter domain is one dimensional, typically the time or a path
  21291. * along a curve defined by the data.
  21292. *
  21293. * The sample values can have any dimensionality and derived classes may
  21294. * apply special interpretations to the data.
  21295. *
  21296. * This class provides the interval seek in a Template Method, deferring
  21297. * the actual interpolation to derived classes.
  21298. *
  21299. * Time complexity is O(1) for linear access crossing at most two points
  21300. * and O(log N) for random access, where N is the number of positions.
  21301. *
  21302. * References:
  21303. *
  21304. * http://www.oodesign.com/template-method-pattern.html
  21305. *
  21306. * @author tschw
  21307. */
  21308. exports.AnimationUtils = AnimationUtils;
  21309. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21310. this.parameterPositions = parameterPositions;
  21311. this._cachedIndex = 0;
  21312. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21313. this.sampleValues = sampleValues;
  21314. this.valueSize = sampleSize;
  21315. }
  21316. Object.assign(Interpolant.prototype, {
  21317. evaluate: function (t) {
  21318. var pp = this.parameterPositions,
  21319. i1 = this._cachedIndex,
  21320. t1 = pp[i1],
  21321. t0 = pp[i1 - 1];
  21322. validate_interval: {
  21323. seek: {
  21324. var right;
  21325. linear_scan: {
  21326. //- See http://jsperf.com/comparison-to-undefined/3
  21327. //- slower code:
  21328. //-
  21329. //- if ( t >= t1 || t1 === undefined ) {
  21330. forward_scan: if (!(t < t1)) {
  21331. for (var giveUpAt = i1 + 2;;) {
  21332. if (t1 === undefined) {
  21333. if (t < t0) break forward_scan; // after end
  21334. i1 = pp.length;
  21335. this._cachedIndex = i1;
  21336. return this.afterEnd_(i1 - 1, t, t0);
  21337. }
  21338. if (i1 === giveUpAt) break; // this loop
  21339. t0 = t1;
  21340. t1 = pp[++i1];
  21341. if (t < t1) {
  21342. // we have arrived at the sought interval
  21343. break seek;
  21344. }
  21345. } // prepare binary search on the right side of the index
  21346. right = pp.length;
  21347. break linear_scan;
  21348. } //- slower code:
  21349. //- if ( t < t0 || t0 === undefined ) {
  21350. if (!(t >= t0)) {
  21351. // looping?
  21352. var t1global = pp[1];
  21353. if (t < t1global) {
  21354. i1 = 2; // + 1, using the scan for the details
  21355. t0 = t1global;
  21356. } // linear reverse scan
  21357. for (var giveUpAt = i1 - 2;;) {
  21358. if (t0 === undefined) {
  21359. // before start
  21360. this._cachedIndex = 0;
  21361. return this.beforeStart_(0, t, t1);
  21362. }
  21363. if (i1 === giveUpAt) break; // this loop
  21364. t1 = t0;
  21365. t0 = pp[--i1 - 1];
  21366. if (t >= t0) {
  21367. // we have arrived at the sought interval
  21368. break seek;
  21369. }
  21370. } // prepare binary search on the left side of the index
  21371. right = i1;
  21372. i1 = 0;
  21373. break linear_scan;
  21374. } // the interval is valid
  21375. break validate_interval;
  21376. } // linear scan
  21377. // binary search
  21378. while (i1 < right) {
  21379. var mid = i1 + right >>> 1;
  21380. if (t < pp[mid]) {
  21381. right = mid;
  21382. } else {
  21383. i1 = mid + 1;
  21384. }
  21385. }
  21386. t1 = pp[i1];
  21387. t0 = pp[i1 - 1]; // check boundary cases, again
  21388. if (t0 === undefined) {
  21389. this._cachedIndex = 0;
  21390. return this.beforeStart_(0, t, t1);
  21391. }
  21392. if (t1 === undefined) {
  21393. i1 = pp.length;
  21394. this._cachedIndex = i1;
  21395. return this.afterEnd_(i1 - 1, t0, t);
  21396. }
  21397. } // seek
  21398. this._cachedIndex = i1;
  21399. this.intervalChanged_(i1, t0, t1);
  21400. } // validate_interval
  21401. return this.interpolate_(i1, t0, t, t1);
  21402. },
  21403. settings: null,
  21404. // optional, subclass-specific settings structure
  21405. // Note: The indirection allows central control of many interpolants.
  21406. // --- Protected interface
  21407. DefaultSettings_: {},
  21408. getSettings_: function () {
  21409. return this.settings || this.DefaultSettings_;
  21410. },
  21411. copySampleValue_: function (index) {
  21412. // copies a sample value to the result buffer
  21413. var result = this.resultBuffer,
  21414. values = this.sampleValues,
  21415. stride = this.valueSize,
  21416. offset = index * stride;
  21417. for (var i = 0; i !== stride; ++i) {
  21418. result[i] = values[offset + i];
  21419. }
  21420. return result;
  21421. },
  21422. // Template methods for derived classes:
  21423. interpolate_: function ()
  21424. /* i1, t0, t, t1 */
  21425. {
  21426. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21427. },
  21428. intervalChanged_: function ()
  21429. /* i1, t0, t1 */
  21430. {// empty
  21431. }
  21432. }); //!\ DECLARE ALIAS AFTER assign prototype !
  21433. Object.assign(Interpolant.prototype, {
  21434. //( 0, t, t0 ), returns this.resultBuffer
  21435. beforeStart_: Interpolant.prototype.copySampleValue_,
  21436. //( N-1, tN-1, t ), returns this.resultBuffer
  21437. afterEnd_: Interpolant.prototype.copySampleValue_
  21438. });
  21439. /**
  21440. * Fast and simple cubic spline interpolant.
  21441. *
  21442. * It was derived from a Hermitian construction setting the first derivative
  21443. * at each sample position to the linear slope between neighboring positions
  21444. * over their parameter interval.
  21445. *
  21446. * @author tschw
  21447. */
  21448. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21449. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21450. this._weightPrev = -0;
  21451. this._offsetPrev = -0;
  21452. this._weightNext = -0;
  21453. this._offsetNext = -0;
  21454. }
  21455. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21456. constructor: CubicInterpolant,
  21457. DefaultSettings_: {
  21458. endingStart: ZeroCurvatureEnding,
  21459. endingEnd: ZeroCurvatureEnding
  21460. },
  21461. intervalChanged_: function (i1, t0, t1) {
  21462. var pp = this.parameterPositions,
  21463. iPrev = i1 - 2,
  21464. iNext = i1 + 1,
  21465. tPrev = pp[iPrev],
  21466. tNext = pp[iNext];
  21467. if (tPrev === undefined) {
  21468. switch (this.getSettings_().endingStart) {
  21469. case ZeroSlopeEnding:
  21470. // f'(t0) = 0
  21471. iPrev = i1;
  21472. tPrev = 2 * t0 - t1;
  21473. break;
  21474. case WrapAroundEnding:
  21475. // use the other end of the curve
  21476. iPrev = pp.length - 2;
  21477. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21478. break;
  21479. default:
  21480. // ZeroCurvatureEnding
  21481. // f''(t0) = 0 a.k.a. Natural Spline
  21482. iPrev = i1;
  21483. tPrev = t1;
  21484. }
  21485. }
  21486. if (tNext === undefined) {
  21487. switch (this.getSettings_().endingEnd) {
  21488. case ZeroSlopeEnding:
  21489. // f'(tN) = 0
  21490. iNext = i1;
  21491. tNext = 2 * t1 - t0;
  21492. break;
  21493. case WrapAroundEnding:
  21494. // use the other end of the curve
  21495. iNext = 1;
  21496. tNext = t1 + pp[1] - pp[0];
  21497. break;
  21498. default:
  21499. // ZeroCurvatureEnding
  21500. // f''(tN) = 0, a.k.a. Natural Spline
  21501. iNext = i1 - 1;
  21502. tNext = t0;
  21503. }
  21504. }
  21505. var halfDt = (t1 - t0) * 0.5,
  21506. stride = this.valueSize;
  21507. this._weightPrev = halfDt / (t0 - tPrev);
  21508. this._weightNext = halfDt / (tNext - t1);
  21509. this._offsetPrev = iPrev * stride;
  21510. this._offsetNext = iNext * stride;
  21511. },
  21512. interpolate_: function (i1, t0, t, t1) {
  21513. var result = this.resultBuffer,
  21514. values = this.sampleValues,
  21515. stride = this.valueSize,
  21516. o1 = i1 * stride,
  21517. o0 = o1 - stride,
  21518. oP = this._offsetPrev,
  21519. oN = this._offsetNext,
  21520. wP = this._weightPrev,
  21521. wN = this._weightNext,
  21522. p = (t - t0) / (t1 - t0),
  21523. pp = p * p,
  21524. ppp = pp * p; // evaluate polynomials
  21525. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  21526. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21527. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21528. var sN = wN * ppp - wN * pp; // combine data linearly
  21529. for (var i = 0; i !== stride; ++i) {
  21530. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21531. }
  21532. return result;
  21533. }
  21534. });
  21535. /**
  21536. * @author tschw
  21537. */
  21538. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21539. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21540. }
  21541. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21542. constructor: LinearInterpolant,
  21543. interpolate_: function (i1, t0, t, t1) {
  21544. var result = this.resultBuffer,
  21545. values = this.sampleValues,
  21546. stride = this.valueSize,
  21547. offset1 = i1 * stride,
  21548. offset0 = offset1 - stride,
  21549. weight1 = (t - t0) / (t1 - t0),
  21550. weight0 = 1 - weight1;
  21551. for (var i = 0; i !== stride; ++i) {
  21552. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21553. }
  21554. return result;
  21555. }
  21556. });
  21557. /**
  21558. *
  21559. * Interpolant that evaluates to the sample value at the position preceeding
  21560. * the parameter.
  21561. *
  21562. * @author tschw
  21563. */
  21564. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21565. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21566. }
  21567. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21568. constructor: DiscreteInterpolant,
  21569. interpolate_: function (i1
  21570. /*, t0, t, t1 */
  21571. ) {
  21572. return this.copySampleValue_(i1 - 1);
  21573. }
  21574. });
  21575. /**
  21576. *
  21577. * A timed sequence of keyframes for a specific property.
  21578. *
  21579. *
  21580. * @author Ben Houston / http://clara.io/
  21581. * @author David Sarno / http://lighthaus.us/
  21582. * @author tschw
  21583. */
  21584. function KeyframeTrack(name, times, values, interpolation) {
  21585. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21586. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21587. this.name = name;
  21588. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21589. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21590. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21591. } // Static methods
  21592. Object.assign(KeyframeTrack, {
  21593. // Serialization (in static context, because of constructor invocation
  21594. // and automatic invocation of .toJSON):
  21595. toJSON: function (track) {
  21596. var trackType = track.constructor;
  21597. var json; // derived classes can define a static toJSON method
  21598. if (trackType.toJSON !== undefined) {
  21599. json = trackType.toJSON(track);
  21600. } else {
  21601. // by default, we assume the data can be serialized as-is
  21602. json = {
  21603. 'name': track.name,
  21604. 'times': AnimationUtils.convertArray(track.times, Array),
  21605. 'values': AnimationUtils.convertArray(track.values, Array)
  21606. };
  21607. var interpolation = track.getInterpolation();
  21608. if (interpolation !== track.DefaultInterpolation) {
  21609. json.interpolation = interpolation;
  21610. }
  21611. }
  21612. json.type = track.ValueTypeName; // mandatory
  21613. return json;
  21614. }
  21615. });
  21616. Object.assign(KeyframeTrack.prototype, {
  21617. constructor: KeyframeTrack,
  21618. TimeBufferType: Float32Array,
  21619. ValueBufferType: Float32Array,
  21620. DefaultInterpolation: InterpolateLinear,
  21621. InterpolantFactoryMethodDiscrete: function (result) {
  21622. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21623. },
  21624. InterpolantFactoryMethodLinear: function (result) {
  21625. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21626. },
  21627. InterpolantFactoryMethodSmooth: function (result) {
  21628. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21629. },
  21630. setInterpolation: function (interpolation) {
  21631. var factoryMethod;
  21632. switch (interpolation) {
  21633. case InterpolateDiscrete:
  21634. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21635. break;
  21636. case InterpolateLinear:
  21637. factoryMethod = this.InterpolantFactoryMethodLinear;
  21638. break;
  21639. case InterpolateSmooth:
  21640. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21641. break;
  21642. }
  21643. if (factoryMethod === undefined) {
  21644. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21645. if (this.createInterpolant === undefined) {
  21646. // fall back to default, unless the default itself is messed up
  21647. if (interpolation !== this.DefaultInterpolation) {
  21648. this.setInterpolation(this.DefaultInterpolation);
  21649. } else {
  21650. throw new Error(message); // fatal, in this case
  21651. }
  21652. }
  21653. console.warn('THREE.KeyframeTrack:', message);
  21654. return this;
  21655. }
  21656. this.createInterpolant = factoryMethod;
  21657. return this;
  21658. },
  21659. getInterpolation: function () {
  21660. switch (this.createInterpolant) {
  21661. case this.InterpolantFactoryMethodDiscrete:
  21662. return InterpolateDiscrete;
  21663. case this.InterpolantFactoryMethodLinear:
  21664. return InterpolateLinear;
  21665. case this.InterpolantFactoryMethodSmooth:
  21666. return InterpolateSmooth;
  21667. }
  21668. },
  21669. getValueSize: function () {
  21670. return this.values.length / this.times.length;
  21671. },
  21672. // move all keyframes either forwards or backwards in time
  21673. shift: function (timeOffset) {
  21674. if (timeOffset !== 0.0) {
  21675. var times = this.times;
  21676. for (var i = 0, n = times.length; i !== n; ++i) {
  21677. times[i] += timeOffset;
  21678. }
  21679. }
  21680. return this;
  21681. },
  21682. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21683. scale: function (timeScale) {
  21684. if (timeScale !== 1.0) {
  21685. var times = this.times;
  21686. for (var i = 0, n = times.length; i !== n; ++i) {
  21687. times[i] *= timeScale;
  21688. }
  21689. }
  21690. return this;
  21691. },
  21692. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21693. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21694. trim: function (startTime, endTime) {
  21695. var times = this.times,
  21696. nKeys = times.length,
  21697. from = 0,
  21698. to = nKeys - 1;
  21699. while (from !== nKeys && times[from] < startTime) {
  21700. ++from;
  21701. }
  21702. while (to !== -1 && times[to] > endTime) {
  21703. --to;
  21704. }
  21705. ++to; // inclusive -> exclusive bound
  21706. if (from !== 0 || to !== nKeys) {
  21707. // empty tracks are forbidden, so keep at least one keyframe
  21708. if (from >= to) to = Math.max(to, 1), from = to - 1;
  21709. var stride = this.getValueSize();
  21710. this.times = AnimationUtils.arraySlice(times, from, to);
  21711. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21712. }
  21713. return this;
  21714. },
  21715. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21716. validate: function () {
  21717. var valid = true;
  21718. var valueSize = this.getValueSize();
  21719. if (valueSize - Math.floor(valueSize) !== 0) {
  21720. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21721. valid = false;
  21722. }
  21723. var times = this.times,
  21724. values = this.values,
  21725. nKeys = times.length;
  21726. if (nKeys === 0) {
  21727. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21728. valid = false;
  21729. }
  21730. var prevTime = null;
  21731. for (var i = 0; i !== nKeys; i++) {
  21732. var currTime = times[i];
  21733. if (typeof currTime === 'number' && isNaN(currTime)) {
  21734. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21735. valid = false;
  21736. break;
  21737. }
  21738. if (prevTime !== null && prevTime > currTime) {
  21739. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21740. valid = false;
  21741. break;
  21742. }
  21743. prevTime = currTime;
  21744. }
  21745. if (values !== undefined) {
  21746. if (AnimationUtils.isTypedArray(values)) {
  21747. for (var i = 0, n = values.length; i !== n; ++i) {
  21748. var value = values[i];
  21749. if (isNaN(value)) {
  21750. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21751. valid = false;
  21752. break;
  21753. }
  21754. }
  21755. }
  21756. }
  21757. return valid;
  21758. },
  21759. // removes equivalent sequential keys as common in morph target sequences
  21760. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21761. optimize: function () {
  21762. var times = this.times,
  21763. values = this.values,
  21764. stride = this.getValueSize(),
  21765. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21766. writeIndex = 1,
  21767. lastIndex = times.length - 1;
  21768. for (var i = 1; i < lastIndex; ++i) {
  21769. var keep = false;
  21770. var time = times[i];
  21771. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21772. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21773. if (!smoothInterpolation) {
  21774. // remove unnecessary keyframes same as their neighbors
  21775. var offset = i * stride,
  21776. offsetP = offset - stride,
  21777. offsetN = offset + stride;
  21778. for (var j = 0; j !== stride; ++j) {
  21779. var value = values[offset + j];
  21780. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21781. keep = true;
  21782. break;
  21783. }
  21784. }
  21785. } else {
  21786. keep = true;
  21787. }
  21788. } // in-place compaction
  21789. if (keep) {
  21790. if (i !== writeIndex) {
  21791. times[writeIndex] = times[i];
  21792. var readOffset = i * stride,
  21793. writeOffset = writeIndex * stride;
  21794. for (var j = 0; j !== stride; ++j) {
  21795. values[writeOffset + j] = values[readOffset + j];
  21796. }
  21797. }
  21798. ++writeIndex;
  21799. }
  21800. } // flush last keyframe (compaction looks ahead)
  21801. if (lastIndex > 0) {
  21802. times[writeIndex] = times[lastIndex];
  21803. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21804. values[writeOffset + j] = values[readOffset + j];
  21805. }
  21806. ++writeIndex;
  21807. }
  21808. if (writeIndex !== times.length) {
  21809. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21810. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21811. }
  21812. return this;
  21813. },
  21814. clone: function () {
  21815. var times = AnimationUtils.arraySlice(this.times, 0);
  21816. var values = AnimationUtils.arraySlice(this.values, 0);
  21817. var TypedKeyframeTrack = this.constructor;
  21818. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21819. track.createInterpolant = this.createInterpolant;
  21820. return track;
  21821. }
  21822. });
  21823. /**
  21824. *
  21825. * A Track of Boolean keyframe values.
  21826. *
  21827. *
  21828. * @author Ben Houston / http://clara.io/
  21829. * @author David Sarno / http://lighthaus.us/
  21830. * @author tschw
  21831. */
  21832. function BooleanKeyframeTrack(name, times, values) {
  21833. KeyframeTrack.call(this, name, times, values);
  21834. }
  21835. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21836. constructor: BooleanKeyframeTrack,
  21837. ValueTypeName: 'bool',
  21838. ValueBufferType: Array,
  21839. DefaultInterpolation: InterpolateDiscrete,
  21840. InterpolantFactoryMethodLinear: undefined,
  21841. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21842. // representation of a single value and a custom interpolant that
  21843. // computes "firstValue ^ isOdd( index )".
  21844. });
  21845. /**
  21846. *
  21847. * A Track of keyframe values that represent color.
  21848. *
  21849. *
  21850. * @author Ben Houston / http://clara.io/
  21851. * @author David Sarno / http://lighthaus.us/
  21852. * @author tschw
  21853. */
  21854. function ColorKeyframeTrack(name, times, values, interpolation) {
  21855. KeyframeTrack.call(this, name, times, values, interpolation);
  21856. }
  21857. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21858. constructor: ColorKeyframeTrack,
  21859. ValueTypeName: 'color' // ValueBufferType is inherited
  21860. // DefaultInterpolation is inherited
  21861. // Note: Very basic implementation and nothing special yet.
  21862. // However, this is the place for color space parameterization.
  21863. });
  21864. /**
  21865. *
  21866. * A Track of numeric keyframe values.
  21867. *
  21868. * @author Ben Houston / http://clara.io/
  21869. * @author David Sarno / http://lighthaus.us/
  21870. * @author tschw
  21871. */
  21872. function NumberKeyframeTrack(name, times, values, interpolation) {
  21873. KeyframeTrack.call(this, name, times, values, interpolation);
  21874. }
  21875. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21876. constructor: NumberKeyframeTrack,
  21877. ValueTypeName: 'number' // ValueBufferType is inherited
  21878. // DefaultInterpolation is inherited
  21879. });
  21880. /**
  21881. * Spherical linear unit quaternion interpolant.
  21882. *
  21883. * @author tschw
  21884. */
  21885. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21886. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21887. }
  21888. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21889. constructor: QuaternionLinearInterpolant,
  21890. interpolate_: function (i1, t0, t, t1) {
  21891. var result = this.resultBuffer,
  21892. values = this.sampleValues,
  21893. stride = this.valueSize,
  21894. offset = i1 * stride,
  21895. alpha = (t - t0) / (t1 - t0);
  21896. for (var end = offset + stride; offset !== end; offset += 4) {
  21897. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21898. }
  21899. return result;
  21900. }
  21901. });
  21902. /**
  21903. *
  21904. * A Track of quaternion keyframe values.
  21905. *
  21906. * @author Ben Houston / http://clara.io/
  21907. * @author David Sarno / http://lighthaus.us/
  21908. * @author tschw
  21909. */
  21910. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21911. KeyframeTrack.call(this, name, times, values, interpolation);
  21912. }
  21913. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21914. constructor: QuaternionKeyframeTrack,
  21915. ValueTypeName: 'quaternion',
  21916. // ValueBufferType is inherited
  21917. DefaultInterpolation: InterpolateLinear,
  21918. InterpolantFactoryMethodLinear: function (result) {
  21919. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21920. },
  21921. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21922. });
  21923. /**
  21924. *
  21925. * A Track that interpolates Strings
  21926. *
  21927. *
  21928. * @author Ben Houston / http://clara.io/
  21929. * @author David Sarno / http://lighthaus.us/
  21930. * @author tschw
  21931. */
  21932. function StringKeyframeTrack(name, times, values, interpolation) {
  21933. KeyframeTrack.call(this, name, times, values, interpolation);
  21934. }
  21935. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21936. constructor: StringKeyframeTrack,
  21937. ValueTypeName: 'string',
  21938. ValueBufferType: Array,
  21939. DefaultInterpolation: InterpolateDiscrete,
  21940. InterpolantFactoryMethodLinear: undefined,
  21941. InterpolantFactoryMethodSmooth: undefined
  21942. });
  21943. /**
  21944. *
  21945. * A Track of vectored keyframe values.
  21946. *
  21947. *
  21948. * @author Ben Houston / http://clara.io/
  21949. * @author David Sarno / http://lighthaus.us/
  21950. * @author tschw
  21951. */
  21952. function VectorKeyframeTrack(name, times, values, interpolation) {
  21953. KeyframeTrack.call(this, name, times, values, interpolation);
  21954. }
  21955. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21956. constructor: VectorKeyframeTrack,
  21957. ValueTypeName: 'vector' // ValueBufferType is inherited
  21958. // DefaultInterpolation is inherited
  21959. });
  21960. /**
  21961. *
  21962. * Reusable set of Tracks that represent an animation.
  21963. *
  21964. * @author Ben Houston / http://clara.io/
  21965. * @author David Sarno / http://lighthaus.us/
  21966. */
  21967. function AnimationClip(name, duration, tracks) {
  21968. this.name = name;
  21969. this.tracks = tracks;
  21970. this.duration = duration !== undefined ? duration : -1;
  21971. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21972. if (this.duration < 0) {
  21973. this.resetDuration();
  21974. }
  21975. }
  21976. function getTrackTypeForValueTypeName(typeName) {
  21977. switch (typeName.toLowerCase()) {
  21978. case 'scalar':
  21979. case 'double':
  21980. case 'float':
  21981. case 'number':
  21982. case 'integer':
  21983. return NumberKeyframeTrack;
  21984. case 'vector':
  21985. case 'vector2':
  21986. case 'vector3':
  21987. case 'vector4':
  21988. return VectorKeyframeTrack;
  21989. case 'color':
  21990. return ColorKeyframeTrack;
  21991. case 'quaternion':
  21992. return QuaternionKeyframeTrack;
  21993. case 'bool':
  21994. case 'boolean':
  21995. return BooleanKeyframeTrack;
  21996. case 'string':
  21997. return StringKeyframeTrack;
  21998. }
  21999. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22000. }
  22001. function parseKeyframeTrack(json) {
  22002. if (json.type === undefined) {
  22003. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22004. }
  22005. var trackType = getTrackTypeForValueTypeName(json.type);
  22006. if (json.times === undefined) {
  22007. var times = [],
  22008. values = [];
  22009. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22010. json.times = times;
  22011. json.values = values;
  22012. } // derived classes can define a static parse method
  22013. if (trackType.parse !== undefined) {
  22014. return trackType.parse(json);
  22015. } else {
  22016. // by default, we assume a constructor compatible with the base
  22017. return new trackType(json.name, json.times, json.values, json.interpolation);
  22018. }
  22019. }
  22020. Object.assign(AnimationClip, {
  22021. parse: function (json) {
  22022. var tracks = [],
  22023. jsonTracks = json.tracks,
  22024. frameTime = 1.0 / (json.fps || 1.0);
  22025. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  22026. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22027. }
  22028. return new AnimationClip(json.name, json.duration, tracks);
  22029. },
  22030. toJSON: function (clip) {
  22031. var tracks = [],
  22032. clipTracks = clip.tracks;
  22033. var json = {
  22034. 'name': clip.name,
  22035. 'duration': clip.duration,
  22036. 'tracks': tracks,
  22037. 'uuid': clip.uuid
  22038. };
  22039. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  22040. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22041. }
  22042. return json;
  22043. },
  22044. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  22045. var numMorphTargets = morphTargetSequence.length;
  22046. var tracks = [];
  22047. for (var i = 0; i < numMorphTargets; i++) {
  22048. var times = [];
  22049. var values = [];
  22050. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22051. values.push(0, 1, 0);
  22052. var order = AnimationUtils.getKeyframeOrder(times);
  22053. times = AnimationUtils.sortedArray(times, 1, order);
  22054. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22055. // last frame as well for perfect loop.
  22056. if (!noLoop && times[0] === 0) {
  22057. times.push(numMorphTargets);
  22058. values.push(values[0]);
  22059. }
  22060. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22061. }
  22062. return new AnimationClip(name, -1, tracks);
  22063. },
  22064. findByName: function (objectOrClipArray, name) {
  22065. var clipArray = objectOrClipArray;
  22066. if (!Array.isArray(objectOrClipArray)) {
  22067. var o = objectOrClipArray;
  22068. clipArray = o.geometry && o.geometry.animations || o.animations;
  22069. }
  22070. for (var i = 0; i < clipArray.length; i++) {
  22071. if (clipArray[i].name === name) {
  22072. return clipArray[i];
  22073. }
  22074. }
  22075. return null;
  22076. },
  22077. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  22078. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22079. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22080. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22081. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22082. for (var i = 0, il = morphTargets.length; i < il; i++) {
  22083. var morphTarget = morphTargets[i];
  22084. var parts = morphTarget.name.match(pattern);
  22085. if (parts && parts.length > 1) {
  22086. var name = parts[1];
  22087. var animationMorphTargets = animationToMorphTargets[name];
  22088. if (!animationMorphTargets) {
  22089. animationToMorphTargets[name] = animationMorphTargets = [];
  22090. }
  22091. animationMorphTargets.push(morphTarget);
  22092. }
  22093. }
  22094. var clips = [];
  22095. for (var name in animationToMorphTargets) {
  22096. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22097. }
  22098. return clips;
  22099. },
  22100. // parse the animation.hierarchy format
  22101. parseAnimation: function (animation, bones) {
  22102. if (!animation) {
  22103. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22104. return null;
  22105. }
  22106. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22107. // only return track if there are actually keys.
  22108. if (animationKeys.length !== 0) {
  22109. var times = [];
  22110. var values = [];
  22111. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22112. if (times.length !== 0) {
  22113. destTracks.push(new trackType(trackName, times, values));
  22114. }
  22115. }
  22116. };
  22117. var tracks = [];
  22118. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  22119. var duration = animation.length || -1;
  22120. var fps = animation.fps || 30;
  22121. var hierarchyTracks = animation.hierarchy || [];
  22122. for (var h = 0; h < hierarchyTracks.length; h++) {
  22123. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22124. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22125. if (animationKeys[0].morphTargets) {
  22126. // figure out all morph targets used in this track
  22127. var morphTargetNames = {};
  22128. for (var k = 0; k < animationKeys.length; k++) {
  22129. if (animationKeys[k].morphTargets) {
  22130. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22131. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22132. }
  22133. }
  22134. } // create a track for each morph target with all zero
  22135. // morphTargetInfluences except for the keys in which
  22136. // the morphTarget is named.
  22137. for (var morphTargetName in morphTargetNames) {
  22138. var times = [];
  22139. var values = [];
  22140. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22141. var animationKey = animationKeys[k];
  22142. times.push(animationKey.time);
  22143. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22144. }
  22145. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22146. }
  22147. duration = morphTargetNames.length * (fps || 1.0);
  22148. } else {
  22149. // ...assume skeletal animation
  22150. var boneName = '.bones[' + bones[h].name + ']';
  22151. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22152. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22153. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22154. }
  22155. }
  22156. if (tracks.length === 0) {
  22157. return null;
  22158. }
  22159. var clip = new AnimationClip(clipName, duration, tracks);
  22160. return clip;
  22161. }
  22162. });
  22163. Object.assign(AnimationClip.prototype, {
  22164. resetDuration: function () {
  22165. var tracks = this.tracks,
  22166. duration = 0;
  22167. for (var i = 0, n = tracks.length; i !== n; ++i) {
  22168. var track = this.tracks[i];
  22169. duration = Math.max(duration, track.times[track.times.length - 1]);
  22170. }
  22171. this.duration = duration;
  22172. return this;
  22173. },
  22174. trim: function () {
  22175. for (var i = 0; i < this.tracks.length; i++) {
  22176. this.tracks[i].trim(0, this.duration);
  22177. }
  22178. return this;
  22179. },
  22180. validate: function () {
  22181. var valid = true;
  22182. for (var i = 0; i < this.tracks.length; i++) {
  22183. valid = valid && this.tracks[i].validate();
  22184. }
  22185. return valid;
  22186. },
  22187. optimize: function () {
  22188. for (var i = 0; i < this.tracks.length; i++) {
  22189. this.tracks[i].optimize();
  22190. }
  22191. return this;
  22192. },
  22193. clone: function () {
  22194. var tracks = [];
  22195. for (var i = 0; i < this.tracks.length; i++) {
  22196. tracks.push(this.tracks[i].clone());
  22197. }
  22198. return new AnimationClip(this.name, this.duration, tracks);
  22199. }
  22200. });
  22201. /**
  22202. * @author mrdoob / http://mrdoob.com/
  22203. */
  22204. var Cache = {
  22205. enabled: false,
  22206. files: {},
  22207. add: function (key, file) {
  22208. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22209. this.files[key] = file;
  22210. },
  22211. get: function (key) {
  22212. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22213. return this.files[key];
  22214. },
  22215. remove: function (key) {
  22216. delete this.files[key];
  22217. },
  22218. clear: function () {
  22219. this.files = {};
  22220. }
  22221. };
  22222. /**
  22223. * @author mrdoob / http://mrdoob.com/
  22224. */
  22225. exports.Cache = Cache;
  22226. function LoadingManager(onLoad, onProgress, onError) {
  22227. var scope = this;
  22228. var isLoading = false;
  22229. var itemsLoaded = 0;
  22230. var itemsTotal = 0;
  22231. var urlModifier = undefined;
  22232. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22233. // in the constructor
  22234. this.onStart = undefined;
  22235. this.onLoad = onLoad;
  22236. this.onProgress = onProgress;
  22237. this.onError = onError;
  22238. this.itemStart = function (url) {
  22239. itemsTotal++;
  22240. if (isLoading === false) {
  22241. if (scope.onStart !== undefined) {
  22242. scope.onStart(url, itemsLoaded, itemsTotal);
  22243. }
  22244. }
  22245. isLoading = true;
  22246. };
  22247. this.itemEnd = function (url) {
  22248. itemsLoaded++;
  22249. if (scope.onProgress !== undefined) {
  22250. scope.onProgress(url, itemsLoaded, itemsTotal);
  22251. }
  22252. if (itemsLoaded === itemsTotal) {
  22253. isLoading = false;
  22254. if (scope.onLoad !== undefined) {
  22255. scope.onLoad();
  22256. }
  22257. }
  22258. };
  22259. this.itemError = function (url) {
  22260. if (scope.onError !== undefined) {
  22261. scope.onError(url);
  22262. }
  22263. };
  22264. this.resolveURL = function (url) {
  22265. if (urlModifier) {
  22266. return urlModifier(url);
  22267. }
  22268. return url;
  22269. };
  22270. this.setURLModifier = function (transform) {
  22271. urlModifier = transform;
  22272. return this;
  22273. };
  22274. this.addHandler = function (regex, loader) {
  22275. handlers.push(regex, loader);
  22276. return this;
  22277. };
  22278. this.removeHandler = function (regex) {
  22279. var index = handlers.indexOf(regex);
  22280. if (index !== -1) {
  22281. handlers.splice(index, 2);
  22282. }
  22283. return this;
  22284. };
  22285. this.getHandler = function (file) {
  22286. for (var i = 0, l = handlers.length; i < l; i += 2) {
  22287. var regex = handlers[i];
  22288. var loader = handlers[i + 1];
  22289. if (regex.test(file)) {
  22290. return loader;
  22291. }
  22292. }
  22293. return null;
  22294. };
  22295. }
  22296. var DefaultLoadingManager = new LoadingManager();
  22297. /**
  22298. * @author alteredq / http://alteredqualia.com/
  22299. */
  22300. exports.DefaultLoadingManager = DefaultLoadingManager;
  22301. function Loader(manager) {
  22302. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22303. this.crossOrigin = 'anonymous';
  22304. this.path = '';
  22305. this.resourcePath = '';
  22306. }
  22307. Object.assign(Loader.prototype, {
  22308. load: function ()
  22309. /* url, onLoad, onProgress, onError */
  22310. {},
  22311. parse: function ()
  22312. /* data */
  22313. {},
  22314. setCrossOrigin: function (crossOrigin) {
  22315. this.crossOrigin = crossOrigin;
  22316. return this;
  22317. },
  22318. setPath: function (path) {
  22319. this.path = path;
  22320. return this;
  22321. },
  22322. setResourcePath: function (resourcePath) {
  22323. this.resourcePath = resourcePath;
  22324. return this;
  22325. }
  22326. });
  22327. /**
  22328. * @author mrdoob / http://mrdoob.com/
  22329. */
  22330. var loading = {};
  22331. function FileLoader(manager) {
  22332. Loader.call(this, manager);
  22333. }
  22334. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22335. constructor: FileLoader,
  22336. load: function (url, onLoad, onProgress, onError) {
  22337. if (url === undefined) url = '';
  22338. if (this.path !== undefined) url = this.path + url;
  22339. url = this.manager.resolveURL(url);
  22340. var scope = this;
  22341. var cached = Cache.get(url);
  22342. if (cached !== undefined) {
  22343. scope.manager.itemStart(url);
  22344. setTimeout(function () {
  22345. if (onLoad) onLoad(cached);
  22346. scope.manager.itemEnd(url);
  22347. }, 0);
  22348. return cached;
  22349. } // Check if request is duplicate
  22350. if (loading[url] !== undefined) {
  22351. loading[url].push({
  22352. onLoad: onLoad,
  22353. onProgress: onProgress,
  22354. onError: onError
  22355. });
  22356. return;
  22357. } // Check for data: URI
  22358. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22359. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22360. if (dataUriRegexResult) {
  22361. var mimeType = dataUriRegexResult[1];
  22362. var isBase64 = !!dataUriRegexResult[2];
  22363. var data = dataUriRegexResult[3];
  22364. data = decodeURIComponent(data);
  22365. if (isBase64) data = atob(data);
  22366. try {
  22367. var response;
  22368. var responseType = (this.responseType || '').toLowerCase();
  22369. switch (responseType) {
  22370. case 'arraybuffer':
  22371. case 'blob':
  22372. var view = new Uint8Array(data.length);
  22373. for (var i = 0; i < data.length; i++) {
  22374. view[i] = data.charCodeAt(i);
  22375. }
  22376. if (responseType === 'blob') {
  22377. response = new Blob([view.buffer], {
  22378. type: mimeType
  22379. });
  22380. } else {
  22381. response = view.buffer;
  22382. }
  22383. break;
  22384. case 'document':
  22385. var parser = new DOMParser();
  22386. response = parser.parseFromString(data, mimeType);
  22387. break;
  22388. case 'json':
  22389. response = JSON.parse(data);
  22390. break;
  22391. default:
  22392. // 'text' or other
  22393. response = data;
  22394. break;
  22395. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22396. setTimeout(function () {
  22397. if (onLoad) onLoad(response);
  22398. scope.manager.itemEnd(url);
  22399. }, 0);
  22400. } catch (error) {
  22401. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22402. setTimeout(function () {
  22403. if (onError) onError(error);
  22404. scope.manager.itemError(url);
  22405. scope.manager.itemEnd(url);
  22406. }, 0);
  22407. }
  22408. } else {
  22409. // Initialise array for duplicate requests
  22410. loading[url] = [];
  22411. loading[url].push({
  22412. onLoad: onLoad,
  22413. onProgress: onProgress,
  22414. onError: onError
  22415. });
  22416. var request = new XMLHttpRequest();
  22417. request.open('GET', url, true);
  22418. request.addEventListener('load', function (event) {
  22419. var response = this.response;
  22420. Cache.add(url, response);
  22421. var callbacks = loading[url];
  22422. delete loading[url];
  22423. if (this.status === 200 || this.status === 0) {
  22424. // Some browsers return HTTP Status 0 when using non-http protocol
  22425. // e.g. 'file://' or 'data://'. Handle as success.
  22426. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22427. for (var i = 0, il = callbacks.length; i < il; i++) {
  22428. var callback = callbacks[i];
  22429. if (callback.onLoad) callback.onLoad(response);
  22430. }
  22431. scope.manager.itemEnd(url);
  22432. } else {
  22433. for (var i = 0, il = callbacks.length; i < il; i++) {
  22434. var callback = callbacks[i];
  22435. if (callback.onError) callback.onError(event);
  22436. }
  22437. scope.manager.itemError(url);
  22438. scope.manager.itemEnd(url);
  22439. }
  22440. }, false);
  22441. request.addEventListener('progress', function (event) {
  22442. var callbacks = loading[url];
  22443. for (var i = 0, il = callbacks.length; i < il; i++) {
  22444. var callback = callbacks[i];
  22445. if (callback.onProgress) callback.onProgress(event);
  22446. }
  22447. }, false);
  22448. request.addEventListener('error', function (event) {
  22449. var callbacks = loading[url];
  22450. delete loading[url];
  22451. for (var i = 0, il = callbacks.length; i < il; i++) {
  22452. var callback = callbacks[i];
  22453. if (callback.onError) callback.onError(event);
  22454. }
  22455. scope.manager.itemError(url);
  22456. scope.manager.itemEnd(url);
  22457. }, false);
  22458. request.addEventListener('abort', function (event) {
  22459. var callbacks = loading[url];
  22460. delete loading[url];
  22461. for (var i = 0, il = callbacks.length; i < il; i++) {
  22462. var callback = callbacks[i];
  22463. if (callback.onError) callback.onError(event);
  22464. }
  22465. scope.manager.itemError(url);
  22466. scope.manager.itemEnd(url);
  22467. }, false);
  22468. if (this.responseType !== undefined) request.responseType = this.responseType;
  22469. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22470. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22471. for (var header in this.requestHeader) {
  22472. request.setRequestHeader(header, this.requestHeader[header]);
  22473. }
  22474. request.send(null);
  22475. }
  22476. scope.manager.itemStart(url);
  22477. return request;
  22478. },
  22479. setResponseType: function (value) {
  22480. this.responseType = value;
  22481. return this;
  22482. },
  22483. setWithCredentials: function (value) {
  22484. this.withCredentials = value;
  22485. return this;
  22486. },
  22487. setMimeType: function (value) {
  22488. this.mimeType = value;
  22489. return this;
  22490. },
  22491. setRequestHeader: function (value) {
  22492. this.requestHeader = value;
  22493. return this;
  22494. }
  22495. });
  22496. /**
  22497. * @author bhouston / http://clara.io/
  22498. */
  22499. function AnimationLoader(manager) {
  22500. Loader.call(this, manager);
  22501. }
  22502. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22503. constructor: AnimationLoader,
  22504. load: function (url, onLoad, onProgress, onError) {
  22505. var scope = this;
  22506. var loader = new FileLoader(scope.manager);
  22507. loader.setPath(scope.path);
  22508. loader.load(url, function (text) {
  22509. onLoad(scope.parse(JSON.parse(text)));
  22510. }, onProgress, onError);
  22511. },
  22512. parse: function (json) {
  22513. var animations = [];
  22514. for (var i = 0; i < json.length; i++) {
  22515. var clip = AnimationClip.parse(json[i]);
  22516. animations.push(clip);
  22517. }
  22518. return animations;
  22519. }
  22520. });
  22521. /**
  22522. * @author mrdoob / http://mrdoob.com/
  22523. *
  22524. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22525. *
  22526. * Sub classes have to implement the parse() method which will be used in load().
  22527. */
  22528. function CompressedTextureLoader(manager) {
  22529. Loader.call(this, manager);
  22530. }
  22531. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22532. constructor: CompressedTextureLoader,
  22533. load: function (url, onLoad, onProgress, onError) {
  22534. var scope = this;
  22535. var images = [];
  22536. var texture = new CompressedTexture();
  22537. texture.image = images;
  22538. var loader = new FileLoader(this.manager);
  22539. loader.setPath(this.path);
  22540. loader.setResponseType('arraybuffer');
  22541. function loadTexture(i) {
  22542. loader.load(url[i], function (buffer) {
  22543. var texDatas = scope.parse(buffer, true);
  22544. images[i] = {
  22545. width: texDatas.width,
  22546. height: texDatas.height,
  22547. format: texDatas.format,
  22548. mipmaps: texDatas.mipmaps
  22549. };
  22550. loaded += 1;
  22551. if (loaded === 6) {
  22552. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22553. texture.format = texDatas.format;
  22554. texture.needsUpdate = true;
  22555. if (onLoad) onLoad(texture);
  22556. }
  22557. }, onProgress, onError);
  22558. }
  22559. if (Array.isArray(url)) {
  22560. var loaded = 0;
  22561. for (var i = 0, il = url.length; i < il; ++i) {
  22562. loadTexture(i);
  22563. }
  22564. } else {
  22565. // compressed cubemap texture stored in a single DDS file
  22566. loader.load(url, function (buffer) {
  22567. var texDatas = scope.parse(buffer, true);
  22568. if (texDatas.isCubemap) {
  22569. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22570. for (var f = 0; f < faces; f++) {
  22571. images[f] = {
  22572. mipmaps: []
  22573. };
  22574. for (var i = 0; i < texDatas.mipmapCount; i++) {
  22575. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22576. images[f].format = texDatas.format;
  22577. images[f].width = texDatas.width;
  22578. images[f].height = texDatas.height;
  22579. }
  22580. }
  22581. } else {
  22582. texture.image.width = texDatas.width;
  22583. texture.image.height = texDatas.height;
  22584. texture.mipmaps = texDatas.mipmaps;
  22585. }
  22586. if (texDatas.mipmapCount === 1) {
  22587. texture.minFilter = LinearFilter;
  22588. }
  22589. texture.format = texDatas.format;
  22590. texture.needsUpdate = true;
  22591. if (onLoad) onLoad(texture);
  22592. }, onProgress, onError);
  22593. }
  22594. return texture;
  22595. }
  22596. });
  22597. /**
  22598. * @author Nikos M. / https://github.com/foo123/
  22599. *
  22600. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22601. *
  22602. * Sub classes have to implement the parse() method which will be used in load().
  22603. */
  22604. function DataTextureLoader(manager) {
  22605. Loader.call(this, manager);
  22606. }
  22607. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22608. constructor: DataTextureLoader,
  22609. load: function (url, onLoad, onProgress, onError) {
  22610. var scope = this;
  22611. var texture = new DataTexture();
  22612. var loader = new FileLoader(this.manager);
  22613. loader.setResponseType('arraybuffer');
  22614. loader.setPath(this.path);
  22615. loader.load(url, function (buffer) {
  22616. var texData = scope.parse(buffer);
  22617. if (!texData) return;
  22618. if (texData.image !== undefined) {
  22619. texture.image = texData.image;
  22620. } else if (texData.data !== undefined) {
  22621. texture.image.width = texData.width;
  22622. texture.image.height = texData.height;
  22623. texture.image.data = texData.data;
  22624. }
  22625. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22626. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22627. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22628. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  22629. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22630. if (texData.format !== undefined) {
  22631. texture.format = texData.format;
  22632. }
  22633. if (texData.type !== undefined) {
  22634. texture.type = texData.type;
  22635. }
  22636. if (texData.mipmaps !== undefined) {
  22637. texture.mipmaps = texData.mipmaps;
  22638. }
  22639. if (texData.mipmapCount === 1) {
  22640. texture.minFilter = LinearFilter;
  22641. }
  22642. texture.needsUpdate = true;
  22643. if (onLoad) onLoad(texture, texData);
  22644. }, onProgress, onError);
  22645. return texture;
  22646. }
  22647. });
  22648. /**
  22649. * @author mrdoob / http://mrdoob.com/
  22650. */
  22651. function ImageLoader(manager) {
  22652. Loader.call(this, manager);
  22653. }
  22654. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22655. constructor: ImageLoader,
  22656. load: function (url, onLoad, onProgress, onError) {
  22657. if (this.path !== undefined) url = this.path + url;
  22658. url = this.manager.resolveURL(url);
  22659. var scope = this;
  22660. var cached = Cache.get(url);
  22661. if (cached !== undefined) {
  22662. scope.manager.itemStart(url);
  22663. setTimeout(function () {
  22664. if (onLoad) onLoad(cached);
  22665. scope.manager.itemEnd(url);
  22666. }, 0);
  22667. return cached;
  22668. }
  22669. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22670. function onImageLoad() {
  22671. image.removeEventListener('load', onImageLoad, false);
  22672. image.removeEventListener('error', onImageError, false);
  22673. Cache.add(url, this);
  22674. if (onLoad) onLoad(this);
  22675. scope.manager.itemEnd(url);
  22676. }
  22677. function onImageError(event) {
  22678. image.removeEventListener('load', onImageLoad, false);
  22679. image.removeEventListener('error', onImageError, false);
  22680. if (onError) onError(event);
  22681. scope.manager.itemError(url);
  22682. scope.manager.itemEnd(url);
  22683. }
  22684. image.addEventListener('load', onImageLoad, false);
  22685. image.addEventListener('error', onImageError, false);
  22686. if (url.substr(0, 5) !== 'data:') {
  22687. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22688. }
  22689. scope.manager.itemStart(url);
  22690. image.src = url;
  22691. return image;
  22692. }
  22693. });
  22694. /**
  22695. * @author mrdoob / http://mrdoob.com/
  22696. */
  22697. function CubeTextureLoader(manager) {
  22698. Loader.call(this, manager);
  22699. }
  22700. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22701. constructor: CubeTextureLoader,
  22702. load: function (urls, onLoad, onProgress, onError) {
  22703. var texture = new CubeTexture();
  22704. var loader = new ImageLoader(this.manager);
  22705. loader.setCrossOrigin(this.crossOrigin);
  22706. loader.setPath(this.path);
  22707. var loaded = 0;
  22708. function loadTexture(i) {
  22709. loader.load(urls[i], function (image) {
  22710. texture.images[i] = image;
  22711. loaded++;
  22712. if (loaded === 6) {
  22713. texture.needsUpdate = true;
  22714. if (onLoad) onLoad(texture);
  22715. }
  22716. }, undefined, onError);
  22717. }
  22718. for (var i = 0; i < urls.length; ++i) {
  22719. loadTexture(i);
  22720. }
  22721. return texture;
  22722. }
  22723. });
  22724. /**
  22725. * @author mrdoob / http://mrdoob.com/
  22726. */
  22727. function TextureLoader(manager) {
  22728. Loader.call(this, manager);
  22729. }
  22730. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22731. constructor: TextureLoader,
  22732. load: function (url, onLoad, onProgress, onError) {
  22733. var texture = new Texture();
  22734. var loader = new ImageLoader(this.manager);
  22735. loader.setCrossOrigin(this.crossOrigin);
  22736. loader.setPath(this.path);
  22737. loader.load(url, function (image) {
  22738. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22739. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22740. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22741. texture.needsUpdate = true;
  22742. if (onLoad !== undefined) {
  22743. onLoad(texture);
  22744. }
  22745. }, onProgress, onError);
  22746. return texture;
  22747. }
  22748. });
  22749. /**
  22750. * @author zz85 / http://www.lab4games.net/zz85/blog
  22751. * Extensible curve object
  22752. *
  22753. * Some common of curve methods:
  22754. * .getPoint( t, optionalTarget ), .getTangent( t )
  22755. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22756. * .getPoints(), .getSpacedPoints()
  22757. * .getLength()
  22758. * .updateArcLengths()
  22759. *
  22760. * This following curves inherit from THREE.Curve:
  22761. *
  22762. * -- 2D curves --
  22763. * THREE.ArcCurve
  22764. * THREE.CubicBezierCurve
  22765. * THREE.EllipseCurve
  22766. * THREE.LineCurve
  22767. * THREE.QuadraticBezierCurve
  22768. * THREE.SplineCurve
  22769. *
  22770. * -- 3D curves --
  22771. * THREE.CatmullRomCurve3
  22772. * THREE.CubicBezierCurve3
  22773. * THREE.LineCurve3
  22774. * THREE.QuadraticBezierCurve3
  22775. *
  22776. * A series of curves can be represented as a THREE.CurvePath.
  22777. *
  22778. **/
  22779. /**************************************************************
  22780. * Abstract Curve base class
  22781. **************************************************************/
  22782. function Curve() {
  22783. this.type = 'Curve';
  22784. this.arcLengthDivisions = 200;
  22785. }
  22786. Object.assign(Curve.prototype, {
  22787. // Virtual base class method to overwrite and implement in subclasses
  22788. // - t [0 .. 1]
  22789. getPoint: function ()
  22790. /* t, optionalTarget */
  22791. {
  22792. console.warn('THREE.Curve: .getPoint() not implemented.');
  22793. return null;
  22794. },
  22795. // Get point at relative position in curve according to arc length
  22796. // - u [0 .. 1]
  22797. getPointAt: function (u, optionalTarget) {
  22798. var t = this.getUtoTmapping(u);
  22799. return this.getPoint(t, optionalTarget);
  22800. },
  22801. // Get sequence of points using getPoint( t )
  22802. getPoints: function (divisions) {
  22803. if (divisions === undefined) divisions = 5;
  22804. var points = [];
  22805. for (var d = 0; d <= divisions; d++) {
  22806. points.push(this.getPoint(d / divisions));
  22807. }
  22808. return points;
  22809. },
  22810. // Get sequence of points using getPointAt( u )
  22811. getSpacedPoints: function (divisions) {
  22812. if (divisions === undefined) divisions = 5;
  22813. var points = [];
  22814. for (var d = 0; d <= divisions; d++) {
  22815. points.push(this.getPointAt(d / divisions));
  22816. }
  22817. return points;
  22818. },
  22819. // Get total curve arc length
  22820. getLength: function () {
  22821. var lengths = this.getLengths();
  22822. return lengths[lengths.length - 1];
  22823. },
  22824. // Get list of cumulative segment lengths
  22825. getLengths: function (divisions) {
  22826. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22827. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22828. return this.cacheArcLengths;
  22829. }
  22830. this.needsUpdate = false;
  22831. var cache = [];
  22832. var current,
  22833. last = this.getPoint(0);
  22834. var p,
  22835. sum = 0;
  22836. cache.push(0);
  22837. for (p = 1; p <= divisions; p++) {
  22838. current = this.getPoint(p / divisions);
  22839. sum += current.distanceTo(last);
  22840. cache.push(sum);
  22841. last = current;
  22842. }
  22843. this.cacheArcLengths = cache;
  22844. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22845. },
  22846. updateArcLengths: function () {
  22847. this.needsUpdate = true;
  22848. this.getLengths();
  22849. },
  22850. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22851. getUtoTmapping: function (u, distance) {
  22852. var arcLengths = this.getLengths();
  22853. var i = 0,
  22854. il = arcLengths.length;
  22855. var targetArcLength; // The targeted u distance value to get
  22856. if (distance) {
  22857. targetArcLength = distance;
  22858. } else {
  22859. targetArcLength = u * arcLengths[il - 1];
  22860. } // binary search for the index with largest value smaller than target u distance
  22861. var low = 0,
  22862. high = il - 1,
  22863. comparison;
  22864. while (low <= high) {
  22865. 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
  22866. comparison = arcLengths[i] - targetArcLength;
  22867. if (comparison < 0) {
  22868. low = i + 1;
  22869. } else if (comparison > 0) {
  22870. high = i - 1;
  22871. } else {
  22872. high = i;
  22873. break; // DONE
  22874. }
  22875. }
  22876. i = high;
  22877. if (arcLengths[i] === targetArcLength) {
  22878. return i / (il - 1);
  22879. } // we could get finer grain at lengths, or use simple interpolation between two points
  22880. var lengthBefore = arcLengths[i];
  22881. var lengthAfter = arcLengths[i + 1];
  22882. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22883. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22884. var t = (i + segmentFraction) / (il - 1);
  22885. return t;
  22886. },
  22887. // Returns a unit vector tangent at t
  22888. // In case any sub curve does not implement its tangent derivation,
  22889. // 2 points a small delta apart will be used to find its gradient
  22890. // which seems to give a reasonable approximation
  22891. getTangent: function (t) {
  22892. var delta = 0.0001;
  22893. var t1 = t - delta;
  22894. var t2 = t + delta; // Capping in case of danger
  22895. if (t1 < 0) t1 = 0;
  22896. if (t2 > 1) t2 = 1;
  22897. var pt1 = this.getPoint(t1);
  22898. var pt2 = this.getPoint(t2);
  22899. var vec = pt2.clone().sub(pt1);
  22900. return vec.normalize();
  22901. },
  22902. getTangentAt: function (u) {
  22903. var t = this.getUtoTmapping(u);
  22904. return this.getTangent(t);
  22905. },
  22906. computeFrenetFrames: function (segments, closed) {
  22907. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22908. var normal = new Vector3();
  22909. var tangents = [];
  22910. var normals = [];
  22911. var binormals = [];
  22912. var vec = new Vector3();
  22913. var mat = new Matrix4();
  22914. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22915. for (i = 0; i <= segments; i++) {
  22916. u = i / segments;
  22917. tangents[i] = this.getTangentAt(u);
  22918. tangents[i].normalize();
  22919. } // select an initial normal vector perpendicular to the first tangent vector,
  22920. // and in the direction of the minimum tangent xyz component
  22921. normals[0] = new Vector3();
  22922. binormals[0] = new Vector3();
  22923. var min = Number.MAX_VALUE;
  22924. var tx = Math.abs(tangents[0].x);
  22925. var ty = Math.abs(tangents[0].y);
  22926. var tz = Math.abs(tangents[0].z);
  22927. if (tx <= min) {
  22928. min = tx;
  22929. normal.set(1, 0, 0);
  22930. }
  22931. if (ty <= min) {
  22932. min = ty;
  22933. normal.set(0, 1, 0);
  22934. }
  22935. if (tz <= min) {
  22936. normal.set(0, 0, 1);
  22937. }
  22938. vec.crossVectors(tangents[0], normal).normalize();
  22939. normals[0].crossVectors(tangents[0], vec);
  22940. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22941. for (i = 1; i <= segments; i++) {
  22942. normals[i] = normals[i - 1].clone();
  22943. binormals[i] = binormals[i - 1].clone();
  22944. vec.crossVectors(tangents[i - 1], tangents[i]);
  22945. if (vec.length() > Number.EPSILON) {
  22946. vec.normalize();
  22947. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22948. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22949. }
  22950. binormals[i].crossVectors(tangents[i], normals[i]);
  22951. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22952. if (closed === true) {
  22953. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  22954. theta /= segments;
  22955. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22956. theta = -theta;
  22957. }
  22958. for (i = 1; i <= segments; i++) {
  22959. // twist a little...
  22960. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22961. binormals[i].crossVectors(tangents[i], normals[i]);
  22962. }
  22963. }
  22964. return {
  22965. tangents: tangents,
  22966. normals: normals,
  22967. binormals: binormals
  22968. };
  22969. },
  22970. clone: function () {
  22971. return new this.constructor().copy(this);
  22972. },
  22973. copy: function (source) {
  22974. this.arcLengthDivisions = source.arcLengthDivisions;
  22975. return this;
  22976. },
  22977. toJSON: function () {
  22978. var data = {
  22979. metadata: {
  22980. version: 4.5,
  22981. type: 'Curve',
  22982. generator: 'Curve.toJSON'
  22983. }
  22984. };
  22985. data.arcLengthDivisions = this.arcLengthDivisions;
  22986. data.type = this.type;
  22987. return data;
  22988. },
  22989. fromJSON: function (json) {
  22990. this.arcLengthDivisions = json.arcLengthDivisions;
  22991. return this;
  22992. }
  22993. });
  22994. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22995. Curve.call(this);
  22996. this.type = 'EllipseCurve';
  22997. this.aX = aX || 0;
  22998. this.aY = aY || 0;
  22999. this.xRadius = xRadius || 1;
  23000. this.yRadius = yRadius || 1;
  23001. this.aStartAngle = aStartAngle || 0;
  23002. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23003. this.aClockwise = aClockwise || false;
  23004. this.aRotation = aRotation || 0;
  23005. }
  23006. EllipseCurve.prototype = Object.create(Curve.prototype);
  23007. EllipseCurve.prototype.constructor = EllipseCurve;
  23008. EllipseCurve.prototype.isEllipseCurve = true;
  23009. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  23010. var point = optionalTarget || new Vector2();
  23011. var twoPi = Math.PI * 2;
  23012. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23013. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  23014. while (deltaAngle < 0) deltaAngle += twoPi;
  23015. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  23016. if (deltaAngle < Number.EPSILON) {
  23017. if (samePoints) {
  23018. deltaAngle = 0;
  23019. } else {
  23020. deltaAngle = twoPi;
  23021. }
  23022. }
  23023. if (this.aClockwise === true && !samePoints) {
  23024. if (deltaAngle === twoPi) {
  23025. deltaAngle = -twoPi;
  23026. } else {
  23027. deltaAngle = deltaAngle - twoPi;
  23028. }
  23029. }
  23030. var angle = this.aStartAngle + t * deltaAngle;
  23031. var x = this.aX + this.xRadius * Math.cos(angle);
  23032. var y = this.aY + this.yRadius * Math.sin(angle);
  23033. if (this.aRotation !== 0) {
  23034. var cos = Math.cos(this.aRotation);
  23035. var sin = Math.sin(this.aRotation);
  23036. var tx = x - this.aX;
  23037. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  23038. x = tx * cos - ty * sin + this.aX;
  23039. y = tx * sin + ty * cos + this.aY;
  23040. }
  23041. return point.set(x, y);
  23042. };
  23043. EllipseCurve.prototype.copy = function (source) {
  23044. Curve.prototype.copy.call(this, source);
  23045. this.aX = source.aX;
  23046. this.aY = source.aY;
  23047. this.xRadius = source.xRadius;
  23048. this.yRadius = source.yRadius;
  23049. this.aStartAngle = source.aStartAngle;
  23050. this.aEndAngle = source.aEndAngle;
  23051. this.aClockwise = source.aClockwise;
  23052. this.aRotation = source.aRotation;
  23053. return this;
  23054. };
  23055. EllipseCurve.prototype.toJSON = function () {
  23056. var data = Curve.prototype.toJSON.call(this);
  23057. data.aX = this.aX;
  23058. data.aY = this.aY;
  23059. data.xRadius = this.xRadius;
  23060. data.yRadius = this.yRadius;
  23061. data.aStartAngle = this.aStartAngle;
  23062. data.aEndAngle = this.aEndAngle;
  23063. data.aClockwise = this.aClockwise;
  23064. data.aRotation = this.aRotation;
  23065. return data;
  23066. };
  23067. EllipseCurve.prototype.fromJSON = function (json) {
  23068. Curve.prototype.fromJSON.call(this, json);
  23069. this.aX = json.aX;
  23070. this.aY = json.aY;
  23071. this.xRadius = json.xRadius;
  23072. this.yRadius = json.yRadius;
  23073. this.aStartAngle = json.aStartAngle;
  23074. this.aEndAngle = json.aEndAngle;
  23075. this.aClockwise = json.aClockwise;
  23076. this.aRotation = json.aRotation;
  23077. return this;
  23078. };
  23079. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23080. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23081. this.type = 'ArcCurve';
  23082. }
  23083. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  23084. ArcCurve.prototype.constructor = ArcCurve;
  23085. ArcCurve.prototype.isArcCurve = true;
  23086. /**
  23087. * @author zz85 https://github.com/zz85
  23088. *
  23089. * Centripetal CatmullRom Curve - which is useful for avoiding
  23090. * cusps and self-intersections in non-uniform catmull rom curves.
  23091. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23092. *
  23093. * curve.type accepts centripetal(default), chordal and catmullrom
  23094. * curve.tension is used for catmullrom which defaults to 0.5
  23095. */
  23096. /*
  23097. Based on an optimized c++ solution in
  23098. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23099. - http://ideone.com/NoEbVM
  23100. This CubicPoly class could be used for reusing some variables and calculations,
  23101. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23102. which can be placed in CurveUtils.
  23103. */
  23104. function CubicPoly() {
  23105. var c0 = 0,
  23106. c1 = 0,
  23107. c2 = 0,
  23108. c3 = 0;
  23109. /*
  23110. * Compute coefficients for a cubic polynomial
  23111. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23112. * such that
  23113. * p(0) = x0, p(1) = x1
  23114. * and
  23115. * p'(0) = t0, p'(1) = t1.
  23116. */
  23117. function init(x0, x1, t0, t1) {
  23118. c0 = x0;
  23119. c1 = t0;
  23120. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23121. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23122. }
  23123. return {
  23124. initCatmullRom: function (x0, x1, x2, x3, tension) {
  23125. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  23126. },
  23127. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  23128. // compute tangents when parameterized in [t1,t2]
  23129. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  23130. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  23131. t1 *= dt1;
  23132. t2 *= dt1;
  23133. init(x1, x2, t1, t2);
  23134. },
  23135. calc: function (t) {
  23136. var t2 = t * t;
  23137. var t3 = t2 * t;
  23138. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23139. }
  23140. };
  23141. } //
  23142. var tmp = new Vector3();
  23143. var px = new CubicPoly(),
  23144. py = new CubicPoly(),
  23145. pz = new CubicPoly();
  23146. function CatmullRomCurve3(points, closed, curveType, tension) {
  23147. Curve.call(this);
  23148. this.type = 'CatmullRomCurve3';
  23149. this.points = points || [];
  23150. this.closed = closed || false;
  23151. this.curveType = curveType || 'centripetal';
  23152. this.tension = tension || 0.5;
  23153. }
  23154. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  23155. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23156. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23157. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  23158. var point = optionalTarget || new Vector3();
  23159. var points = this.points;
  23160. var l = points.length;
  23161. var p = (l - (this.closed ? 0 : 1)) * t;
  23162. var intPoint = Math.floor(p);
  23163. var weight = p - intPoint;
  23164. if (this.closed) {
  23165. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  23166. } else if (weight === 0 && intPoint === l - 1) {
  23167. intPoint = l - 2;
  23168. weight = 1;
  23169. }
  23170. var p0, p1, p2, p3; // 4 points
  23171. if (this.closed || intPoint > 0) {
  23172. p0 = points[(intPoint - 1) % l];
  23173. } else {
  23174. // extrapolate first point
  23175. tmp.subVectors(points[0], points[1]).add(points[0]);
  23176. p0 = tmp;
  23177. }
  23178. p1 = points[intPoint % l];
  23179. p2 = points[(intPoint + 1) % l];
  23180. if (this.closed || intPoint + 2 < l) {
  23181. p3 = points[(intPoint + 2) % l];
  23182. } else {
  23183. // extrapolate last point
  23184. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  23185. p3 = tmp;
  23186. }
  23187. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  23188. // init Centripetal / Chordal Catmull-Rom
  23189. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23190. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  23191. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  23192. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  23193. if (dt1 < 1e-4) dt1 = 1.0;
  23194. if (dt0 < 1e-4) dt0 = dt1;
  23195. if (dt2 < 1e-4) dt2 = dt1;
  23196. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  23197. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  23198. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  23199. } else if (this.curveType === 'catmullrom') {
  23200. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  23201. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  23202. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  23203. }
  23204. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  23205. return point;
  23206. };
  23207. CatmullRomCurve3.prototype.copy = function (source) {
  23208. Curve.prototype.copy.call(this, source);
  23209. this.points = [];
  23210. for (var i = 0, l = source.points.length; i < l; i++) {
  23211. var point = source.points[i];
  23212. this.points.push(point.clone());
  23213. }
  23214. this.closed = source.closed;
  23215. this.curveType = source.curveType;
  23216. this.tension = source.tension;
  23217. return this;
  23218. };
  23219. CatmullRomCurve3.prototype.toJSON = function () {
  23220. var data = Curve.prototype.toJSON.call(this);
  23221. data.points = [];
  23222. for (var i = 0, l = this.points.length; i < l; i++) {
  23223. var point = this.points[i];
  23224. data.points.push(point.toArray());
  23225. }
  23226. data.closed = this.closed;
  23227. data.curveType = this.curveType;
  23228. data.tension = this.tension;
  23229. return data;
  23230. };
  23231. CatmullRomCurve3.prototype.fromJSON = function (json) {
  23232. Curve.prototype.fromJSON.call(this, json);
  23233. this.points = [];
  23234. for (var i = 0, l = json.points.length; i < l; i++) {
  23235. var point = json.points[i];
  23236. this.points.push(new Vector3().fromArray(point));
  23237. }
  23238. this.closed = json.closed;
  23239. this.curveType = json.curveType;
  23240. this.tension = json.tension;
  23241. return this;
  23242. };
  23243. /**
  23244. * @author zz85 / http://www.lab4games.net/zz85/blog
  23245. *
  23246. * Bezier Curves formulas obtained from
  23247. * http://en.wikipedia.org/wiki/Bézier_curve
  23248. */
  23249. function CatmullRom(t, p0, p1, p2, p3) {
  23250. var v0 = (p2 - p0) * 0.5;
  23251. var v1 = (p3 - p1) * 0.5;
  23252. var t2 = t * t;
  23253. var t3 = t * t2;
  23254. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  23255. } //
  23256. function QuadraticBezierP0(t, p) {
  23257. var k = 1 - t;
  23258. return k * k * p;
  23259. }
  23260. function QuadraticBezierP1(t, p) {
  23261. return 2 * (1 - t) * t * p;
  23262. }
  23263. function QuadraticBezierP2(t, p) {
  23264. return t * t * p;
  23265. }
  23266. function QuadraticBezier(t, p0, p1, p2) {
  23267. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  23268. } //
  23269. function CubicBezierP0(t, p) {
  23270. var k = 1 - t;
  23271. return k * k * k * p;
  23272. }
  23273. function CubicBezierP1(t, p) {
  23274. var k = 1 - t;
  23275. return 3 * k * k * t * p;
  23276. }
  23277. function CubicBezierP2(t, p) {
  23278. return 3 * (1 - t) * t * t * p;
  23279. }
  23280. function CubicBezierP3(t, p) {
  23281. return t * t * t * p;
  23282. }
  23283. function CubicBezier(t, p0, p1, p2, p3) {
  23284. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  23285. }
  23286. function CubicBezierCurve(v0, v1, v2, v3) {
  23287. Curve.call(this);
  23288. this.type = 'CubicBezierCurve';
  23289. this.v0 = v0 || new Vector2();
  23290. this.v1 = v1 || new Vector2();
  23291. this.v2 = v2 || new Vector2();
  23292. this.v3 = v3 || new Vector2();
  23293. }
  23294. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  23295. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23296. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23297. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23298. var point = optionalTarget || new Vector2();
  23299. var v0 = this.v0,
  23300. v1 = this.v1,
  23301. v2 = this.v2,
  23302. v3 = this.v3;
  23303. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  23304. return point;
  23305. };
  23306. CubicBezierCurve.prototype.copy = function (source) {
  23307. Curve.prototype.copy.call(this, source);
  23308. this.v0.copy(source.v0);
  23309. this.v1.copy(source.v1);
  23310. this.v2.copy(source.v2);
  23311. this.v3.copy(source.v3);
  23312. return this;
  23313. };
  23314. CubicBezierCurve.prototype.toJSON = function () {
  23315. var data = Curve.prototype.toJSON.call(this);
  23316. data.v0 = this.v0.toArray();
  23317. data.v1 = this.v1.toArray();
  23318. data.v2 = this.v2.toArray();
  23319. data.v3 = this.v3.toArray();
  23320. return data;
  23321. };
  23322. CubicBezierCurve.prototype.fromJSON = function (json) {
  23323. Curve.prototype.fromJSON.call(this, json);
  23324. this.v0.fromArray(json.v0);
  23325. this.v1.fromArray(json.v1);
  23326. this.v2.fromArray(json.v2);
  23327. this.v3.fromArray(json.v3);
  23328. return this;
  23329. };
  23330. function CubicBezierCurve3(v0, v1, v2, v3) {
  23331. Curve.call(this);
  23332. this.type = 'CubicBezierCurve3';
  23333. this.v0 = v0 || new Vector3();
  23334. this.v1 = v1 || new Vector3();
  23335. this.v2 = v2 || new Vector3();
  23336. this.v3 = v3 || new Vector3();
  23337. }
  23338. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23339. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23340. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23341. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23342. var point = optionalTarget || new Vector3();
  23343. var v0 = this.v0,
  23344. v1 = this.v1,
  23345. v2 = this.v2,
  23346. v3 = this.v3;
  23347. 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));
  23348. return point;
  23349. };
  23350. CubicBezierCurve3.prototype.copy = function (source) {
  23351. Curve.prototype.copy.call(this, source);
  23352. this.v0.copy(source.v0);
  23353. this.v1.copy(source.v1);
  23354. this.v2.copy(source.v2);
  23355. this.v3.copy(source.v3);
  23356. return this;
  23357. };
  23358. CubicBezierCurve3.prototype.toJSON = function () {
  23359. var data = Curve.prototype.toJSON.call(this);
  23360. data.v0 = this.v0.toArray();
  23361. data.v1 = this.v1.toArray();
  23362. data.v2 = this.v2.toArray();
  23363. data.v3 = this.v3.toArray();
  23364. return data;
  23365. };
  23366. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23367. Curve.prototype.fromJSON.call(this, json);
  23368. this.v0.fromArray(json.v0);
  23369. this.v1.fromArray(json.v1);
  23370. this.v2.fromArray(json.v2);
  23371. this.v3.fromArray(json.v3);
  23372. return this;
  23373. };
  23374. function LineCurve(v1, v2) {
  23375. Curve.call(this);
  23376. this.type = 'LineCurve';
  23377. this.v1 = v1 || new Vector2();
  23378. this.v2 = v2 || new Vector2();
  23379. }
  23380. LineCurve.prototype = Object.create(Curve.prototype);
  23381. LineCurve.prototype.constructor = LineCurve;
  23382. LineCurve.prototype.isLineCurve = true;
  23383. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  23384. var point = optionalTarget || new Vector2();
  23385. if (t === 1) {
  23386. point.copy(this.v2);
  23387. } else {
  23388. point.copy(this.v2).sub(this.v1);
  23389. point.multiplyScalar(t).add(this.v1);
  23390. }
  23391. return point;
  23392. }; // Line curve is linear, so we can overwrite default getPointAt
  23393. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23394. return this.getPoint(u, optionalTarget);
  23395. };
  23396. LineCurve.prototype.getTangent = function ()
  23397. /* t */
  23398. {
  23399. var tangent = this.v2.clone().sub(this.v1);
  23400. return tangent.normalize();
  23401. };
  23402. LineCurve.prototype.copy = function (source) {
  23403. Curve.prototype.copy.call(this, source);
  23404. this.v1.copy(source.v1);
  23405. this.v2.copy(source.v2);
  23406. return this;
  23407. };
  23408. LineCurve.prototype.toJSON = function () {
  23409. var data = Curve.prototype.toJSON.call(this);
  23410. data.v1 = this.v1.toArray();
  23411. data.v2 = this.v2.toArray();
  23412. return data;
  23413. };
  23414. LineCurve.prototype.fromJSON = function (json) {
  23415. Curve.prototype.fromJSON.call(this, json);
  23416. this.v1.fromArray(json.v1);
  23417. this.v2.fromArray(json.v2);
  23418. return this;
  23419. };
  23420. function LineCurve3(v1, v2) {
  23421. Curve.call(this);
  23422. this.type = 'LineCurve3';
  23423. this.v1 = v1 || new Vector3();
  23424. this.v2 = v2 || new Vector3();
  23425. }
  23426. LineCurve3.prototype = Object.create(Curve.prototype);
  23427. LineCurve3.prototype.constructor = LineCurve3;
  23428. LineCurve3.prototype.isLineCurve3 = true;
  23429. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  23430. var point = optionalTarget || new Vector3();
  23431. if (t === 1) {
  23432. point.copy(this.v2);
  23433. } else {
  23434. point.copy(this.v2).sub(this.v1);
  23435. point.multiplyScalar(t).add(this.v1);
  23436. }
  23437. return point;
  23438. }; // Line curve is linear, so we can overwrite default getPointAt
  23439. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23440. return this.getPoint(u, optionalTarget);
  23441. };
  23442. LineCurve3.prototype.copy = function (source) {
  23443. Curve.prototype.copy.call(this, source);
  23444. this.v1.copy(source.v1);
  23445. this.v2.copy(source.v2);
  23446. return this;
  23447. };
  23448. LineCurve3.prototype.toJSON = function () {
  23449. var data = Curve.prototype.toJSON.call(this);
  23450. data.v1 = this.v1.toArray();
  23451. data.v2 = this.v2.toArray();
  23452. return data;
  23453. };
  23454. LineCurve3.prototype.fromJSON = function (json) {
  23455. Curve.prototype.fromJSON.call(this, json);
  23456. this.v1.fromArray(json.v1);
  23457. this.v2.fromArray(json.v2);
  23458. return this;
  23459. };
  23460. function QuadraticBezierCurve(v0, v1, v2) {
  23461. Curve.call(this);
  23462. this.type = 'QuadraticBezierCurve';
  23463. this.v0 = v0 || new Vector2();
  23464. this.v1 = v1 || new Vector2();
  23465. this.v2 = v2 || new Vector2();
  23466. }
  23467. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23468. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23469. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23470. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23471. var point = optionalTarget || new Vector2();
  23472. var v0 = this.v0,
  23473. v1 = this.v1,
  23474. v2 = this.v2;
  23475. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23476. return point;
  23477. };
  23478. QuadraticBezierCurve.prototype.copy = function (source) {
  23479. Curve.prototype.copy.call(this, source);
  23480. this.v0.copy(source.v0);
  23481. this.v1.copy(source.v1);
  23482. this.v2.copy(source.v2);
  23483. return this;
  23484. };
  23485. QuadraticBezierCurve.prototype.toJSON = function () {
  23486. var data = Curve.prototype.toJSON.call(this);
  23487. data.v0 = this.v0.toArray();
  23488. data.v1 = this.v1.toArray();
  23489. data.v2 = this.v2.toArray();
  23490. return data;
  23491. };
  23492. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23493. Curve.prototype.fromJSON.call(this, json);
  23494. this.v0.fromArray(json.v0);
  23495. this.v1.fromArray(json.v1);
  23496. this.v2.fromArray(json.v2);
  23497. return this;
  23498. };
  23499. function QuadraticBezierCurve3(v0, v1, v2) {
  23500. Curve.call(this);
  23501. this.type = 'QuadraticBezierCurve3';
  23502. this.v0 = v0 || new Vector3();
  23503. this.v1 = v1 || new Vector3();
  23504. this.v2 = v2 || new Vector3();
  23505. }
  23506. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23507. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23508. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23509. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23510. var point = optionalTarget || new Vector3();
  23511. var v0 = this.v0,
  23512. v1 = this.v1,
  23513. v2 = this.v2;
  23514. 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));
  23515. return point;
  23516. };
  23517. QuadraticBezierCurve3.prototype.copy = function (source) {
  23518. Curve.prototype.copy.call(this, source);
  23519. this.v0.copy(source.v0);
  23520. this.v1.copy(source.v1);
  23521. this.v2.copy(source.v2);
  23522. return this;
  23523. };
  23524. QuadraticBezierCurve3.prototype.toJSON = function () {
  23525. var data = Curve.prototype.toJSON.call(this);
  23526. data.v0 = this.v0.toArray();
  23527. data.v1 = this.v1.toArray();
  23528. data.v2 = this.v2.toArray();
  23529. return data;
  23530. };
  23531. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23532. Curve.prototype.fromJSON.call(this, json);
  23533. this.v0.fromArray(json.v0);
  23534. this.v1.fromArray(json.v1);
  23535. this.v2.fromArray(json.v2);
  23536. return this;
  23537. };
  23538. function SplineCurve(points
  23539. /* array of Vector2 */
  23540. ) {
  23541. Curve.call(this);
  23542. this.type = 'SplineCurve';
  23543. this.points = points || [];
  23544. }
  23545. SplineCurve.prototype = Object.create(Curve.prototype);
  23546. SplineCurve.prototype.constructor = SplineCurve;
  23547. SplineCurve.prototype.isSplineCurve = true;
  23548. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  23549. var point = optionalTarget || new Vector2();
  23550. var points = this.points;
  23551. var p = (points.length - 1) * t;
  23552. var intPoint = Math.floor(p);
  23553. var weight = p - intPoint;
  23554. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23555. var p1 = points[intPoint];
  23556. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23557. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23558. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23559. return point;
  23560. };
  23561. SplineCurve.prototype.copy = function (source) {
  23562. Curve.prototype.copy.call(this, source);
  23563. this.points = [];
  23564. for (var i = 0, l = source.points.length; i < l; i++) {
  23565. var point = source.points[i];
  23566. this.points.push(point.clone());
  23567. }
  23568. return this;
  23569. };
  23570. SplineCurve.prototype.toJSON = function () {
  23571. var data = Curve.prototype.toJSON.call(this);
  23572. data.points = [];
  23573. for (var i = 0, l = this.points.length; i < l; i++) {
  23574. var point = this.points[i];
  23575. data.points.push(point.toArray());
  23576. }
  23577. return data;
  23578. };
  23579. SplineCurve.prototype.fromJSON = function (json) {
  23580. Curve.prototype.fromJSON.call(this, json);
  23581. this.points = [];
  23582. for (var i = 0, l = json.points.length; i < l; i++) {
  23583. var point = json.points[i];
  23584. this.points.push(new Vector2().fromArray(point));
  23585. }
  23586. return this;
  23587. };
  23588. var Curves =
  23589. /*#__PURE__*/
  23590. Object.freeze({
  23591. ArcCurve: ArcCurve,
  23592. CatmullRomCurve3: CatmullRomCurve3,
  23593. CubicBezierCurve: CubicBezierCurve,
  23594. CubicBezierCurve3: CubicBezierCurve3,
  23595. EllipseCurve: EllipseCurve,
  23596. LineCurve: LineCurve,
  23597. LineCurve3: LineCurve3,
  23598. QuadraticBezierCurve: QuadraticBezierCurve,
  23599. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23600. SplineCurve: SplineCurve
  23601. });
  23602. /**
  23603. * @author zz85 / http://www.lab4games.net/zz85/blog
  23604. *
  23605. **/
  23606. /**************************************************************
  23607. * Curved Path - a curve path is simply a array of connected
  23608. * curves, but retains the api of a curve
  23609. **************************************************************/
  23610. function CurvePath() {
  23611. Curve.call(this);
  23612. this.type = 'CurvePath';
  23613. this.curves = [];
  23614. this.autoClose = false; // Automatically closes the path
  23615. }
  23616. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23617. constructor: CurvePath,
  23618. add: function (curve) {
  23619. this.curves.push(curve);
  23620. },
  23621. closePath: function () {
  23622. // Add a line curve if start and end of lines are not connected
  23623. var startPoint = this.curves[0].getPoint(0);
  23624. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23625. if (!startPoint.equals(endPoint)) {
  23626. this.curves.push(new LineCurve(endPoint, startPoint));
  23627. }
  23628. },
  23629. // To get accurate point with reference to
  23630. // entire path distance at time t,
  23631. // following has to be done:
  23632. // 1. Length of each sub path have to be known
  23633. // 2. Locate and identify type of curve
  23634. // 3. Get t for the curve
  23635. // 4. Return curve.getPointAt(t')
  23636. getPoint: function (t) {
  23637. var d = t * this.getLength();
  23638. var curveLengths = this.getCurveLengths();
  23639. var i = 0; // To think about boundaries points.
  23640. while (i < curveLengths.length) {
  23641. if (curveLengths[i] >= d) {
  23642. var diff = curveLengths[i] - d;
  23643. var curve = this.curves[i];
  23644. var segmentLength = curve.getLength();
  23645. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23646. return curve.getPointAt(u);
  23647. }
  23648. i++;
  23649. }
  23650. return null; // loop where sum != 0, sum > d , sum+1 <d
  23651. },
  23652. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23653. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23654. // getPoint() depends on getLength
  23655. getLength: function () {
  23656. var lens = this.getCurveLengths();
  23657. return lens[lens.length - 1];
  23658. },
  23659. // cacheLengths must be recalculated.
  23660. updateArcLengths: function () {
  23661. this.needsUpdate = true;
  23662. this.cacheLengths = null;
  23663. this.getCurveLengths();
  23664. },
  23665. // Compute lengths and cache them
  23666. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23667. getCurveLengths: function () {
  23668. // We use cache values if curves and cache array are same length
  23669. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23670. return this.cacheLengths;
  23671. } // Get length of sub-curve
  23672. // Push sums into cached array
  23673. var lengths = [],
  23674. sums = 0;
  23675. for (var i = 0, l = this.curves.length; i < l; i++) {
  23676. sums += this.curves[i].getLength();
  23677. lengths.push(sums);
  23678. }
  23679. this.cacheLengths = lengths;
  23680. return lengths;
  23681. },
  23682. getSpacedPoints: function (divisions) {
  23683. if (divisions === undefined) divisions = 40;
  23684. var points = [];
  23685. for (var i = 0; i <= divisions; i++) {
  23686. points.push(this.getPoint(i / divisions));
  23687. }
  23688. if (this.autoClose) {
  23689. points.push(points[0]);
  23690. }
  23691. return points;
  23692. },
  23693. getPoints: function (divisions) {
  23694. divisions = divisions || 12;
  23695. var points = [],
  23696. last;
  23697. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  23698. var curve = curves[i];
  23699. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23700. var pts = curve.getPoints(resolution);
  23701. for (var j = 0; j < pts.length; j++) {
  23702. var point = pts[j];
  23703. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23704. points.push(point);
  23705. last = point;
  23706. }
  23707. }
  23708. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23709. points.push(points[0]);
  23710. }
  23711. return points;
  23712. },
  23713. copy: function (source) {
  23714. Curve.prototype.copy.call(this, source);
  23715. this.curves = [];
  23716. for (var i = 0, l = source.curves.length; i < l; i++) {
  23717. var curve = source.curves[i];
  23718. this.curves.push(curve.clone());
  23719. }
  23720. this.autoClose = source.autoClose;
  23721. return this;
  23722. },
  23723. toJSON: function () {
  23724. var data = Curve.prototype.toJSON.call(this);
  23725. data.autoClose = this.autoClose;
  23726. data.curves = [];
  23727. for (var i = 0, l = this.curves.length; i < l; i++) {
  23728. var curve = this.curves[i];
  23729. data.curves.push(curve.toJSON());
  23730. }
  23731. return data;
  23732. },
  23733. fromJSON: function (json) {
  23734. Curve.prototype.fromJSON.call(this, json);
  23735. this.autoClose = json.autoClose;
  23736. this.curves = [];
  23737. for (var i = 0, l = json.curves.length; i < l; i++) {
  23738. var curve = json.curves[i];
  23739. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23740. }
  23741. return this;
  23742. }
  23743. });
  23744. /**
  23745. * @author zz85 / http://www.lab4games.net/zz85/blog
  23746. * Creates free form 2d path using series of points, lines or curves.
  23747. **/
  23748. function Path(points) {
  23749. CurvePath.call(this);
  23750. this.type = 'Path';
  23751. this.currentPoint = new Vector2();
  23752. if (points) {
  23753. this.setFromPoints(points);
  23754. }
  23755. }
  23756. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23757. constructor: Path,
  23758. setFromPoints: function (points) {
  23759. this.moveTo(points[0].x, points[0].y);
  23760. for (var i = 1, l = points.length; i < l; i++) {
  23761. this.lineTo(points[i].x, points[i].y);
  23762. }
  23763. },
  23764. moveTo: function (x, y) {
  23765. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23766. },
  23767. lineTo: function (x, y) {
  23768. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23769. this.curves.push(curve);
  23770. this.currentPoint.set(x, y);
  23771. },
  23772. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23773. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23774. this.curves.push(curve);
  23775. this.currentPoint.set(aX, aY);
  23776. },
  23777. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23778. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23779. this.curves.push(curve);
  23780. this.currentPoint.set(aX, aY);
  23781. },
  23782. splineThru: function (pts
  23783. /*Array of Vector*/
  23784. ) {
  23785. var npts = [this.currentPoint.clone()].concat(pts);
  23786. var curve = new SplineCurve(npts);
  23787. this.curves.push(curve);
  23788. this.currentPoint.copy(pts[pts.length - 1]);
  23789. },
  23790. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23791. var x0 = this.currentPoint.x;
  23792. var y0 = this.currentPoint.y;
  23793. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23794. },
  23795. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23796. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23797. },
  23798. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23799. var x0 = this.currentPoint.x;
  23800. var y0 = this.currentPoint.y;
  23801. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23802. },
  23803. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23804. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23805. if (this.curves.length > 0) {
  23806. // if a previous curve is present, attempt to join
  23807. var firstPoint = curve.getPoint(0);
  23808. if (!firstPoint.equals(this.currentPoint)) {
  23809. this.lineTo(firstPoint.x, firstPoint.y);
  23810. }
  23811. }
  23812. this.curves.push(curve);
  23813. var lastPoint = curve.getPoint(1);
  23814. this.currentPoint.copy(lastPoint);
  23815. },
  23816. copy: function (source) {
  23817. CurvePath.prototype.copy.call(this, source);
  23818. this.currentPoint.copy(source.currentPoint);
  23819. return this;
  23820. },
  23821. toJSON: function () {
  23822. var data = CurvePath.prototype.toJSON.call(this);
  23823. data.currentPoint = this.currentPoint.toArray();
  23824. return data;
  23825. },
  23826. fromJSON: function (json) {
  23827. CurvePath.prototype.fromJSON.call(this, json);
  23828. this.currentPoint.fromArray(json.currentPoint);
  23829. return this;
  23830. }
  23831. });
  23832. /**
  23833. * @author zz85 / http://www.lab4games.net/zz85/blog
  23834. * Defines a 2d shape plane using paths.
  23835. **/
  23836. // STEP 1 Create a path.
  23837. // STEP 2 Turn path into shape.
  23838. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23839. // STEP 3a - Extract points from each shape, turn to vertices
  23840. // STEP 3b - Triangulate each shape, add faces.
  23841. function Shape(points) {
  23842. Path.call(this, points);
  23843. this.uuid = _Math.generateUUID();
  23844. this.type = 'Shape';
  23845. this.holes = [];
  23846. }
  23847. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23848. constructor: Shape,
  23849. getPointsHoles: function (divisions) {
  23850. var holesPts = [];
  23851. for (var i = 0, l = this.holes.length; i < l; i++) {
  23852. holesPts[i] = this.holes[i].getPoints(divisions);
  23853. }
  23854. return holesPts;
  23855. },
  23856. // get points of shape and holes (keypoints based on segments parameter)
  23857. extractPoints: function (divisions) {
  23858. return {
  23859. shape: this.getPoints(divisions),
  23860. holes: this.getPointsHoles(divisions)
  23861. };
  23862. },
  23863. copy: function (source) {
  23864. Path.prototype.copy.call(this, source);
  23865. this.holes = [];
  23866. for (var i = 0, l = source.holes.length; i < l; i++) {
  23867. var hole = source.holes[i];
  23868. this.holes.push(hole.clone());
  23869. }
  23870. return this;
  23871. },
  23872. toJSON: function () {
  23873. var data = Path.prototype.toJSON.call(this);
  23874. data.uuid = this.uuid;
  23875. data.holes = [];
  23876. for (var i = 0, l = this.holes.length; i < l; i++) {
  23877. var hole = this.holes[i];
  23878. data.holes.push(hole.toJSON());
  23879. }
  23880. return data;
  23881. },
  23882. fromJSON: function (json) {
  23883. Path.prototype.fromJSON.call(this, json);
  23884. this.uuid = json.uuid;
  23885. this.holes = [];
  23886. for (var i = 0, l = json.holes.length; i < l; i++) {
  23887. var hole = json.holes[i];
  23888. this.holes.push(new Path().fromJSON(hole));
  23889. }
  23890. return this;
  23891. }
  23892. });
  23893. /**
  23894. * @author mrdoob / http://mrdoob.com/
  23895. * @author alteredq / http://alteredqualia.com/
  23896. */
  23897. function Light(color, intensity) {
  23898. Object3D.call(this);
  23899. this.type = 'Light';
  23900. this.color = new Color(color);
  23901. this.intensity = intensity !== undefined ? intensity : 1;
  23902. this.receiveShadow = undefined;
  23903. }
  23904. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23905. constructor: Light,
  23906. isLight: true,
  23907. copy: function (source) {
  23908. Object3D.prototype.copy.call(this, source);
  23909. this.color.copy(source.color);
  23910. this.intensity = source.intensity;
  23911. return this;
  23912. },
  23913. toJSON: function (meta) {
  23914. var data = Object3D.prototype.toJSON.call(this, meta);
  23915. data.object.color = this.color.getHex();
  23916. data.object.intensity = this.intensity;
  23917. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23918. if (this.distance !== undefined) data.object.distance = this.distance;
  23919. if (this.angle !== undefined) data.object.angle = this.angle;
  23920. if (this.decay !== undefined) data.object.decay = this.decay;
  23921. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23922. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23923. return data;
  23924. }
  23925. });
  23926. /**
  23927. * @author alteredq / http://alteredqualia.com/
  23928. */
  23929. function HemisphereLight(skyColor, groundColor, intensity) {
  23930. Light.call(this, skyColor, intensity);
  23931. this.type = 'HemisphereLight';
  23932. this.castShadow = undefined;
  23933. this.position.copy(Object3D.DefaultUp);
  23934. this.updateMatrix();
  23935. this.groundColor = new Color(groundColor);
  23936. }
  23937. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23938. constructor: HemisphereLight,
  23939. isHemisphereLight: true,
  23940. copy: function (source) {
  23941. Light.prototype.copy.call(this, source);
  23942. this.groundColor.copy(source.groundColor);
  23943. return this;
  23944. }
  23945. });
  23946. /**
  23947. * @author mrdoob / http://mrdoob.com/
  23948. */
  23949. function LightShadow(camera) {
  23950. this.camera = camera;
  23951. this.bias = 0;
  23952. this.radius = 1;
  23953. this.mapSize = new Vector2(512, 512);
  23954. this.map = null;
  23955. this.mapPass = null;
  23956. this.matrix = new Matrix4();
  23957. this._frustum = new Frustum();
  23958. this._frameExtents = new Vector2(1, 1);
  23959. this._viewportCount = 1;
  23960. this._viewports = [new Vector4(0, 0, 1, 1)];
  23961. }
  23962. Object.assign(LightShadow.prototype, {
  23963. _projScreenMatrix: new Matrix4(),
  23964. _lightPositionWorld: new Vector3(),
  23965. _lookTarget: new Vector3(),
  23966. getViewportCount: function () {
  23967. return this._viewportCount;
  23968. },
  23969. getFrustum: function () {
  23970. return this._frustum;
  23971. },
  23972. updateMatrices: function (light) {
  23973. var shadowCamera = this.camera,
  23974. shadowMatrix = this.matrix,
  23975. projScreenMatrix = this._projScreenMatrix,
  23976. lookTarget = this._lookTarget,
  23977. lightPositionWorld = this._lightPositionWorld;
  23978. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23979. shadowCamera.position.copy(lightPositionWorld);
  23980. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23981. shadowCamera.lookAt(lookTarget);
  23982. shadowCamera.updateMatrixWorld();
  23983. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23984. this._frustum.setFromMatrix(projScreenMatrix);
  23985. 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);
  23986. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23987. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23988. },
  23989. getViewport: function (viewportIndex) {
  23990. return this._viewports[viewportIndex];
  23991. },
  23992. getFrameExtents: function () {
  23993. return this._frameExtents;
  23994. },
  23995. copy: function (source) {
  23996. this.camera = source.camera.clone();
  23997. this.bias = source.bias;
  23998. this.radius = source.radius;
  23999. this.mapSize.copy(source.mapSize);
  24000. return this;
  24001. },
  24002. clone: function () {
  24003. return new this.constructor().copy(this);
  24004. },
  24005. toJSON: function () {
  24006. var object = {};
  24007. if (this.bias !== 0) object.bias = this.bias;
  24008. if (this.radius !== 1) object.radius = this.radius;
  24009. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24010. object.camera = this.camera.toJSON(false).object;
  24011. delete object.camera.matrix;
  24012. return object;
  24013. }
  24014. });
  24015. /**
  24016. * @author mrdoob / http://mrdoob.com/
  24017. */
  24018. function SpotLightShadow() {
  24019. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  24020. }
  24021. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24022. constructor: SpotLightShadow,
  24023. isSpotLightShadow: true,
  24024. updateMatrices: function (light, viewCamera, viewportIndex) {
  24025. var camera = this.camera;
  24026. var fov = _Math.RAD2DEG * 2 * light.angle;
  24027. var aspect = this.mapSize.width / this.mapSize.height;
  24028. var far = light.distance || camera.far;
  24029. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24030. camera.fov = fov;
  24031. camera.aspect = aspect;
  24032. camera.far = far;
  24033. camera.updateProjectionMatrix();
  24034. }
  24035. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24036. }
  24037. });
  24038. /**
  24039. * @author alteredq / http://alteredqualia.com/
  24040. */
  24041. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  24042. Light.call(this, color, intensity);
  24043. this.type = 'SpotLight';
  24044. this.position.copy(Object3D.DefaultUp);
  24045. this.updateMatrix();
  24046. this.target = new Object3D();
  24047. Object.defineProperty(this, 'power', {
  24048. get: function () {
  24049. // intensity = power per solid angle.
  24050. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24051. return this.intensity * Math.PI;
  24052. },
  24053. set: function (power) {
  24054. // intensity = power per solid angle.
  24055. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24056. this.intensity = power / Math.PI;
  24057. }
  24058. });
  24059. this.distance = distance !== undefined ? distance : 0;
  24060. this.angle = angle !== undefined ? angle : Math.PI / 3;
  24061. this.penumbra = penumbra !== undefined ? penumbra : 0;
  24062. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24063. this.shadow = new SpotLightShadow();
  24064. }
  24065. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  24066. constructor: SpotLight,
  24067. isSpotLight: true,
  24068. copy: function (source) {
  24069. Light.prototype.copy.call(this, source);
  24070. this.distance = source.distance;
  24071. this.angle = source.angle;
  24072. this.penumbra = source.penumbra;
  24073. this.decay = source.decay;
  24074. this.target = source.target.clone();
  24075. this.shadow = source.shadow.clone();
  24076. return this;
  24077. }
  24078. });
  24079. function PointLightShadow() {
  24080. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  24081. this._frameExtents = new Vector2(4, 2);
  24082. this._viewportCount = 6;
  24083. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  24084. // following orientation:
  24085. //
  24086. // xzXZ
  24087. // y Y
  24088. //
  24089. // X - Positive x direction
  24090. // x - Negative x direction
  24091. // Y - Positive y direction
  24092. // y - Negative y direction
  24093. // Z - Positive z direction
  24094. // z - Negative z direction
  24095. // positive X
  24096. new Vector4(2, 1, 1, 1), // negative X
  24097. new Vector4(0, 1, 1, 1), // positive Z
  24098. new Vector4(3, 1, 1, 1), // negative Z
  24099. new Vector4(1, 1, 1, 1), // positive Y
  24100. new Vector4(3, 0, 1, 1), // negative Y
  24101. new Vector4(1, 0, 1, 1)];
  24102. 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)];
  24103. 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)];
  24104. }
  24105. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24106. constructor: PointLightShadow,
  24107. isPointLightShadow: true,
  24108. updateMatrices: function (light, viewCamera, viewportIndex) {
  24109. var camera = this.camera,
  24110. shadowMatrix = this.matrix,
  24111. lightPositionWorld = this._lightPositionWorld,
  24112. lookTarget = this._lookTarget,
  24113. projScreenMatrix = this._projScreenMatrix;
  24114. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24115. camera.position.copy(lightPositionWorld);
  24116. lookTarget.copy(camera.position);
  24117. lookTarget.add(this._cubeDirections[viewportIndex]);
  24118. camera.up.copy(this._cubeUps[viewportIndex]);
  24119. camera.lookAt(lookTarget);
  24120. camera.updateMatrixWorld();
  24121. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  24122. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24123. this._frustum.setFromMatrix(projScreenMatrix);
  24124. }
  24125. });
  24126. /**
  24127. * @author mrdoob / http://mrdoob.com/
  24128. */
  24129. function PointLight(color, intensity, distance, decay) {
  24130. Light.call(this, color, intensity);
  24131. this.type = 'PointLight';
  24132. Object.defineProperty(this, 'power', {
  24133. get: function () {
  24134. // intensity = power per solid angle.
  24135. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24136. return this.intensity * 4 * Math.PI;
  24137. },
  24138. set: function (power) {
  24139. // intensity = power per solid angle.
  24140. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24141. this.intensity = power / (4 * Math.PI);
  24142. }
  24143. });
  24144. this.distance = distance !== undefined ? distance : 0;
  24145. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24146. this.shadow = new PointLightShadow();
  24147. }
  24148. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  24149. constructor: PointLight,
  24150. isPointLight: true,
  24151. copy: function (source) {
  24152. Light.prototype.copy.call(this, source);
  24153. this.distance = source.distance;
  24154. this.decay = source.decay;
  24155. this.shadow = source.shadow.clone();
  24156. return this;
  24157. }
  24158. });
  24159. /**
  24160. * @author alteredq / http://alteredqualia.com/
  24161. * @author arose / http://github.com/arose
  24162. */
  24163. function OrthographicCamera(left, right, top, bottom, near, far) {
  24164. Camera.call(this);
  24165. this.type = 'OrthographicCamera';
  24166. this.zoom = 1;
  24167. this.view = null;
  24168. this.left = left !== undefined ? left : -1;
  24169. this.right = right !== undefined ? right : 1;
  24170. this.top = top !== undefined ? top : 1;
  24171. this.bottom = bottom !== undefined ? bottom : -1;
  24172. this.near = near !== undefined ? near : 0.1;
  24173. this.far = far !== undefined ? far : 2000;
  24174. this.updateProjectionMatrix();
  24175. }
  24176. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  24177. constructor: OrthographicCamera,
  24178. isOrthographicCamera: true,
  24179. copy: function (source, recursive) {
  24180. Camera.prototype.copy.call(this, source, recursive);
  24181. this.left = source.left;
  24182. this.right = source.right;
  24183. this.top = source.top;
  24184. this.bottom = source.bottom;
  24185. this.near = source.near;
  24186. this.far = source.far;
  24187. this.zoom = source.zoom;
  24188. this.view = source.view === null ? null : Object.assign({}, source.view);
  24189. return this;
  24190. },
  24191. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  24192. if (this.view === null) {
  24193. this.view = {
  24194. enabled: true,
  24195. fullWidth: 1,
  24196. fullHeight: 1,
  24197. offsetX: 0,
  24198. offsetY: 0,
  24199. width: 1,
  24200. height: 1
  24201. };
  24202. }
  24203. this.view.enabled = true;
  24204. this.view.fullWidth = fullWidth;
  24205. this.view.fullHeight = fullHeight;
  24206. this.view.offsetX = x;
  24207. this.view.offsetY = y;
  24208. this.view.width = width;
  24209. this.view.height = height;
  24210. this.updateProjectionMatrix();
  24211. },
  24212. clearViewOffset: function () {
  24213. if (this.view !== null) {
  24214. this.view.enabled = false;
  24215. }
  24216. this.updateProjectionMatrix();
  24217. },
  24218. updateProjectionMatrix: function () {
  24219. var dx = (this.right - this.left) / (2 * this.zoom);
  24220. var dy = (this.top - this.bottom) / (2 * this.zoom);
  24221. var cx = (this.right + this.left) / 2;
  24222. var cy = (this.top + this.bottom) / 2;
  24223. var left = cx - dx;
  24224. var right = cx + dx;
  24225. var top = cy + dy;
  24226. var bottom = cy - dy;
  24227. if (this.view !== null && this.view.enabled) {
  24228. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  24229. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  24230. var scaleW = (this.right - this.left) / this.view.width;
  24231. var scaleH = (this.top - this.bottom) / this.view.height;
  24232. left += scaleW * (this.view.offsetX / zoomW);
  24233. right = left + scaleW * (this.view.width / zoomW);
  24234. top -= scaleH * (this.view.offsetY / zoomH);
  24235. bottom = top - scaleH * (this.view.height / zoomH);
  24236. }
  24237. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  24238. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  24239. },
  24240. toJSON: function (meta) {
  24241. var data = Object3D.prototype.toJSON.call(this, meta);
  24242. data.object.zoom = this.zoom;
  24243. data.object.left = this.left;
  24244. data.object.right = this.right;
  24245. data.object.top = this.top;
  24246. data.object.bottom = this.bottom;
  24247. data.object.near = this.near;
  24248. data.object.far = this.far;
  24249. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  24250. return data;
  24251. }
  24252. });
  24253. /**
  24254. * @author mrdoob / http://mrdoob.com/
  24255. */
  24256. function DirectionalLightShadow() {
  24257. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24258. }
  24259. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24260. constructor: DirectionalLightShadow,
  24261. isDirectionalLightShadow: true,
  24262. updateMatrices: function (light, viewCamera, viewportIndex) {
  24263. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24264. }
  24265. });
  24266. /**
  24267. * @author mrdoob / http://mrdoob.com/
  24268. * @author alteredq / http://alteredqualia.com/
  24269. */
  24270. function DirectionalLight(color, intensity) {
  24271. Light.call(this, color, intensity);
  24272. this.type = 'DirectionalLight';
  24273. this.position.copy(Object3D.DefaultUp);
  24274. this.updateMatrix();
  24275. this.target = new Object3D();
  24276. this.shadow = new DirectionalLightShadow();
  24277. }
  24278. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  24279. constructor: DirectionalLight,
  24280. isDirectionalLight: true,
  24281. copy: function (source) {
  24282. Light.prototype.copy.call(this, source);
  24283. this.target = source.target.clone();
  24284. this.shadow = source.shadow.clone();
  24285. return this;
  24286. }
  24287. });
  24288. /**
  24289. * @author mrdoob / http://mrdoob.com/
  24290. */
  24291. function AmbientLight(color, intensity) {
  24292. Light.call(this, color, intensity);
  24293. this.type = 'AmbientLight';
  24294. this.castShadow = undefined;
  24295. }
  24296. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  24297. constructor: AmbientLight,
  24298. isAmbientLight: true
  24299. });
  24300. /**
  24301. * @author abelnation / http://github.com/abelnation
  24302. */
  24303. function RectAreaLight(color, intensity, width, height) {
  24304. Light.call(this, color, intensity);
  24305. this.type = 'RectAreaLight';
  24306. this.width = width !== undefined ? width : 10;
  24307. this.height = height !== undefined ? height : 10;
  24308. }
  24309. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  24310. constructor: RectAreaLight,
  24311. isRectAreaLight: true,
  24312. copy: function (source) {
  24313. Light.prototype.copy.call(this, source);
  24314. this.width = source.width;
  24315. this.height = source.height;
  24316. return this;
  24317. },
  24318. toJSON: function (meta) {
  24319. var data = Light.prototype.toJSON.call(this, meta);
  24320. data.object.width = this.width;
  24321. data.object.height = this.height;
  24322. return data;
  24323. }
  24324. });
  24325. /**
  24326. * @author mrdoob / http://mrdoob.com/
  24327. */
  24328. function MaterialLoader(manager) {
  24329. Loader.call(this, manager);
  24330. this.textures = {};
  24331. }
  24332. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24333. constructor: MaterialLoader,
  24334. load: function (url, onLoad, onProgress, onError) {
  24335. var scope = this;
  24336. var loader = new FileLoader(scope.manager);
  24337. loader.setPath(scope.path);
  24338. loader.load(url, function (text) {
  24339. onLoad(scope.parse(JSON.parse(text)));
  24340. }, onProgress, onError);
  24341. },
  24342. parse: function (json) {
  24343. var textures = this.textures;
  24344. function getTexture(name) {
  24345. if (textures[name] === undefined) {
  24346. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24347. }
  24348. return textures[name];
  24349. }
  24350. var material = new Materials[json.type]();
  24351. if (json.uuid !== undefined) material.uuid = json.uuid;
  24352. if (json.name !== undefined) material.name = json.name;
  24353. if (json.color !== undefined) material.color.setHex(json.color);
  24354. if (json.roughness !== undefined) material.roughness = json.roughness;
  24355. if (json.metalness !== undefined) material.metalness = json.metalness;
  24356. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24357. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  24358. if (json.specular !== undefined) material.specular.setHex(json.specular);
  24359. if (json.shininess !== undefined) material.shininess = json.shininess;
  24360. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24361. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24362. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  24363. if (json.fog !== undefined) material.fog = json.fog;
  24364. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24365. if (json.blending !== undefined) material.blending = json.blending;
  24366. if (json.combine !== undefined) material.combine = json.combine;
  24367. if (json.side !== undefined) material.side = json.side;
  24368. if (json.opacity !== undefined) material.opacity = json.opacity;
  24369. if (json.transparent !== undefined) material.transparent = json.transparent;
  24370. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24371. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24372. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24373. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24374. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24375. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24376. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24377. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24378. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24379. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24380. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24381. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24382. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24383. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24384. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24385. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24386. if (json.rotation !== undefined) material.rotation = json.rotation;
  24387. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24388. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24389. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24390. if (json.scale !== undefined) material.scale = json.scale;
  24391. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24392. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24393. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24394. if (json.skinning !== undefined) material.skinning = json.skinning;
  24395. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24396. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24397. if (json.dithering !== undefined) material.dithering = json.dithering;
  24398. if (json.visible !== undefined) material.visible = json.visible;
  24399. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24400. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  24401. if (json.uniforms !== undefined) {
  24402. for (var name in json.uniforms) {
  24403. var uniform = json.uniforms[name];
  24404. material.uniforms[name] = {};
  24405. switch (uniform.type) {
  24406. case 't':
  24407. material.uniforms[name].value = getTexture(uniform.value);
  24408. break;
  24409. case 'c':
  24410. material.uniforms[name].value = new Color().setHex(uniform.value);
  24411. break;
  24412. case 'v2':
  24413. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24414. break;
  24415. case 'v3':
  24416. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24417. break;
  24418. case 'v4':
  24419. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24420. break;
  24421. case 'm3':
  24422. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24423. case 'm4':
  24424. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24425. break;
  24426. default:
  24427. material.uniforms[name].value = uniform.value;
  24428. }
  24429. }
  24430. }
  24431. if (json.defines !== undefined) material.defines = json.defines;
  24432. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24433. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24434. if (json.extensions !== undefined) {
  24435. for (var key in json.extensions) {
  24436. material.extensions[key] = json.extensions[key];
  24437. }
  24438. } // Deprecated
  24439. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24440. // for PointsMaterial
  24441. if (json.size !== undefined) material.size = json.size;
  24442. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24443. if (json.map !== undefined) material.map = getTexture(json.map);
  24444. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24445. if (json.alphaMap !== undefined) {
  24446. material.alphaMap = getTexture(json.alphaMap);
  24447. material.transparent = true;
  24448. }
  24449. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24450. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24451. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24452. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24453. if (json.normalScale !== undefined) {
  24454. var normalScale = json.normalScale;
  24455. if (Array.isArray(normalScale) === false) {
  24456. // Blender exporter used to export a scalar. See #7459
  24457. normalScale = [normalScale, normalScale];
  24458. }
  24459. material.normalScale = new Vector2().fromArray(normalScale);
  24460. }
  24461. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24462. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24463. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24464. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24465. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24466. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24467. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24468. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24469. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24470. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24471. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24472. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24473. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24474. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24475. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24476. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24477. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24478. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24479. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24480. return material;
  24481. },
  24482. setTextures: function (value) {
  24483. this.textures = value;
  24484. return this;
  24485. }
  24486. });
  24487. /**
  24488. * @author Don McCurdy / https://www.donmccurdy.com
  24489. */
  24490. var LoaderUtils = {
  24491. decodeText: function (array) {
  24492. if (typeof TextDecoder !== 'undefined') {
  24493. return new TextDecoder().decode(array);
  24494. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24495. // throws a "maximum call stack size exceeded" error for large arrays.
  24496. var s = '';
  24497. for (var i = 0, il = array.length; i < il; i++) {
  24498. // Implicitly assumes little-endian.
  24499. s += String.fromCharCode(array[i]);
  24500. }
  24501. try {
  24502. // merges multi-byte utf-8 characters.
  24503. return decodeURIComponent(escape(s));
  24504. } catch (e) {
  24505. // see #16358
  24506. return s;
  24507. }
  24508. },
  24509. extractUrlBase: function (url) {
  24510. var index = url.lastIndexOf('/');
  24511. if (index === -1) return './';
  24512. return url.substr(0, index + 1);
  24513. }
  24514. };
  24515. /**
  24516. * @author benaadams / https://twitter.com/ben_a_adams
  24517. */
  24518. exports.LoaderUtils = LoaderUtils;
  24519. function InstancedBufferGeometry() {
  24520. BufferGeometry.call(this);
  24521. this.type = 'InstancedBufferGeometry';
  24522. this.maxInstancedCount = undefined;
  24523. }
  24524. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24525. constructor: InstancedBufferGeometry,
  24526. isInstancedBufferGeometry: true,
  24527. copy: function (source) {
  24528. BufferGeometry.prototype.copy.call(this, source);
  24529. this.maxInstancedCount = source.maxInstancedCount;
  24530. return this;
  24531. },
  24532. clone: function () {
  24533. return new this.constructor().copy(this);
  24534. },
  24535. toJSON: function () {
  24536. var data = BufferGeometry.prototype.toJSON.call(this);
  24537. data.maxInstancedCount = this.maxInstancedCount;
  24538. data.isInstancedBufferGeometry = true;
  24539. return data;
  24540. }
  24541. });
  24542. /**
  24543. * @author benaadams / https://twitter.com/ben_a_adams
  24544. */
  24545. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24546. if (typeof normalized === 'number') {
  24547. meshPerAttribute = normalized;
  24548. normalized = false;
  24549. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24550. }
  24551. BufferAttribute.call(this, array, itemSize, normalized);
  24552. this.meshPerAttribute = meshPerAttribute || 1;
  24553. }
  24554. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24555. constructor: InstancedBufferAttribute,
  24556. isInstancedBufferAttribute: true,
  24557. copy: function (source) {
  24558. BufferAttribute.prototype.copy.call(this, source);
  24559. this.meshPerAttribute = source.meshPerAttribute;
  24560. return this;
  24561. },
  24562. toJSON: function () {
  24563. var data = BufferAttribute.prototype.toJSON.call(this);
  24564. data.meshPerAttribute = this.meshPerAttribute;
  24565. data.isInstancedBufferAttribute = true;
  24566. return data;
  24567. }
  24568. });
  24569. /**
  24570. * @author mrdoob / http://mrdoob.com/
  24571. */
  24572. function BufferGeometryLoader(manager) {
  24573. Loader.call(this, manager);
  24574. }
  24575. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24576. constructor: BufferGeometryLoader,
  24577. load: function (url, onLoad, onProgress, onError) {
  24578. var scope = this;
  24579. var loader = new FileLoader(scope.manager);
  24580. loader.setPath(scope.path);
  24581. loader.load(url, function (text) {
  24582. onLoad(scope.parse(JSON.parse(text)));
  24583. }, onProgress, onError);
  24584. },
  24585. parse: function (json) {
  24586. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24587. var index = json.data.index;
  24588. if (index !== undefined) {
  24589. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  24590. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24591. }
  24592. var attributes = json.data.attributes;
  24593. for (var key in attributes) {
  24594. var attribute = attributes[key];
  24595. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24596. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24597. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24598. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24599. geometry.addAttribute(key, bufferAttribute);
  24600. }
  24601. var morphAttributes = json.data.morphAttributes;
  24602. if (morphAttributes) {
  24603. for (var key in morphAttributes) {
  24604. var attributeArray = morphAttributes[key];
  24605. var array = [];
  24606. for (var i = 0, il = attributeArray.length; i < il; i++) {
  24607. var attribute = attributeArray[i];
  24608. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24609. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24610. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24611. array.push(bufferAttribute);
  24612. }
  24613. geometry.morphAttributes[key] = array;
  24614. }
  24615. }
  24616. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24617. if (groups !== undefined) {
  24618. for (var i = 0, n = groups.length; i !== n; ++i) {
  24619. var group = groups[i];
  24620. geometry.addGroup(group.start, group.count, group.materialIndex);
  24621. }
  24622. }
  24623. var boundingSphere = json.data.boundingSphere;
  24624. if (boundingSphere !== undefined) {
  24625. var center = new Vector3();
  24626. if (boundingSphere.center !== undefined) {
  24627. center.fromArray(boundingSphere.center);
  24628. }
  24629. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24630. }
  24631. if (json.name) geometry.name = json.name;
  24632. if (json.userData) geometry.userData = json.userData;
  24633. return geometry;
  24634. }
  24635. });
  24636. var TYPED_ARRAYS = {
  24637. Int8Array: Int8Array,
  24638. Uint8Array: Uint8Array,
  24639. // Workaround for IE11 pre KB2929437. See #11440
  24640. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24641. Int16Array: Int16Array,
  24642. Uint16Array: Uint16Array,
  24643. Int32Array: Int32Array,
  24644. Uint32Array: Uint32Array,
  24645. Float32Array: Float32Array,
  24646. Float64Array: Float64Array
  24647. };
  24648. /**
  24649. * @author mrdoob / http://mrdoob.com/
  24650. */
  24651. function ObjectLoader(manager) {
  24652. Loader.call(this, manager);
  24653. }
  24654. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24655. constructor: ObjectLoader,
  24656. load: function (url, onLoad, onProgress, onError) {
  24657. var scope = this;
  24658. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24659. this.resourcePath = this.resourcePath || path;
  24660. var loader = new FileLoader(scope.manager);
  24661. loader.setPath(this.path);
  24662. loader.load(url, function (text) {
  24663. var json = null;
  24664. try {
  24665. json = JSON.parse(text);
  24666. } catch (error) {
  24667. if (onError !== undefined) onError(error);
  24668. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24669. return;
  24670. }
  24671. var metadata = json.metadata;
  24672. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24673. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24674. return;
  24675. }
  24676. scope.parse(json, onLoad);
  24677. }, onProgress, onError);
  24678. },
  24679. parse: function (json, onLoad) {
  24680. var shapes = this.parseShape(json.shapes);
  24681. var geometries = this.parseGeometries(json.geometries, shapes);
  24682. var images = this.parseImages(json.images, function () {
  24683. if (onLoad !== undefined) onLoad(object);
  24684. });
  24685. var textures = this.parseTextures(json.textures, images);
  24686. var materials = this.parseMaterials(json.materials, textures);
  24687. var object = this.parseObject(json.object, geometries, materials);
  24688. if (json.animations) {
  24689. object.animations = this.parseAnimations(json.animations);
  24690. }
  24691. if (json.images === undefined || json.images.length === 0) {
  24692. if (onLoad !== undefined) onLoad(object);
  24693. }
  24694. return object;
  24695. },
  24696. parseShape: function (json) {
  24697. var shapes = {};
  24698. if (json !== undefined) {
  24699. for (var i = 0, l = json.length; i < l; i++) {
  24700. var shape = new Shape().fromJSON(json[i]);
  24701. shapes[shape.uuid] = shape;
  24702. }
  24703. }
  24704. return shapes;
  24705. },
  24706. parseGeometries: function (json, shapes) {
  24707. var geometries = {};
  24708. if (json !== undefined) {
  24709. var bufferGeometryLoader = new BufferGeometryLoader();
  24710. for (var i = 0, l = json.length; i < l; i++) {
  24711. var geometry;
  24712. var data = json[i];
  24713. switch (data.type) {
  24714. case 'PlaneGeometry':
  24715. case 'PlaneBufferGeometry':
  24716. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24717. break;
  24718. case 'BoxGeometry':
  24719. case 'BoxBufferGeometry':
  24720. case 'CubeGeometry':
  24721. // backwards compatible
  24722. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24723. break;
  24724. case 'CircleGeometry':
  24725. case 'CircleBufferGeometry':
  24726. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24727. break;
  24728. case 'CylinderGeometry':
  24729. case 'CylinderBufferGeometry':
  24730. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24731. break;
  24732. case 'ConeGeometry':
  24733. case 'ConeBufferGeometry':
  24734. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24735. break;
  24736. case 'SphereGeometry':
  24737. case 'SphereBufferGeometry':
  24738. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24739. break;
  24740. case 'DodecahedronGeometry':
  24741. case 'DodecahedronBufferGeometry':
  24742. case 'IcosahedronGeometry':
  24743. case 'IcosahedronBufferGeometry':
  24744. case 'OctahedronGeometry':
  24745. case 'OctahedronBufferGeometry':
  24746. case 'TetrahedronGeometry':
  24747. case 'TetrahedronBufferGeometry':
  24748. geometry = new Geometries[data.type](data.radius, data.detail);
  24749. break;
  24750. case 'RingGeometry':
  24751. case 'RingBufferGeometry':
  24752. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24753. break;
  24754. case 'TorusGeometry':
  24755. case 'TorusBufferGeometry':
  24756. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24757. break;
  24758. case 'TorusKnotGeometry':
  24759. case 'TorusKnotBufferGeometry':
  24760. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24761. break;
  24762. case 'TubeGeometry':
  24763. case 'TubeBufferGeometry':
  24764. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24765. // User defined curves or instances of CurvePath will not be deserialized.
  24766. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24767. break;
  24768. case 'LatheGeometry':
  24769. case 'LatheBufferGeometry':
  24770. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24771. break;
  24772. case 'PolyhedronGeometry':
  24773. case 'PolyhedronBufferGeometry':
  24774. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24775. break;
  24776. case 'ShapeGeometry':
  24777. case 'ShapeBufferGeometry':
  24778. var geometryShapes = [];
  24779. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24780. var shape = shapes[data.shapes[j]];
  24781. geometryShapes.push(shape);
  24782. }
  24783. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24784. break;
  24785. case 'ExtrudeGeometry':
  24786. case 'ExtrudeBufferGeometry':
  24787. var geometryShapes = [];
  24788. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24789. var shape = shapes[data.shapes[j]];
  24790. geometryShapes.push(shape);
  24791. }
  24792. var extrudePath = data.options.extrudePath;
  24793. if (extrudePath !== undefined) {
  24794. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24795. }
  24796. geometry = new Geometries[data.type](geometryShapes, data.options);
  24797. break;
  24798. case 'BufferGeometry':
  24799. case 'InstancedBufferGeometry':
  24800. geometry = bufferGeometryLoader.parse(data);
  24801. break;
  24802. case 'Geometry':
  24803. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  24804. var geometryLoader = new THREE.LegacyJSONLoader();
  24805. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  24806. } else {
  24807. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  24808. }
  24809. break;
  24810. default:
  24811. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24812. continue;
  24813. }
  24814. geometry.uuid = data.uuid;
  24815. if (data.name !== undefined) geometry.name = data.name;
  24816. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24817. geometries[data.uuid] = geometry;
  24818. }
  24819. }
  24820. return geometries;
  24821. },
  24822. parseMaterials: function (json, textures) {
  24823. var cache = {}; // MultiMaterial
  24824. var materials = {};
  24825. if (json !== undefined) {
  24826. var loader = new MaterialLoader();
  24827. loader.setTextures(textures);
  24828. for (var i = 0, l = json.length; i < l; i++) {
  24829. var data = json[i];
  24830. if (data.type === 'MultiMaterial') {
  24831. // Deprecated
  24832. var array = [];
  24833. for (var j = 0; j < data.materials.length; j++) {
  24834. var material = data.materials[j];
  24835. if (cache[material.uuid] === undefined) {
  24836. cache[material.uuid] = loader.parse(material);
  24837. }
  24838. array.push(cache[material.uuid]);
  24839. }
  24840. materials[data.uuid] = array;
  24841. } else {
  24842. if (cache[data.uuid] === undefined) {
  24843. cache[data.uuid] = loader.parse(data);
  24844. }
  24845. materials[data.uuid] = cache[data.uuid];
  24846. }
  24847. }
  24848. }
  24849. return materials;
  24850. },
  24851. parseAnimations: function (json) {
  24852. var animations = [];
  24853. for (var i = 0; i < json.length; i++) {
  24854. var data = json[i];
  24855. var clip = AnimationClip.parse(data);
  24856. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24857. animations.push(clip);
  24858. }
  24859. return animations;
  24860. },
  24861. parseImages: function (json, onLoad) {
  24862. var scope = this;
  24863. var images = {};
  24864. function loadImage(url) {
  24865. scope.manager.itemStart(url);
  24866. return loader.load(url, function () {
  24867. scope.manager.itemEnd(url);
  24868. }, undefined, function () {
  24869. scope.manager.itemError(url);
  24870. scope.manager.itemEnd(url);
  24871. });
  24872. }
  24873. if (json !== undefined && json.length > 0) {
  24874. var manager = new LoadingManager(onLoad);
  24875. var loader = new ImageLoader(manager);
  24876. loader.setCrossOrigin(this.crossOrigin);
  24877. for (var i = 0, il = json.length; i < il; i++) {
  24878. var image = json[i];
  24879. var url = image.url;
  24880. if (Array.isArray(url)) {
  24881. // load array of images e.g CubeTexture
  24882. images[image.uuid] = [];
  24883. for (var j = 0, jl = url.length; j < jl; j++) {
  24884. var currentUrl = url[j];
  24885. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24886. images[image.uuid].push(loadImage(path));
  24887. }
  24888. } else {
  24889. // load single image
  24890. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24891. images[image.uuid] = loadImage(path);
  24892. }
  24893. }
  24894. }
  24895. return images;
  24896. },
  24897. parseTextures: function (json, images) {
  24898. function parseConstant(value, type) {
  24899. if (typeof value === 'number') return value;
  24900. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24901. return type[value];
  24902. }
  24903. var textures = {};
  24904. if (json !== undefined) {
  24905. for (var i = 0, l = json.length; i < l; i++) {
  24906. var data = json[i];
  24907. if (data.image === undefined) {
  24908. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24909. }
  24910. if (images[data.image] === undefined) {
  24911. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24912. }
  24913. var texture;
  24914. if (Array.isArray(images[data.image])) {
  24915. texture = new CubeTexture(images[data.image]);
  24916. } else {
  24917. texture = new Texture(images[data.image]);
  24918. }
  24919. texture.needsUpdate = true;
  24920. texture.uuid = data.uuid;
  24921. if (data.name !== undefined) texture.name = data.name;
  24922. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24923. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24924. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24925. if (data.center !== undefined) texture.center.fromArray(data.center);
  24926. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24927. if (data.wrap !== undefined) {
  24928. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24929. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24930. }
  24931. if (data.format !== undefined) texture.format = data.format;
  24932. if (data.type !== undefined) texture.type = data.type;
  24933. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24934. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24935. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24936. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24937. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24938. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24939. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24940. textures[data.uuid] = texture;
  24941. }
  24942. }
  24943. return textures;
  24944. },
  24945. parseObject: function (data, geometries, materials) {
  24946. var object;
  24947. function getGeometry(name) {
  24948. if (geometries[name] === undefined) {
  24949. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24950. }
  24951. return geometries[name];
  24952. }
  24953. function getMaterial(name) {
  24954. if (name === undefined) return undefined;
  24955. if (Array.isArray(name)) {
  24956. var array = [];
  24957. for (var i = 0, l = name.length; i < l; i++) {
  24958. var uuid = name[i];
  24959. if (materials[uuid] === undefined) {
  24960. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24961. }
  24962. array.push(materials[uuid]);
  24963. }
  24964. return array;
  24965. }
  24966. if (materials[name] === undefined) {
  24967. console.warn('THREE.ObjectLoader: Undefined material', name);
  24968. }
  24969. return materials[name];
  24970. }
  24971. switch (data.type) {
  24972. case 'Scene':
  24973. object = new Scene();
  24974. if (data.background !== undefined) {
  24975. if (Number.isInteger(data.background)) {
  24976. object.background = new Color(data.background);
  24977. }
  24978. }
  24979. if (data.fog !== undefined) {
  24980. if (data.fog.type === 'Fog') {
  24981. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24982. } else if (data.fog.type === 'FogExp2') {
  24983. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24984. }
  24985. }
  24986. break;
  24987. case 'PerspectiveCamera':
  24988. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24989. if (data.focus !== undefined) object.focus = data.focus;
  24990. if (data.zoom !== undefined) object.zoom = data.zoom;
  24991. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24992. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24993. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24994. break;
  24995. case 'OrthographicCamera':
  24996. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24997. if (data.zoom !== undefined) object.zoom = data.zoom;
  24998. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24999. break;
  25000. case 'AmbientLight':
  25001. object = new AmbientLight(data.color, data.intensity);
  25002. break;
  25003. case 'DirectionalLight':
  25004. object = new DirectionalLight(data.color, data.intensity);
  25005. break;
  25006. case 'PointLight':
  25007. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25008. break;
  25009. case 'RectAreaLight':
  25010. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25011. break;
  25012. case 'SpotLight':
  25013. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25014. break;
  25015. case 'HemisphereLight':
  25016. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25017. break;
  25018. case 'SkinnedMesh':
  25019. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  25020. case 'Mesh':
  25021. var geometry = getGeometry(data.geometry);
  25022. var material = getMaterial(data.material);
  25023. if (geometry.bones && geometry.bones.length > 0) {
  25024. object = new SkinnedMesh(geometry, material);
  25025. } else {
  25026. object = new Mesh(geometry, material);
  25027. }
  25028. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  25029. break;
  25030. case 'LOD':
  25031. object = new LOD();
  25032. break;
  25033. case 'Line':
  25034. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  25035. break;
  25036. case 'LineLoop':
  25037. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25038. break;
  25039. case 'LineSegments':
  25040. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25041. break;
  25042. case 'PointCloud':
  25043. case 'Points':
  25044. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25045. break;
  25046. case 'Sprite':
  25047. object = new Sprite(getMaterial(data.material));
  25048. break;
  25049. case 'Group':
  25050. object = new Group();
  25051. break;
  25052. default:
  25053. object = new Object3D();
  25054. }
  25055. object.uuid = data.uuid;
  25056. if (data.name !== undefined) object.name = data.name;
  25057. if (data.matrix !== undefined) {
  25058. object.matrix.fromArray(data.matrix);
  25059. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25060. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25061. } else {
  25062. if (data.position !== undefined) object.position.fromArray(data.position);
  25063. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25064. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25065. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25066. }
  25067. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25068. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25069. if (data.shadow) {
  25070. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25071. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25072. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25073. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25074. }
  25075. if (data.visible !== undefined) object.visible = data.visible;
  25076. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25077. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25078. if (data.userData !== undefined) object.userData = data.userData;
  25079. if (data.layers !== undefined) object.layers.mask = data.layers;
  25080. if (data.children !== undefined) {
  25081. var children = data.children;
  25082. for (var i = 0; i < children.length; i++) {
  25083. object.add(this.parseObject(children[i], geometries, materials));
  25084. }
  25085. }
  25086. if (data.type === 'LOD') {
  25087. var levels = data.levels;
  25088. for (var l = 0; l < levels.length; l++) {
  25089. var level = levels[l];
  25090. var child = object.getObjectByProperty('uuid', level.object);
  25091. if (child !== undefined) {
  25092. object.addLevel(child, level.distance);
  25093. }
  25094. }
  25095. }
  25096. return object;
  25097. }
  25098. });
  25099. var TEXTURE_MAPPING = {
  25100. UVMapping: UVMapping,
  25101. CubeReflectionMapping: CubeReflectionMapping,
  25102. CubeRefractionMapping: CubeRefractionMapping,
  25103. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25104. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25105. SphericalReflectionMapping: SphericalReflectionMapping,
  25106. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25107. CubeUVRefractionMapping: CubeUVRefractionMapping
  25108. };
  25109. var TEXTURE_WRAPPING = {
  25110. RepeatWrapping: RepeatWrapping,
  25111. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25112. MirroredRepeatWrapping: MirroredRepeatWrapping
  25113. };
  25114. var TEXTURE_FILTER = {
  25115. NearestFilter: NearestFilter,
  25116. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25117. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25118. LinearFilter: LinearFilter,
  25119. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25120. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25121. };
  25122. /**
  25123. * @author thespite / http://clicktorelease.com/
  25124. */
  25125. function ImageBitmapLoader(manager) {
  25126. if (typeof createImageBitmap === 'undefined') {
  25127. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25128. }
  25129. if (typeof fetch === 'undefined') {
  25130. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25131. }
  25132. Loader.call(this, manager);
  25133. this.options = undefined;
  25134. }
  25135. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25136. constructor: ImageBitmapLoader,
  25137. setOptions: function setOptions(options) {
  25138. this.options = options;
  25139. return this;
  25140. },
  25141. load: function (url, onLoad, onProgress, onError) {
  25142. if (url === undefined) url = '';
  25143. if (this.path !== undefined) url = this.path + url;
  25144. url = this.manager.resolveURL(url);
  25145. var scope = this;
  25146. var cached = Cache.get(url);
  25147. if (cached !== undefined) {
  25148. scope.manager.itemStart(url);
  25149. setTimeout(function () {
  25150. if (onLoad) onLoad(cached);
  25151. scope.manager.itemEnd(url);
  25152. }, 0);
  25153. return cached;
  25154. }
  25155. fetch(url).then(function (res) {
  25156. return res.blob();
  25157. }).then(function (blob) {
  25158. if (scope.options === undefined) {
  25159. // Workaround for FireFox. It causes an error if you pass options.
  25160. return createImageBitmap(blob);
  25161. } else {
  25162. return createImageBitmap(blob, scope.options);
  25163. }
  25164. }).then(function (imageBitmap) {
  25165. Cache.add(url, imageBitmap);
  25166. if (onLoad) onLoad(imageBitmap);
  25167. scope.manager.itemEnd(url);
  25168. }).catch(function (e) {
  25169. if (onError) onError(e);
  25170. scope.manager.itemError(url);
  25171. scope.manager.itemEnd(url);
  25172. });
  25173. scope.manager.itemStart(url);
  25174. }
  25175. });
  25176. /**
  25177. * @author zz85 / http://www.lab4games.net/zz85/blog
  25178. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25179. **/
  25180. function ShapePath() {
  25181. this.type = 'ShapePath';
  25182. this.color = new Color();
  25183. this.subPaths = [];
  25184. this.currentPath = null;
  25185. }
  25186. Object.assign(ShapePath.prototype, {
  25187. moveTo: function (x, y) {
  25188. this.currentPath = new Path();
  25189. this.subPaths.push(this.currentPath);
  25190. this.currentPath.moveTo(x, y);
  25191. },
  25192. lineTo: function (x, y) {
  25193. this.currentPath.lineTo(x, y);
  25194. },
  25195. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25196. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25197. },
  25198. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25199. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25200. },
  25201. splineThru: function (pts) {
  25202. this.currentPath.splineThru(pts);
  25203. },
  25204. toShapes: function (isCCW, noHoles) {
  25205. function toShapesNoHoles(inSubpaths) {
  25206. var shapes = [];
  25207. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  25208. var tmpPath = inSubpaths[i];
  25209. var tmpShape = new Shape();
  25210. tmpShape.curves = tmpPath.curves;
  25211. shapes.push(tmpShape);
  25212. }
  25213. return shapes;
  25214. }
  25215. function isPointInsidePolygon(inPt, inPolygon) {
  25216. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25217. // toggling of inside/outside at every single! intersection point of an edge
  25218. // with the horizontal line through inPt, left of inPt
  25219. // not counting lowerY endpoints of edges and whole edges on that line
  25220. var inside = false;
  25221. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25222. var edgeLowPt = inPolygon[p];
  25223. var edgeHighPt = inPolygon[q];
  25224. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25225. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25226. if (Math.abs(edgeDy) > Number.EPSILON) {
  25227. // not parallel
  25228. if (edgeDy < 0) {
  25229. edgeLowPt = inPolygon[q];
  25230. edgeDx = -edgeDx;
  25231. edgeHighPt = inPolygon[p];
  25232. edgeDy = -edgeDy;
  25233. }
  25234. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25235. if (inPt.y === edgeLowPt.y) {
  25236. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25237. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25238. } else {
  25239. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25240. if (perpEdge === 0) return true; // inPt is on contour ?
  25241. if (perpEdge < 0) continue;
  25242. inside = !inside; // true intersection left of inPt
  25243. }
  25244. } else {
  25245. // parallel or collinear
  25246. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25247. // edge lies on the same horizontal line as inPt
  25248. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25249. // continue;
  25250. }
  25251. }
  25252. return inside;
  25253. }
  25254. var isClockWise = ShapeUtils.isClockWise;
  25255. var subPaths = this.subPaths;
  25256. if (subPaths.length === 0) return [];
  25257. if (noHoles === true) return toShapesNoHoles(subPaths);
  25258. var solid,
  25259. tmpPath,
  25260. tmpShape,
  25261. shapes = [];
  25262. if (subPaths.length === 1) {
  25263. tmpPath = subPaths[0];
  25264. tmpShape = new Shape();
  25265. tmpShape.curves = tmpPath.curves;
  25266. shapes.push(tmpShape);
  25267. return shapes;
  25268. }
  25269. var holesFirst = !isClockWise(subPaths[0].getPoints());
  25270. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25271. var betterShapeHoles = [];
  25272. var newShapes = [];
  25273. var newShapeHoles = [];
  25274. var mainIdx = 0;
  25275. var tmpPoints;
  25276. newShapes[mainIdx] = undefined;
  25277. newShapeHoles[mainIdx] = [];
  25278. for (var i = 0, l = subPaths.length; i < l; i++) {
  25279. tmpPath = subPaths[i];
  25280. tmpPoints = tmpPath.getPoints();
  25281. solid = isClockWise(tmpPoints);
  25282. solid = isCCW ? !solid : solid;
  25283. if (solid) {
  25284. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25285. newShapes[mainIdx] = {
  25286. s: new Shape(),
  25287. p: tmpPoints
  25288. };
  25289. newShapes[mainIdx].s.curves = tmpPath.curves;
  25290. if (holesFirst) mainIdx++;
  25291. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25292. } else {
  25293. newShapeHoles[mainIdx].push({
  25294. h: tmpPath,
  25295. p: tmpPoints[0]
  25296. }); //console.log('ccw', i);
  25297. }
  25298. } // only Holes? -> probably all Shapes with wrong orientation
  25299. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25300. if (newShapes.length > 1) {
  25301. var ambiguous = false;
  25302. var toChange = [];
  25303. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25304. betterShapeHoles[sIdx] = [];
  25305. }
  25306. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25307. var sho = newShapeHoles[sIdx];
  25308. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  25309. var ho = sho[hIdx];
  25310. var hole_unassigned = true;
  25311. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25312. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25313. if (sIdx !== s2Idx) toChange.push({
  25314. froms: sIdx,
  25315. tos: s2Idx,
  25316. hole: hIdx
  25317. });
  25318. if (hole_unassigned) {
  25319. hole_unassigned = false;
  25320. betterShapeHoles[s2Idx].push(ho);
  25321. } else {
  25322. ambiguous = true;
  25323. }
  25324. }
  25325. }
  25326. if (hole_unassigned) {
  25327. betterShapeHoles[sIdx].push(ho);
  25328. }
  25329. }
  25330. } // console.log("ambiguous: ", ambiguous);
  25331. if (toChange.length > 0) {
  25332. // console.log("to change: ", toChange);
  25333. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25334. }
  25335. }
  25336. var tmpHoles;
  25337. for (var i = 0, il = newShapes.length; i < il; i++) {
  25338. tmpShape = newShapes[i].s;
  25339. shapes.push(tmpShape);
  25340. tmpHoles = newShapeHoles[i];
  25341. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  25342. tmpShape.holes.push(tmpHoles[j].h);
  25343. }
  25344. } //console.log("shape", shapes);
  25345. return shapes;
  25346. }
  25347. });
  25348. /**
  25349. * @author zz85 / http://www.lab4games.net/zz85/blog
  25350. * @author mrdoob / http://mrdoob.com/
  25351. */
  25352. function Font(data) {
  25353. this.type = 'Font';
  25354. this.data = data;
  25355. }
  25356. Object.assign(Font.prototype, {
  25357. isFont: true,
  25358. generateShapes: function (text, size) {
  25359. if (size === undefined) size = 100;
  25360. var shapes = [];
  25361. var paths = createPaths(text, size, this.data);
  25362. for (var p = 0, pl = paths.length; p < pl; p++) {
  25363. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25364. }
  25365. return shapes;
  25366. }
  25367. });
  25368. function createPaths(text, size, data) {
  25369. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  25370. var scale = size / data.resolution;
  25371. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25372. var paths = [];
  25373. var offsetX = 0,
  25374. offsetY = 0;
  25375. for (var i = 0; i < chars.length; i++) {
  25376. var char = chars[i];
  25377. if (char === '\n') {
  25378. offsetX = 0;
  25379. offsetY -= line_height;
  25380. } else {
  25381. var ret = createPath(char, scale, offsetX, offsetY, data);
  25382. offsetX += ret.offsetX;
  25383. paths.push(ret.path);
  25384. }
  25385. }
  25386. return paths;
  25387. }
  25388. function createPath(char, scale, offsetX, offsetY, data) {
  25389. var glyph = data.glyphs[char] || data.glyphs['?'];
  25390. if (!glyph) {
  25391. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25392. return;
  25393. }
  25394. var path = new ShapePath();
  25395. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25396. if (glyph.o) {
  25397. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25398. for (var i = 0, l = outline.length; i < l;) {
  25399. var action = outline[i++];
  25400. switch (action) {
  25401. case 'm':
  25402. // moveTo
  25403. x = outline[i++] * scale + offsetX;
  25404. y = outline[i++] * scale + offsetY;
  25405. path.moveTo(x, y);
  25406. break;
  25407. case 'l':
  25408. // lineTo
  25409. x = outline[i++] * scale + offsetX;
  25410. y = outline[i++] * scale + offsetY;
  25411. path.lineTo(x, y);
  25412. break;
  25413. case 'q':
  25414. // quadraticCurveTo
  25415. cpx = outline[i++] * scale + offsetX;
  25416. cpy = outline[i++] * scale + offsetY;
  25417. cpx1 = outline[i++] * scale + offsetX;
  25418. cpy1 = outline[i++] * scale + offsetY;
  25419. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25420. break;
  25421. case 'b':
  25422. // bezierCurveTo
  25423. cpx = outline[i++] * scale + offsetX;
  25424. cpy = outline[i++] * scale + offsetY;
  25425. cpx1 = outline[i++] * scale + offsetX;
  25426. cpy1 = outline[i++] * scale + offsetY;
  25427. cpx2 = outline[i++] * scale + offsetX;
  25428. cpy2 = outline[i++] * scale + offsetY;
  25429. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25430. break;
  25431. }
  25432. }
  25433. }
  25434. return {
  25435. offsetX: glyph.ha * scale,
  25436. path: path
  25437. };
  25438. }
  25439. /**
  25440. * @author mrdoob / http://mrdoob.com/
  25441. */
  25442. function FontLoader(manager) {
  25443. Loader.call(this, manager);
  25444. }
  25445. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25446. constructor: FontLoader,
  25447. load: function (url, onLoad, onProgress, onError) {
  25448. var scope = this;
  25449. var loader = new FileLoader(this.manager);
  25450. loader.setPath(this.path);
  25451. loader.load(url, function (text) {
  25452. var json;
  25453. try {
  25454. json = JSON.parse(text);
  25455. } catch (e) {
  25456. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25457. json = JSON.parse(text.substring(65, text.length - 2));
  25458. }
  25459. var font = scope.parse(json);
  25460. if (onLoad) onLoad(font);
  25461. }, onProgress, onError);
  25462. },
  25463. parse: function (json) {
  25464. return new Font(json);
  25465. }
  25466. });
  25467. /**
  25468. * @author mrdoob / http://mrdoob.com/
  25469. */
  25470. var _context;
  25471. var AudioContext = {
  25472. getContext: function () {
  25473. if (_context === undefined) {
  25474. _context = new (window.AudioContext || window.webkitAudioContext)();
  25475. }
  25476. return _context;
  25477. },
  25478. setContext: function (value) {
  25479. _context = value;
  25480. }
  25481. };
  25482. /**
  25483. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25484. */
  25485. exports.AudioContext = AudioContext;
  25486. function AudioLoader(manager) {
  25487. Loader.call(this, manager);
  25488. }
  25489. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25490. constructor: AudioLoader,
  25491. load: function (url, onLoad, onProgress, onError) {
  25492. var loader = new FileLoader(this.manager);
  25493. loader.setResponseType('arraybuffer');
  25494. loader.setPath(this.path);
  25495. loader.load(url, function (buffer) {
  25496. // Create a copy of the buffer. The `decodeAudioData` method
  25497. // detaches the buffer when complete, preventing reuse.
  25498. var bufferCopy = buffer.slice(0);
  25499. var context = AudioContext.getContext();
  25500. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25501. onLoad(audioBuffer);
  25502. });
  25503. }, onProgress, onError);
  25504. }
  25505. });
  25506. /**
  25507. * @author bhouston / http://clara.io
  25508. * @author WestLangley / http://github.com/WestLangley
  25509. *
  25510. * Primary reference:
  25511. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25512. *
  25513. * Secondary reference:
  25514. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25515. */
  25516. // 3-band SH defined by 9 coefficients
  25517. function SphericalHarmonics3() {
  25518. this.coefficients = [];
  25519. for (var i = 0; i < 9; i++) {
  25520. this.coefficients.push(new Vector3());
  25521. }
  25522. }
  25523. Object.assign(SphericalHarmonics3.prototype, {
  25524. isSphericalHarmonics3: true,
  25525. set: function (coefficients) {
  25526. for (var i = 0; i < 9; i++) {
  25527. this.coefficients[i].copy(coefficients[i]);
  25528. }
  25529. return this;
  25530. },
  25531. zero: function () {
  25532. for (var i = 0; i < 9; i++) {
  25533. this.coefficients[i].set(0, 0, 0);
  25534. }
  25535. return this;
  25536. },
  25537. // get the radiance in the direction of the normal
  25538. // target is a Vector3
  25539. getAt: function (normal, target) {
  25540. // normal is assumed to be unit length
  25541. var x = normal.x,
  25542. y = normal.y,
  25543. z = normal.z;
  25544. var coeff = this.coefficients; // band 0
  25545. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  25546. target.addScale(coeff[1], 0.488603 * y);
  25547. target.addScale(coeff[2], 0.488603 * z);
  25548. target.addScale(coeff[3], 0.488603 * x); // band 2
  25549. target.addScale(coeff[4], 1.092548 * (x * y));
  25550. target.addScale(coeff[5], 1.092548 * (y * z));
  25551. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  25552. target.addScale(coeff[7], 1.092548 * (x * z));
  25553. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  25554. return target;
  25555. },
  25556. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25557. // target is a Vector3
  25558. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25559. getIrradianceAt: function (normal, target) {
  25560. // normal is assumed to be unit length
  25561. var x = normal.x,
  25562. y = normal.y,
  25563. z = normal.z;
  25564. var coeff = this.coefficients; // band 0
  25565. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  25566. // band 1
  25567. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  25568. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  25569. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  25570. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  25571. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  25572. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  25573. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  25574. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  25575. return target;
  25576. },
  25577. add: function (sh) {
  25578. for (var i = 0; i < 9; i++) {
  25579. this.coefficients[i].add(sh.coefficients[i]);
  25580. }
  25581. return this;
  25582. },
  25583. scale: function (s) {
  25584. for (var i = 0; i < 9; i++) {
  25585. this.coefficients[i].multiplyScalar(s);
  25586. }
  25587. return this;
  25588. },
  25589. lerp: function (sh, alpha) {
  25590. for (var i = 0; i < 9; i++) {
  25591. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  25592. }
  25593. return this;
  25594. },
  25595. equals: function (sh) {
  25596. for (var i = 0; i < 9; i++) {
  25597. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  25598. return false;
  25599. }
  25600. }
  25601. return true;
  25602. },
  25603. copy: function (sh) {
  25604. return this.set(sh.coefficients);
  25605. },
  25606. clone: function () {
  25607. return new this.constructor().copy(this);
  25608. },
  25609. fromArray: function (array, offset) {
  25610. if (offset === undefined) offset = 0;
  25611. var coefficients = this.coefficients;
  25612. for (var i = 0; i < 9; i++) {
  25613. coefficients[i].fromArray(array, offset + i * 3);
  25614. }
  25615. return this;
  25616. },
  25617. toArray: function (array, offset) {
  25618. if (array === undefined) array = [];
  25619. if (offset === undefined) offset = 0;
  25620. var coefficients = this.coefficients;
  25621. for (var i = 0; i < 9; i++) {
  25622. coefficients[i].toArray(array, offset + i * 3);
  25623. }
  25624. return array;
  25625. }
  25626. });
  25627. Object.assign(SphericalHarmonics3, {
  25628. // evaluate the basis functions
  25629. // shBasis is an Array[ 9 ]
  25630. getBasisAt: function (normal, shBasis) {
  25631. // normal is assumed to be unit length
  25632. var x = normal.x,
  25633. y = normal.y,
  25634. z = normal.z; // band 0
  25635. shBasis[0] = 0.282095; // band 1
  25636. shBasis[1] = 0.488603 * y;
  25637. shBasis[2] = 0.488603 * z;
  25638. shBasis[3] = 0.488603 * x; // band 2
  25639. shBasis[4] = 1.092548 * x * y;
  25640. shBasis[5] = 1.092548 * y * z;
  25641. shBasis[6] = 0.315392 * (3 * z * z - 1);
  25642. shBasis[7] = 1.092548 * x * z;
  25643. shBasis[8] = 0.546274 * (x * x - y * y);
  25644. }
  25645. });
  25646. /**
  25647. * @author WestLangley / http://github.com/WestLangley
  25648. *
  25649. * A LightProbe is a source of indirect-diffuse light
  25650. */
  25651. function LightProbe(sh, intensity) {
  25652. Light.call(this, undefined, intensity);
  25653. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  25654. }
  25655. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  25656. constructor: LightProbe,
  25657. isLightProbe: true,
  25658. copy: function (source) {
  25659. Light.prototype.copy.call(this, source);
  25660. this.sh.copy(source.sh);
  25661. this.intensity = source.intensity;
  25662. return this;
  25663. },
  25664. toJSON: function (meta) {
  25665. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25666. return data;
  25667. }
  25668. });
  25669. /**
  25670. * @author WestLangley / http://github.com/WestLangley
  25671. */
  25672. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25673. LightProbe.call(this, undefined, intensity);
  25674. var color1 = new Color().set(skyColor);
  25675. var color2 = new Color().set(groundColor);
  25676. var sky = new Vector3(color1.r, color1.g, color1.b);
  25677. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25678. var c0 = Math.sqrt(Math.PI);
  25679. var c1 = c0 * Math.sqrt(0.75);
  25680. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25681. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25682. }
  25683. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25684. constructor: HemisphereLightProbe,
  25685. isHemisphereLightProbe: true,
  25686. copy: function (source) {
  25687. // modifying colors not currently supported
  25688. LightProbe.prototype.copy.call(this, source);
  25689. return this;
  25690. },
  25691. toJSON: function (meta) {
  25692. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25693. return data;
  25694. }
  25695. });
  25696. /**
  25697. * @author WestLangley / http://github.com/WestLangley
  25698. */
  25699. function AmbientLightProbe(color, intensity) {
  25700. LightProbe.call(this, undefined, intensity);
  25701. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25702. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25703. }
  25704. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25705. constructor: AmbientLightProbe,
  25706. isAmbientLightProbe: true,
  25707. copy: function (source) {
  25708. // modifying color not currently supported
  25709. LightProbe.prototype.copy.call(this, source);
  25710. return this;
  25711. },
  25712. toJSON: function (meta) {
  25713. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25714. return data;
  25715. }
  25716. });
  25717. var _eyeRight = new Matrix4();
  25718. var _eyeLeft = new Matrix4();
  25719. /**
  25720. * @author mrdoob / http://mrdoob.com/
  25721. */
  25722. function StereoCamera() {
  25723. this.type = 'StereoCamera';
  25724. this.aspect = 1;
  25725. this.eyeSep = 0.064;
  25726. this.cameraL = new PerspectiveCamera();
  25727. this.cameraL.layers.enable(1);
  25728. this.cameraL.matrixAutoUpdate = false;
  25729. this.cameraR = new PerspectiveCamera();
  25730. this.cameraR.layers.enable(2);
  25731. this.cameraR.matrixAutoUpdate = false;
  25732. this._cache = {
  25733. focus: null,
  25734. fov: null,
  25735. aspect: null,
  25736. near: null,
  25737. far: null,
  25738. zoom: null,
  25739. eyeSep: null
  25740. };
  25741. }
  25742. Object.assign(StereoCamera.prototype, {
  25743. update: function (camera) {
  25744. var cache = this._cache;
  25745. 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;
  25746. if (needsUpdate) {
  25747. cache.focus = camera.focus;
  25748. cache.fov = camera.fov;
  25749. cache.aspect = camera.aspect * this.aspect;
  25750. cache.near = camera.near;
  25751. cache.far = camera.far;
  25752. cache.zoom = camera.zoom;
  25753. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25754. // http://paulbourke.net/stereographics/stereorender/
  25755. var projectionMatrix = camera.projectionMatrix.clone();
  25756. var eyeSepHalf = cache.eyeSep / 2;
  25757. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25758. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25759. var xmin, xmax; // translate xOffset
  25760. _eyeLeft.elements[12] = -eyeSepHalf;
  25761. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25762. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25763. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25764. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25765. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25766. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25767. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25768. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25769. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25770. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25771. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25772. }
  25773. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25774. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25775. }
  25776. });
  25777. /**
  25778. * @author alteredq / http://alteredqualia.com/
  25779. */
  25780. function Clock(autoStart) {
  25781. this.autoStart = autoStart !== undefined ? autoStart : true;
  25782. this.startTime = 0;
  25783. this.oldTime = 0;
  25784. this.elapsedTime = 0;
  25785. this.running = false;
  25786. }
  25787. Object.assign(Clock.prototype, {
  25788. start: function () {
  25789. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25790. this.oldTime = this.startTime;
  25791. this.elapsedTime = 0;
  25792. this.running = true;
  25793. },
  25794. stop: function () {
  25795. this.getElapsedTime();
  25796. this.running = false;
  25797. this.autoStart = false;
  25798. },
  25799. getElapsedTime: function () {
  25800. this.getDelta();
  25801. return this.elapsedTime;
  25802. },
  25803. getDelta: function () {
  25804. var diff = 0;
  25805. if (this.autoStart && !this.running) {
  25806. this.start();
  25807. return 0;
  25808. }
  25809. if (this.running) {
  25810. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25811. diff = (newTime - this.oldTime) / 1000;
  25812. this.oldTime = newTime;
  25813. this.elapsedTime += diff;
  25814. }
  25815. return diff;
  25816. }
  25817. });
  25818. /**
  25819. * @author mrdoob / http://mrdoob.com/
  25820. */
  25821. var _position$2 = new Vector3();
  25822. var _quaternion$3 = new Quaternion();
  25823. var _scale$1 = new Vector3();
  25824. var _orientation = new Vector3();
  25825. function AudioListener() {
  25826. Object3D.call(this);
  25827. this.type = 'AudioListener';
  25828. this.context = AudioContext.getContext();
  25829. this.gain = this.context.createGain();
  25830. this.gain.connect(this.context.destination);
  25831. this.filter = null;
  25832. this.timeDelta = 0; // private
  25833. this._clock = new Clock();
  25834. }
  25835. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25836. constructor: AudioListener,
  25837. getInput: function () {
  25838. return this.gain;
  25839. },
  25840. removeFilter: function () {
  25841. if (this.filter !== null) {
  25842. this.gain.disconnect(this.filter);
  25843. this.filter.disconnect(this.context.destination);
  25844. this.gain.connect(this.context.destination);
  25845. this.filter = null;
  25846. }
  25847. return this;
  25848. },
  25849. getFilter: function () {
  25850. return this.filter;
  25851. },
  25852. setFilter: function (value) {
  25853. if (this.filter !== null) {
  25854. this.gain.disconnect(this.filter);
  25855. this.filter.disconnect(this.context.destination);
  25856. } else {
  25857. this.gain.disconnect(this.context.destination);
  25858. }
  25859. this.filter = value;
  25860. this.gain.connect(this.filter);
  25861. this.filter.connect(this.context.destination);
  25862. return this;
  25863. },
  25864. getMasterVolume: function () {
  25865. return this.gain.gain.value;
  25866. },
  25867. setMasterVolume: function (value) {
  25868. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25869. return this;
  25870. },
  25871. updateMatrixWorld: function (force) {
  25872. Object3D.prototype.updateMatrixWorld.call(this, force);
  25873. var listener = this.context.listener;
  25874. var up = this.up;
  25875. this.timeDelta = this._clock.getDelta();
  25876. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25877. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25878. if (listener.positionX) {
  25879. // code path for Chrome (see #14393)
  25880. var endTime = this.context.currentTime + this.timeDelta;
  25881. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25882. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25883. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25884. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25885. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25886. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25887. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25888. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25889. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25890. } else {
  25891. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25892. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25893. }
  25894. }
  25895. });
  25896. /**
  25897. * @author mrdoob / http://mrdoob.com/
  25898. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25899. */
  25900. function Audio(listener) {
  25901. Object3D.call(this);
  25902. this.type = 'Audio';
  25903. this.listener = listener;
  25904. this.context = listener.context;
  25905. this.gain = this.context.createGain();
  25906. this.gain.connect(listener.getInput());
  25907. this.autoplay = false;
  25908. this.buffer = null;
  25909. this.detune = 0;
  25910. this.loop = false;
  25911. this.startTime = 0;
  25912. this.offset = 0;
  25913. this.duration = undefined;
  25914. this.playbackRate = 1;
  25915. this.isPlaying = false;
  25916. this.hasPlaybackControl = true;
  25917. this.sourceType = 'empty';
  25918. this.filters = [];
  25919. }
  25920. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25921. constructor: Audio,
  25922. getOutput: function () {
  25923. return this.gain;
  25924. },
  25925. setNodeSource: function (audioNode) {
  25926. this.hasPlaybackControl = false;
  25927. this.sourceType = 'audioNode';
  25928. this.source = audioNode;
  25929. this.connect();
  25930. return this;
  25931. },
  25932. setMediaElementSource: function (mediaElement) {
  25933. this.hasPlaybackControl = false;
  25934. this.sourceType = 'mediaNode';
  25935. this.source = this.context.createMediaElementSource(mediaElement);
  25936. this.connect();
  25937. return this;
  25938. },
  25939. setMediaStreamSource: function (mediaStream) {
  25940. this.hasPlaybackControl = false;
  25941. this.sourceType = 'mediaStreamNode';
  25942. this.source = this.context.createMediaStreamSource(mediaStream);
  25943. this.connect();
  25944. return this;
  25945. },
  25946. setBuffer: function (audioBuffer) {
  25947. this.buffer = audioBuffer;
  25948. this.sourceType = 'buffer';
  25949. if (this.autoplay) this.play();
  25950. return this;
  25951. },
  25952. play: function () {
  25953. if (this.isPlaying === true) {
  25954. console.warn('THREE.Audio: Audio is already playing.');
  25955. return;
  25956. }
  25957. if (this.hasPlaybackControl === false) {
  25958. console.warn('THREE.Audio: this Audio has no playback control.');
  25959. return;
  25960. }
  25961. var source = this.context.createBufferSource();
  25962. source.buffer = this.buffer;
  25963. source.loop = this.loop;
  25964. source.onended = this.onEnded.bind(this);
  25965. this.startTime = this.context.currentTime;
  25966. source.start(this.startTime, this.offset, this.duration);
  25967. this.isPlaying = true;
  25968. this.source = source;
  25969. this.setDetune(this.detune);
  25970. this.setPlaybackRate(this.playbackRate);
  25971. return this.connect();
  25972. },
  25973. pause: function () {
  25974. if (this.hasPlaybackControl === false) {
  25975. console.warn('THREE.Audio: this Audio has no playback control.');
  25976. return;
  25977. }
  25978. if (this.isPlaying === true) {
  25979. this.source.stop();
  25980. this.source.onended = null;
  25981. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  25982. this.isPlaying = false;
  25983. }
  25984. return this;
  25985. },
  25986. stop: function () {
  25987. if (this.hasPlaybackControl === false) {
  25988. console.warn('THREE.Audio: this Audio has no playback control.');
  25989. return;
  25990. }
  25991. this.source.stop();
  25992. this.source.onended = null;
  25993. this.offset = 0;
  25994. this.isPlaying = false;
  25995. return this;
  25996. },
  25997. connect: function () {
  25998. if (this.filters.length > 0) {
  25999. this.source.connect(this.filters[0]);
  26000. for (var i = 1, l = this.filters.length; i < l; i++) {
  26001. this.filters[i - 1].connect(this.filters[i]);
  26002. }
  26003. this.filters[this.filters.length - 1].connect(this.getOutput());
  26004. } else {
  26005. this.source.connect(this.getOutput());
  26006. }
  26007. return this;
  26008. },
  26009. disconnect: function () {
  26010. if (this.filters.length > 0) {
  26011. this.source.disconnect(this.filters[0]);
  26012. for (var i = 1, l = this.filters.length; i < l; i++) {
  26013. this.filters[i - 1].disconnect(this.filters[i]);
  26014. }
  26015. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26016. } else {
  26017. this.source.disconnect(this.getOutput());
  26018. }
  26019. return this;
  26020. },
  26021. getFilters: function () {
  26022. return this.filters;
  26023. },
  26024. setFilters: function (value) {
  26025. if (!value) value = [];
  26026. if (this.isPlaying === true) {
  26027. this.disconnect();
  26028. this.filters = value;
  26029. this.connect();
  26030. } else {
  26031. this.filters = value;
  26032. }
  26033. return this;
  26034. },
  26035. setDetune: function (value) {
  26036. this.detune = value;
  26037. if (this.source.detune === undefined) return; // only set detune when available
  26038. if (this.isPlaying === true) {
  26039. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26040. }
  26041. return this;
  26042. },
  26043. getDetune: function () {
  26044. return this.detune;
  26045. },
  26046. getFilter: function () {
  26047. return this.getFilters()[0];
  26048. },
  26049. setFilter: function (filter) {
  26050. return this.setFilters(filter ? [filter] : []);
  26051. },
  26052. setPlaybackRate: function (value) {
  26053. if (this.hasPlaybackControl === false) {
  26054. console.warn('THREE.Audio: this Audio has no playback control.');
  26055. return;
  26056. }
  26057. this.playbackRate = value;
  26058. if (this.isPlaying === true) {
  26059. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26060. }
  26061. return this;
  26062. },
  26063. getPlaybackRate: function () {
  26064. return this.playbackRate;
  26065. },
  26066. onEnded: function () {
  26067. this.isPlaying = false;
  26068. },
  26069. getLoop: function () {
  26070. if (this.hasPlaybackControl === false) {
  26071. console.warn('THREE.Audio: this Audio has no playback control.');
  26072. return false;
  26073. }
  26074. return this.loop;
  26075. },
  26076. setLoop: function (value) {
  26077. if (this.hasPlaybackControl === false) {
  26078. console.warn('THREE.Audio: this Audio has no playback control.');
  26079. return;
  26080. }
  26081. this.loop = value;
  26082. if (this.isPlaying === true) {
  26083. this.source.loop = this.loop;
  26084. }
  26085. return this;
  26086. },
  26087. getVolume: function () {
  26088. return this.gain.gain.value;
  26089. },
  26090. setVolume: function (value) {
  26091. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26092. return this;
  26093. }
  26094. });
  26095. /**
  26096. * @author mrdoob / http://mrdoob.com/
  26097. */
  26098. var _position$3 = new Vector3();
  26099. var _quaternion$4 = new Quaternion();
  26100. var _scale$2 = new Vector3();
  26101. var _orientation$1 = new Vector3();
  26102. function PositionalAudio(listener) {
  26103. Audio.call(this, listener);
  26104. this.panner = this.context.createPanner();
  26105. this.panner.panningModel = 'HRTF';
  26106. this.panner.connect(this.gain);
  26107. }
  26108. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  26109. constructor: PositionalAudio,
  26110. getOutput: function () {
  26111. return this.panner;
  26112. },
  26113. getRefDistance: function () {
  26114. return this.panner.refDistance;
  26115. },
  26116. setRefDistance: function (value) {
  26117. this.panner.refDistance = value;
  26118. return this;
  26119. },
  26120. getRolloffFactor: function () {
  26121. return this.panner.rolloffFactor;
  26122. },
  26123. setRolloffFactor: function (value) {
  26124. this.panner.rolloffFactor = value;
  26125. return this;
  26126. },
  26127. getDistanceModel: function () {
  26128. return this.panner.distanceModel;
  26129. },
  26130. setDistanceModel: function (value) {
  26131. this.panner.distanceModel = value;
  26132. return this;
  26133. },
  26134. getMaxDistance: function () {
  26135. return this.panner.maxDistance;
  26136. },
  26137. setMaxDistance: function (value) {
  26138. this.panner.maxDistance = value;
  26139. return this;
  26140. },
  26141. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26142. this.panner.coneInnerAngle = coneInnerAngle;
  26143. this.panner.coneOuterAngle = coneOuterAngle;
  26144. this.panner.coneOuterGain = coneOuterGain;
  26145. return this;
  26146. },
  26147. updateMatrixWorld: function (force) {
  26148. Object3D.prototype.updateMatrixWorld.call(this, force);
  26149. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26150. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  26151. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  26152. var panner = this.panner;
  26153. if (panner.positionX) {
  26154. // code path for Chrome and Firefox (see #14393)
  26155. var endTime = this.context.currentTime + this.listener.timeDelta;
  26156. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  26157. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  26158. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  26159. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26160. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26161. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26162. } else {
  26163. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  26164. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  26165. }
  26166. }
  26167. });
  26168. /**
  26169. * @author mrdoob / http://mrdoob.com/
  26170. */
  26171. function AudioAnalyser(audio, fftSize) {
  26172. this.analyser = audio.context.createAnalyser();
  26173. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26174. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26175. audio.getOutput().connect(this.analyser);
  26176. }
  26177. Object.assign(AudioAnalyser.prototype, {
  26178. getFrequencyData: function () {
  26179. this.analyser.getByteFrequencyData(this.data);
  26180. return this.data;
  26181. },
  26182. getAverageFrequency: function () {
  26183. var value = 0,
  26184. data = this.getFrequencyData();
  26185. for (var i = 0; i < data.length; i++) {
  26186. value += data[i];
  26187. }
  26188. return value / data.length;
  26189. }
  26190. });
  26191. /**
  26192. *
  26193. * Buffered scene graph property that allows weighted accumulation.
  26194. *
  26195. *
  26196. * @author Ben Houston / http://clara.io/
  26197. * @author David Sarno / http://lighthaus.us/
  26198. * @author tschw
  26199. */
  26200. function PropertyMixer(binding, typeName, valueSize) {
  26201. this.binding = binding;
  26202. this.valueSize = valueSize;
  26203. var bufferType = Float64Array,
  26204. mixFunction;
  26205. switch (typeName) {
  26206. case 'quaternion':
  26207. mixFunction = this._slerp;
  26208. break;
  26209. case 'string':
  26210. case 'bool':
  26211. bufferType = Array;
  26212. mixFunction = this._select;
  26213. break;
  26214. default:
  26215. mixFunction = this._lerp;
  26216. }
  26217. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  26218. //
  26219. // interpolators can use .buffer as their .result
  26220. // the data then goes to 'incoming'
  26221. //
  26222. // 'accu0' and 'accu1' are used frame-interleaved for
  26223. // the cumulative result and are compared to detect
  26224. // changes
  26225. //
  26226. // 'orig' stores the original state of the property
  26227. this._mixBufferRegion = mixFunction;
  26228. this.cumulativeWeight = 0;
  26229. this.useCount = 0;
  26230. this.referenceCount = 0;
  26231. }
  26232. Object.assign(PropertyMixer.prototype, {
  26233. // accumulate data in the 'incoming' region into 'accu<i>'
  26234. accumulate: function (accuIndex, weight) {
  26235. // note: happily accumulating nothing when weight = 0, the caller knows
  26236. // the weight and shouldn't have made the call in the first place
  26237. var buffer = this.buffer,
  26238. stride = this.valueSize,
  26239. offset = accuIndex * stride + stride,
  26240. currentWeight = this.cumulativeWeight;
  26241. if (currentWeight === 0) {
  26242. // accuN := incoming * weight
  26243. for (var i = 0; i !== stride; ++i) {
  26244. buffer[offset + i] = buffer[i];
  26245. }
  26246. currentWeight = weight;
  26247. } else {
  26248. // accuN := accuN + incoming * weight
  26249. currentWeight += weight;
  26250. var mix = weight / currentWeight;
  26251. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26252. }
  26253. this.cumulativeWeight = currentWeight;
  26254. },
  26255. // apply the state of 'accu<i>' to the binding when accus differ
  26256. apply: function (accuIndex) {
  26257. var stride = this.valueSize,
  26258. buffer = this.buffer,
  26259. offset = accuIndex * stride + stride,
  26260. weight = this.cumulativeWeight,
  26261. binding = this.binding;
  26262. this.cumulativeWeight = 0;
  26263. if (weight < 1) {
  26264. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26265. var originalValueOffset = stride * 3;
  26266. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26267. }
  26268. for (var i = stride, e = stride + stride; i !== e; ++i) {
  26269. if (buffer[i] !== buffer[i + stride]) {
  26270. // value has changed -> update scene graph
  26271. binding.setValue(buffer, offset);
  26272. break;
  26273. }
  26274. }
  26275. },
  26276. // remember the state of the bound property and copy it to both accus
  26277. saveOriginalState: function () {
  26278. var binding = this.binding;
  26279. var buffer = this.buffer,
  26280. stride = this.valueSize,
  26281. originalValueOffset = stride * 3;
  26282. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26283. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  26284. buffer[i] = buffer[originalValueOffset + i % stride];
  26285. }
  26286. this.cumulativeWeight = 0;
  26287. },
  26288. // apply the state previously taken via 'saveOriginalState' to the binding
  26289. restoreOriginalState: function () {
  26290. var originalValueOffset = this.valueSize * 3;
  26291. this.binding.setValue(this.buffer, originalValueOffset);
  26292. },
  26293. // mix functions
  26294. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26295. if (t >= 0.5) {
  26296. for (var i = 0; i !== stride; ++i) {
  26297. buffer[dstOffset + i] = buffer[srcOffset + i];
  26298. }
  26299. }
  26300. },
  26301. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26302. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26303. },
  26304. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26305. var s = 1 - t;
  26306. for (var i = 0; i !== stride; ++i) {
  26307. var j = dstOffset + i;
  26308. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26309. }
  26310. }
  26311. });
  26312. /**
  26313. *
  26314. * A reference to a real property in the scene graph.
  26315. *
  26316. *
  26317. * @author Ben Houston / http://clara.io/
  26318. * @author David Sarno / http://lighthaus.us/
  26319. * @author tschw
  26320. */
  26321. // Characters [].:/ are reserved for track binding syntax.
  26322. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26323. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26324. // only latin characters, and the unicode \p{L} is not yet supported. So
  26325. // instead, we exclude reserved characters and match everything else.
  26326. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26327. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26328. // be matched to parse the rest of the track name.
  26329. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26330. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26331. // characters. Accessor may contain any character except closing bracket.
  26332. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26333. // contain any non-bracket characters.
  26334. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26335. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26336. var _supportedObjectNames = ['material', 'materials', 'bones'];
  26337. function Composite(targetGroup, path, optionalParsedPath) {
  26338. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26339. this._targetGroup = targetGroup;
  26340. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26341. }
  26342. Object.assign(Composite.prototype, {
  26343. getValue: function (array, offset) {
  26344. this.bind(); // bind all binding
  26345. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26346. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26347. if (binding !== undefined) binding.getValue(array, offset);
  26348. },
  26349. setValue: function (array, offset) {
  26350. var bindings = this._bindings;
  26351. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26352. bindings[i].setValue(array, offset);
  26353. }
  26354. },
  26355. bind: function () {
  26356. var bindings = this._bindings;
  26357. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26358. bindings[i].bind();
  26359. }
  26360. },
  26361. unbind: function () {
  26362. var bindings = this._bindings;
  26363. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26364. bindings[i].unbind();
  26365. }
  26366. }
  26367. });
  26368. function PropertyBinding(rootNode, path, parsedPath) {
  26369. this.path = path;
  26370. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26371. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26372. this.rootNode = rootNode;
  26373. }
  26374. Object.assign(PropertyBinding, {
  26375. Composite: Composite,
  26376. create: function (root, path, parsedPath) {
  26377. if (!(root && root.isAnimationObjectGroup)) {
  26378. return new PropertyBinding(root, path, parsedPath);
  26379. } else {
  26380. return new PropertyBinding.Composite(root, path, parsedPath);
  26381. }
  26382. },
  26383. /**
  26384. * Replaces spaces with underscores and removes unsupported characters from
  26385. * node names, to ensure compatibility with parseTrackName().
  26386. *
  26387. * @param {string} name Node name to be sanitized.
  26388. * @return {string}
  26389. */
  26390. sanitizeNodeName: function (name) {
  26391. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26392. },
  26393. parseTrackName: function (trackName) {
  26394. var matches = _trackRe.exec(trackName);
  26395. if (!matches) {
  26396. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26397. }
  26398. var results = {
  26399. // directoryName: matches[ 1 ], // (tschw) currently unused
  26400. nodeName: matches[2],
  26401. objectName: matches[3],
  26402. objectIndex: matches[4],
  26403. propertyName: matches[5],
  26404. // required
  26405. propertyIndex: matches[6]
  26406. };
  26407. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26408. if (lastDot !== undefined && lastDot !== -1) {
  26409. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  26410. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26411. // 'bar' could be the objectName, or part of a nodeName (which can
  26412. // include '.' characters).
  26413. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26414. results.nodeName = results.nodeName.substring(0, lastDot);
  26415. results.objectName = objectName;
  26416. }
  26417. }
  26418. if (results.propertyName === null || results.propertyName.length === 0) {
  26419. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26420. }
  26421. return results;
  26422. },
  26423. findNode: function (root, nodeName) {
  26424. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26425. return root;
  26426. } // search into skeleton bones.
  26427. if (root.skeleton) {
  26428. var bone = root.skeleton.getBoneByName(nodeName);
  26429. if (bone !== undefined) {
  26430. return bone;
  26431. }
  26432. } // search into node subtree.
  26433. if (root.children) {
  26434. var searchNodeSubtree = function (children) {
  26435. for (var i = 0; i < children.length; i++) {
  26436. var childNode = children[i];
  26437. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26438. return childNode;
  26439. }
  26440. var result = searchNodeSubtree(childNode.children);
  26441. if (result) return result;
  26442. }
  26443. return null;
  26444. };
  26445. var subTreeNode = searchNodeSubtree(root.children);
  26446. if (subTreeNode) {
  26447. return subTreeNode;
  26448. }
  26449. }
  26450. return null;
  26451. }
  26452. });
  26453. Object.assign(PropertyBinding.prototype, {
  26454. // prototype, continued
  26455. // these are used to "bind" a nonexistent property
  26456. _getValue_unavailable: function () {},
  26457. _setValue_unavailable: function () {},
  26458. BindingType: {
  26459. Direct: 0,
  26460. EntireArray: 1,
  26461. ArrayElement: 2,
  26462. HasFromToArray: 3
  26463. },
  26464. Versioning: {
  26465. None: 0,
  26466. NeedsUpdate: 1,
  26467. MatrixWorldNeedsUpdate: 2
  26468. },
  26469. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26470. buffer[offset] = this.node[this.propertyName];
  26471. }, function getValue_array(buffer, offset) {
  26472. var source = this.resolvedProperty;
  26473. for (var i = 0, n = source.length; i !== n; ++i) {
  26474. buffer[offset++] = source[i];
  26475. }
  26476. }, function getValue_arrayElement(buffer, offset) {
  26477. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26478. }, function getValue_toArray(buffer, offset) {
  26479. this.resolvedProperty.toArray(buffer, offset);
  26480. }],
  26481. SetterByBindingTypeAndVersioning: [[// Direct
  26482. function setValue_direct(buffer, offset) {
  26483. this.targetObject[this.propertyName] = buffer[offset];
  26484. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26485. this.targetObject[this.propertyName] = buffer[offset];
  26486. this.targetObject.needsUpdate = true;
  26487. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26488. this.targetObject[this.propertyName] = buffer[offset];
  26489. this.targetObject.matrixWorldNeedsUpdate = true;
  26490. }], [// EntireArray
  26491. function setValue_array(buffer, offset) {
  26492. var dest = this.resolvedProperty;
  26493. for (var i = 0, n = dest.length; i !== n; ++i) {
  26494. dest[i] = buffer[offset++];
  26495. }
  26496. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26497. var dest = this.resolvedProperty;
  26498. for (var i = 0, n = dest.length; i !== n; ++i) {
  26499. dest[i] = buffer[offset++];
  26500. }
  26501. this.targetObject.needsUpdate = true;
  26502. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26503. var dest = this.resolvedProperty;
  26504. for (var i = 0, n = dest.length; i !== n; ++i) {
  26505. dest[i] = buffer[offset++];
  26506. }
  26507. this.targetObject.matrixWorldNeedsUpdate = true;
  26508. }], [// ArrayElement
  26509. function setValue_arrayElement(buffer, offset) {
  26510. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26511. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26512. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26513. this.targetObject.needsUpdate = true;
  26514. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26515. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26516. this.targetObject.matrixWorldNeedsUpdate = true;
  26517. }], [// HasToFromArray
  26518. function setValue_fromArray(buffer, offset) {
  26519. this.resolvedProperty.fromArray(buffer, offset);
  26520. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26521. this.resolvedProperty.fromArray(buffer, offset);
  26522. this.targetObject.needsUpdate = true;
  26523. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26524. this.resolvedProperty.fromArray(buffer, offset);
  26525. this.targetObject.matrixWorldNeedsUpdate = true;
  26526. }]],
  26527. getValue: function getValue_unbound(targetArray, offset) {
  26528. this.bind();
  26529. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26530. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26531. // prototype version of these methods with one that represents
  26532. // the bound state. When the property is not found, the methods
  26533. // become no-ops.
  26534. },
  26535. setValue: function getValue_unbound(sourceArray, offset) {
  26536. this.bind();
  26537. this.setValue(sourceArray, offset);
  26538. },
  26539. // create getter / setter pair for a property in the scene graph
  26540. bind: function () {
  26541. var targetObject = this.node,
  26542. parsedPath = this.parsedPath,
  26543. objectName = parsedPath.objectName,
  26544. propertyName = parsedPath.propertyName,
  26545. propertyIndex = parsedPath.propertyIndex;
  26546. if (!targetObject) {
  26547. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26548. this.node = targetObject;
  26549. } // set fail state so we can just 'return' on error
  26550. this.getValue = this._getValue_unavailable;
  26551. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26552. if (!targetObject) {
  26553. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26554. return;
  26555. }
  26556. if (objectName) {
  26557. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26558. switch (objectName) {
  26559. case 'materials':
  26560. if (!targetObject.material) {
  26561. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26562. return;
  26563. }
  26564. if (!targetObject.material.materials) {
  26565. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26566. return;
  26567. }
  26568. targetObject = targetObject.material.materials;
  26569. break;
  26570. case 'bones':
  26571. if (!targetObject.skeleton) {
  26572. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26573. return;
  26574. } // potential future optimization: skip this if propertyIndex is already an integer
  26575. // and convert the integer string to a true integer.
  26576. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26577. for (var i = 0; i < targetObject.length; i++) {
  26578. if (targetObject[i].name === objectIndex) {
  26579. objectIndex = i;
  26580. break;
  26581. }
  26582. }
  26583. break;
  26584. default:
  26585. if (targetObject[objectName] === undefined) {
  26586. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26587. return;
  26588. }
  26589. targetObject = targetObject[objectName];
  26590. }
  26591. if (objectIndex !== undefined) {
  26592. if (targetObject[objectIndex] === undefined) {
  26593. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26594. return;
  26595. }
  26596. targetObject = targetObject[objectIndex];
  26597. }
  26598. } // resolve property
  26599. var nodeProperty = targetObject[propertyName];
  26600. if (nodeProperty === undefined) {
  26601. var nodeName = parsedPath.nodeName;
  26602. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26603. return;
  26604. } // determine versioning scheme
  26605. var versioning = this.Versioning.None;
  26606. this.targetObject = targetObject;
  26607. if (targetObject.needsUpdate !== undefined) {
  26608. // material
  26609. versioning = this.Versioning.NeedsUpdate;
  26610. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26611. // node transform
  26612. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26613. } // determine how the property gets bound
  26614. var bindingType = this.BindingType.Direct;
  26615. if (propertyIndex !== undefined) {
  26616. // access a sub element of the property array (only primitives are supported right now)
  26617. if (propertyName === "morphTargetInfluences") {
  26618. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26619. // support resolving morphTarget names into indices.
  26620. if (!targetObject.geometry) {
  26621. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26622. return;
  26623. }
  26624. if (targetObject.geometry.isBufferGeometry) {
  26625. if (!targetObject.geometry.morphAttributes) {
  26626. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26627. return;
  26628. }
  26629. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  26630. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  26631. propertyIndex = i;
  26632. break;
  26633. }
  26634. }
  26635. } else {
  26636. if (!targetObject.geometry.morphTargets) {
  26637. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  26638. return;
  26639. }
  26640. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  26641. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  26642. propertyIndex = i;
  26643. break;
  26644. }
  26645. }
  26646. }
  26647. }
  26648. bindingType = this.BindingType.ArrayElement;
  26649. this.resolvedProperty = nodeProperty;
  26650. this.propertyIndex = propertyIndex;
  26651. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26652. // must use copy for Object3D.Euler/Quaternion
  26653. bindingType = this.BindingType.HasFromToArray;
  26654. this.resolvedProperty = nodeProperty;
  26655. } else if (Array.isArray(nodeProperty)) {
  26656. bindingType = this.BindingType.EntireArray;
  26657. this.resolvedProperty = nodeProperty;
  26658. } else {
  26659. this.propertyName = propertyName;
  26660. } // select getter / setter
  26661. this.getValue = this.GetterByBindingType[bindingType];
  26662. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26663. },
  26664. unbind: function () {
  26665. this.node = null; // back to the prototype version of getValue / setValue
  26666. // note: avoiding to mutate the shape of 'this' via 'delete'
  26667. this.getValue = this._getValue_unbound;
  26668. this.setValue = this._setValue_unbound;
  26669. }
  26670. }); //!\ DECLARE ALIAS AFTER assign prototype !
  26671. Object.assign(PropertyBinding.prototype, {
  26672. // initial state of these methods that calls 'bind'
  26673. _getValue_unbound: PropertyBinding.prototype.getValue,
  26674. _setValue_unbound: PropertyBinding.prototype.setValue
  26675. });
  26676. /**
  26677. *
  26678. * A group of objects that receives a shared animation state.
  26679. *
  26680. * Usage:
  26681. *
  26682. * - Add objects you would otherwise pass as 'root' to the
  26683. * constructor or the .clipAction method of AnimationMixer.
  26684. *
  26685. * - Instead pass this object as 'root'.
  26686. *
  26687. * - You can also add and remove objects later when the mixer
  26688. * is running.
  26689. *
  26690. * Note:
  26691. *
  26692. * Objects of this class appear as one object to the mixer,
  26693. * so cache control of the individual objects must be done
  26694. * on the group.
  26695. *
  26696. * Limitation:
  26697. *
  26698. * - The animated properties must be compatible among the
  26699. * all objects in the group.
  26700. *
  26701. * - A single property can either be controlled through a
  26702. * target group or directly, but not both.
  26703. *
  26704. * @author tschw
  26705. */
  26706. function AnimationObjectGroup() {
  26707. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  26708. this._objects = Array.prototype.slice.call(arguments);
  26709. this.nCachedObjects_ = 0; // threshold
  26710. // note: read by PropertyBinding.Composite
  26711. var indices = {};
  26712. this._indicesByUUID = indices; // for bookkeeping
  26713. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26714. indices[arguments[i].uuid] = i;
  26715. }
  26716. this._paths = []; // inside: string
  26717. this._parsedPaths = []; // inside: { we don't care, here }
  26718. this._bindings = []; // inside: Array< PropertyBinding >
  26719. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26720. var scope = this;
  26721. this.stats = {
  26722. objects: {
  26723. get total() {
  26724. return scope._objects.length;
  26725. },
  26726. get inUse() {
  26727. return this.total - scope.nCachedObjects_;
  26728. }
  26729. },
  26730. get bindingsPerObject() {
  26731. return scope._bindings.length;
  26732. }
  26733. };
  26734. }
  26735. Object.assign(AnimationObjectGroup.prototype, {
  26736. isAnimationObjectGroup: true,
  26737. add: function () {
  26738. var objects = this._objects,
  26739. nObjects = objects.length,
  26740. nCachedObjects = this.nCachedObjects_,
  26741. indicesByUUID = this._indicesByUUID,
  26742. paths = this._paths,
  26743. parsedPaths = this._parsedPaths,
  26744. bindings = this._bindings,
  26745. nBindings = bindings.length,
  26746. knownObject = undefined;
  26747. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26748. var object = arguments[i],
  26749. uuid = object.uuid,
  26750. index = indicesByUUID[uuid];
  26751. if (index === undefined) {
  26752. // unknown object -> add it to the ACTIVE region
  26753. index = nObjects++;
  26754. indicesByUUID[uuid] = index;
  26755. objects.push(object); // accounting is done, now do the same for all bindings
  26756. for (var j = 0, m = nBindings; j !== m; ++j) {
  26757. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26758. }
  26759. } else if (index < nCachedObjects) {
  26760. knownObject = objects[index]; // move existing object to the ACTIVE region
  26761. var firstActiveIndex = --nCachedObjects,
  26762. lastCachedObject = objects[firstActiveIndex];
  26763. indicesByUUID[lastCachedObject.uuid] = index;
  26764. objects[index] = lastCachedObject;
  26765. indicesByUUID[uuid] = firstActiveIndex;
  26766. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26767. for (var j = 0, m = nBindings; j !== m; ++j) {
  26768. var bindingsForPath = bindings[j],
  26769. lastCached = bindingsForPath[firstActiveIndex],
  26770. binding = bindingsForPath[index];
  26771. bindingsForPath[index] = lastCached;
  26772. if (binding === undefined) {
  26773. // since we do not bother to create new bindings
  26774. // for objects that are cached, the binding may
  26775. // or may not exist
  26776. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26777. }
  26778. bindingsForPath[firstActiveIndex] = binding;
  26779. }
  26780. } else if (objects[index] !== knownObject) {
  26781. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26782. } // else the object is already where we want it to be
  26783. } // for arguments
  26784. this.nCachedObjects_ = nCachedObjects;
  26785. },
  26786. remove: function () {
  26787. var objects = this._objects,
  26788. nCachedObjects = this.nCachedObjects_,
  26789. indicesByUUID = this._indicesByUUID,
  26790. bindings = this._bindings,
  26791. nBindings = bindings.length;
  26792. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26793. var object = arguments[i],
  26794. uuid = object.uuid,
  26795. index = indicesByUUID[uuid];
  26796. if (index !== undefined && index >= nCachedObjects) {
  26797. // move existing object into the CACHED region
  26798. var lastCachedIndex = nCachedObjects++,
  26799. firstActiveObject = objects[lastCachedIndex];
  26800. indicesByUUID[firstActiveObject.uuid] = index;
  26801. objects[index] = firstActiveObject;
  26802. indicesByUUID[uuid] = lastCachedIndex;
  26803. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26804. for (var j = 0, m = nBindings; j !== m; ++j) {
  26805. var bindingsForPath = bindings[j],
  26806. firstActive = bindingsForPath[lastCachedIndex],
  26807. binding = bindingsForPath[index];
  26808. bindingsForPath[index] = firstActive;
  26809. bindingsForPath[lastCachedIndex] = binding;
  26810. }
  26811. }
  26812. } // for arguments
  26813. this.nCachedObjects_ = nCachedObjects;
  26814. },
  26815. // remove & forget
  26816. uncache: function () {
  26817. var objects = this._objects,
  26818. nObjects = objects.length,
  26819. nCachedObjects = this.nCachedObjects_,
  26820. indicesByUUID = this._indicesByUUID,
  26821. bindings = this._bindings,
  26822. nBindings = bindings.length;
  26823. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26824. var object = arguments[i],
  26825. uuid = object.uuid,
  26826. index = indicesByUUID[uuid];
  26827. if (index !== undefined) {
  26828. delete indicesByUUID[uuid];
  26829. if (index < nCachedObjects) {
  26830. // object is cached, shrink the CACHED region
  26831. var firstActiveIndex = --nCachedObjects,
  26832. lastCachedObject = objects[firstActiveIndex],
  26833. lastIndex = --nObjects,
  26834. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26835. indicesByUUID[lastCachedObject.uuid] = index;
  26836. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26837. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26838. objects[firstActiveIndex] = lastObject;
  26839. objects.pop(); // accounting is done, now do the same for all bindings
  26840. for (var j = 0, m = nBindings; j !== m; ++j) {
  26841. var bindingsForPath = bindings[j],
  26842. lastCached = bindingsForPath[firstActiveIndex],
  26843. last = bindingsForPath[lastIndex];
  26844. bindingsForPath[index] = lastCached;
  26845. bindingsForPath[firstActiveIndex] = last;
  26846. bindingsForPath.pop();
  26847. }
  26848. } else {
  26849. // object is active, just swap with the last and pop
  26850. var lastIndex = --nObjects,
  26851. lastObject = objects[lastIndex];
  26852. indicesByUUID[lastObject.uuid] = index;
  26853. objects[index] = lastObject;
  26854. objects.pop(); // accounting is done, now do the same for all bindings
  26855. for (var j = 0, m = nBindings; j !== m; ++j) {
  26856. var bindingsForPath = bindings[j];
  26857. bindingsForPath[index] = bindingsForPath[lastIndex];
  26858. bindingsForPath.pop();
  26859. }
  26860. } // cached or active
  26861. } // if object is known
  26862. } // for arguments
  26863. this.nCachedObjects_ = nCachedObjects;
  26864. },
  26865. // Internal interface used by befriended PropertyBinding.Composite:
  26866. subscribe_: function (path, parsedPath) {
  26867. // returns an array of bindings for the given path that is changed
  26868. // according to the contained objects in the group
  26869. var indicesByPath = this._bindingsIndicesByPath,
  26870. index = indicesByPath[path],
  26871. bindings = this._bindings;
  26872. if (index !== undefined) return bindings[index];
  26873. var paths = this._paths,
  26874. parsedPaths = this._parsedPaths,
  26875. objects = this._objects,
  26876. nObjects = objects.length,
  26877. nCachedObjects = this.nCachedObjects_,
  26878. bindingsForPath = new Array(nObjects);
  26879. index = bindings.length;
  26880. indicesByPath[path] = index;
  26881. paths.push(path);
  26882. parsedPaths.push(parsedPath);
  26883. bindings.push(bindingsForPath);
  26884. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26885. var object = objects[i];
  26886. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26887. }
  26888. return bindingsForPath;
  26889. },
  26890. unsubscribe_: function (path) {
  26891. // tells the group to forget about a property path and no longer
  26892. // update the array previously obtained with 'subscribe_'
  26893. var indicesByPath = this._bindingsIndicesByPath,
  26894. index = indicesByPath[path];
  26895. if (index !== undefined) {
  26896. var paths = this._paths,
  26897. parsedPaths = this._parsedPaths,
  26898. bindings = this._bindings,
  26899. lastBindingsIndex = bindings.length - 1,
  26900. lastBindings = bindings[lastBindingsIndex],
  26901. lastBindingsPath = path[lastBindingsIndex];
  26902. indicesByPath[lastBindingsPath] = index;
  26903. bindings[index] = lastBindings;
  26904. bindings.pop();
  26905. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26906. parsedPaths.pop();
  26907. paths[index] = paths[lastBindingsIndex];
  26908. paths.pop();
  26909. }
  26910. }
  26911. });
  26912. /**
  26913. *
  26914. * Action provided by AnimationMixer for scheduling clip playback on specific
  26915. * objects.
  26916. *
  26917. * @author Ben Houston / http://clara.io/
  26918. * @author David Sarno / http://lighthaus.us/
  26919. * @author tschw
  26920. *
  26921. */
  26922. function AnimationAction(mixer, clip, localRoot) {
  26923. this._mixer = mixer;
  26924. this._clip = clip;
  26925. this._localRoot = localRoot || null;
  26926. var tracks = clip.tracks,
  26927. nTracks = tracks.length,
  26928. interpolants = new Array(nTracks);
  26929. var interpolantSettings = {
  26930. endingStart: ZeroCurvatureEnding,
  26931. endingEnd: ZeroCurvatureEnding
  26932. };
  26933. for (var i = 0; i !== nTracks; ++i) {
  26934. var interpolant = tracks[i].createInterpolant(null);
  26935. interpolants[i] = interpolant;
  26936. interpolant.settings = interpolantSettings;
  26937. }
  26938. this._interpolantSettings = interpolantSettings;
  26939. this._interpolants = interpolants; // bound by the mixer
  26940. // inside: PropertyMixer (managed by the mixer)
  26941. this._propertyBindings = new Array(nTracks);
  26942. this._cacheIndex = null; // for the memory manager
  26943. this._byClipCacheIndex = null; // for the memory manager
  26944. this._timeScaleInterpolant = null;
  26945. this._weightInterpolant = null;
  26946. this.loop = LoopRepeat;
  26947. this._loopCount = -1; // global mixer time when the action is to be started
  26948. // it's set back to 'null' upon start of the action
  26949. this._startTime = null; // scaled local time of the action
  26950. // gets clamped or wrapped to 0..clip.duration according to loop
  26951. this.time = 0;
  26952. this.timeScale = 1;
  26953. this._effectiveTimeScale = 1;
  26954. this.weight = 1;
  26955. this._effectiveWeight = 1;
  26956. this.repetitions = Infinity; // no. of repetitions when looping
  26957. this.paused = false; // true -> zero effective time scale
  26958. this.enabled = true; // false -> zero effective weight
  26959. this.clampWhenFinished = false; // keep feeding the last frame?
  26960. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26961. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26962. }
  26963. Object.assign(AnimationAction.prototype, {
  26964. // State & Scheduling
  26965. play: function () {
  26966. this._mixer._activateAction(this);
  26967. return this;
  26968. },
  26969. stop: function () {
  26970. this._mixer._deactivateAction(this);
  26971. return this.reset();
  26972. },
  26973. reset: function () {
  26974. this.paused = false;
  26975. this.enabled = true;
  26976. this.time = 0; // restart clip
  26977. this._loopCount = -1; // forget previous loops
  26978. this._startTime = null; // forget scheduling
  26979. return this.stopFading().stopWarping();
  26980. },
  26981. isRunning: function () {
  26982. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26983. },
  26984. // return true when play has been called
  26985. isScheduled: function () {
  26986. return this._mixer._isActiveAction(this);
  26987. },
  26988. startAt: function (time) {
  26989. this._startTime = time;
  26990. return this;
  26991. },
  26992. setLoop: function (mode, repetitions) {
  26993. this.loop = mode;
  26994. this.repetitions = repetitions;
  26995. return this;
  26996. },
  26997. // Weight
  26998. // set the weight stopping any scheduled fading
  26999. // although .enabled = false yields an effective weight of zero, this
  27000. // method does *not* change .enabled, because it would be confusing
  27001. setEffectiveWeight: function (weight) {
  27002. this.weight = weight; // note: same logic as when updated at runtime
  27003. this._effectiveWeight = this.enabled ? weight : 0;
  27004. return this.stopFading();
  27005. },
  27006. // return the weight considering fading and .enabled
  27007. getEffectiveWeight: function () {
  27008. return this._effectiveWeight;
  27009. },
  27010. fadeIn: function (duration) {
  27011. return this._scheduleFading(duration, 0, 1);
  27012. },
  27013. fadeOut: function (duration) {
  27014. return this._scheduleFading(duration, 1, 0);
  27015. },
  27016. crossFadeFrom: function (fadeOutAction, duration, warp) {
  27017. fadeOutAction.fadeOut(duration);
  27018. this.fadeIn(duration);
  27019. if (warp) {
  27020. var fadeInDuration = this._clip.duration,
  27021. fadeOutDuration = fadeOutAction._clip.duration,
  27022. startEndRatio = fadeOutDuration / fadeInDuration,
  27023. endStartRatio = fadeInDuration / fadeOutDuration;
  27024. fadeOutAction.warp(1.0, startEndRatio, duration);
  27025. this.warp(endStartRatio, 1.0, duration);
  27026. }
  27027. return this;
  27028. },
  27029. crossFadeTo: function (fadeInAction, duration, warp) {
  27030. return fadeInAction.crossFadeFrom(this, duration, warp);
  27031. },
  27032. stopFading: function () {
  27033. var weightInterpolant = this._weightInterpolant;
  27034. if (weightInterpolant !== null) {
  27035. this._weightInterpolant = null;
  27036. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27037. }
  27038. return this;
  27039. },
  27040. // Time Scale Control
  27041. // set the time scale stopping any scheduled warping
  27042. // although .paused = true yields an effective time scale of zero, this
  27043. // method does *not* change .paused, because it would be confusing
  27044. setEffectiveTimeScale: function (timeScale) {
  27045. this.timeScale = timeScale;
  27046. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27047. return this.stopWarping();
  27048. },
  27049. // return the time scale considering warping and .paused
  27050. getEffectiveTimeScale: function () {
  27051. return this._effectiveTimeScale;
  27052. },
  27053. setDuration: function (duration) {
  27054. this.timeScale = this._clip.duration / duration;
  27055. return this.stopWarping();
  27056. },
  27057. syncWith: function (action) {
  27058. this.time = action.time;
  27059. this.timeScale = action.timeScale;
  27060. return this.stopWarping();
  27061. },
  27062. halt: function (duration) {
  27063. return this.warp(this._effectiveTimeScale, 0, duration);
  27064. },
  27065. warp: function (startTimeScale, endTimeScale, duration) {
  27066. var mixer = this._mixer,
  27067. now = mixer.time,
  27068. interpolant = this._timeScaleInterpolant,
  27069. timeScale = this.timeScale;
  27070. if (interpolant === null) {
  27071. interpolant = mixer._lendControlInterpolant();
  27072. this._timeScaleInterpolant = interpolant;
  27073. }
  27074. var times = interpolant.parameterPositions,
  27075. values = interpolant.sampleValues;
  27076. times[0] = now;
  27077. times[1] = now + duration;
  27078. values[0] = startTimeScale / timeScale;
  27079. values[1] = endTimeScale / timeScale;
  27080. return this;
  27081. },
  27082. stopWarping: function () {
  27083. var timeScaleInterpolant = this._timeScaleInterpolant;
  27084. if (timeScaleInterpolant !== null) {
  27085. this._timeScaleInterpolant = null;
  27086. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27087. }
  27088. return this;
  27089. },
  27090. // Object Accessors
  27091. getMixer: function () {
  27092. return this._mixer;
  27093. },
  27094. getClip: function () {
  27095. return this._clip;
  27096. },
  27097. getRoot: function () {
  27098. return this._localRoot || this._mixer._root;
  27099. },
  27100. // Interna
  27101. _update: function (time, deltaTime, timeDirection, accuIndex) {
  27102. // called by the mixer
  27103. if (!this.enabled) {
  27104. // call ._updateWeight() to update ._effectiveWeight
  27105. this._updateWeight(time);
  27106. return;
  27107. }
  27108. var startTime = this._startTime;
  27109. if (startTime !== null) {
  27110. // check for scheduled start of action
  27111. var timeRunning = (time - startTime) * timeDirection;
  27112. if (timeRunning < 0 || timeDirection === 0) {
  27113. return; // yet to come / don't decide when delta = 0
  27114. } // start
  27115. this._startTime = null; // unschedule
  27116. deltaTime = timeDirection * timeRunning;
  27117. } // apply time scale and advance time
  27118. deltaTime *= this._updateTimeScale(time);
  27119. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  27120. // an effective weight of 0
  27121. var weight = this._updateWeight(time);
  27122. if (weight > 0) {
  27123. var interpolants = this._interpolants;
  27124. var propertyMixers = this._propertyBindings;
  27125. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  27126. interpolants[j].evaluate(clipTime);
  27127. propertyMixers[j].accumulate(accuIndex, weight);
  27128. }
  27129. }
  27130. },
  27131. _updateWeight: function (time) {
  27132. var weight = 0;
  27133. if (this.enabled) {
  27134. weight = this.weight;
  27135. var interpolant = this._weightInterpolant;
  27136. if (interpolant !== null) {
  27137. var interpolantValue = interpolant.evaluate(time)[0];
  27138. weight *= interpolantValue;
  27139. if (time > interpolant.parameterPositions[1]) {
  27140. this.stopFading();
  27141. if (interpolantValue === 0) {
  27142. // faded out, disable
  27143. this.enabled = false;
  27144. }
  27145. }
  27146. }
  27147. }
  27148. this._effectiveWeight = weight;
  27149. return weight;
  27150. },
  27151. _updateTimeScale: function (time) {
  27152. var timeScale = 0;
  27153. if (!this.paused) {
  27154. timeScale = this.timeScale;
  27155. var interpolant = this._timeScaleInterpolant;
  27156. if (interpolant !== null) {
  27157. var interpolantValue = interpolant.evaluate(time)[0];
  27158. timeScale *= interpolantValue;
  27159. if (time > interpolant.parameterPositions[1]) {
  27160. this.stopWarping();
  27161. if (timeScale === 0) {
  27162. // motion has halted, pause
  27163. this.paused = true;
  27164. } else {
  27165. // warp done - apply final time scale
  27166. this.timeScale = timeScale;
  27167. }
  27168. }
  27169. }
  27170. }
  27171. this._effectiveTimeScale = timeScale;
  27172. return timeScale;
  27173. },
  27174. _updateTime: function (deltaTime) {
  27175. var time = this.time + deltaTime;
  27176. var duration = this._clip.duration;
  27177. var loop = this.loop;
  27178. var loopCount = this._loopCount;
  27179. var pingPong = loop === LoopPingPong;
  27180. if (deltaTime === 0) {
  27181. if (loopCount === -1) return time;
  27182. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27183. }
  27184. if (loop === LoopOnce) {
  27185. if (loopCount === -1) {
  27186. // just started
  27187. this._loopCount = 0;
  27188. this._setEndings(true, true, false);
  27189. }
  27190. handle_stop: {
  27191. if (time >= duration) {
  27192. time = duration;
  27193. } else if (time < 0) {
  27194. time = 0;
  27195. } else {
  27196. this.time = time;
  27197. break handle_stop;
  27198. }
  27199. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27200. this.time = time;
  27201. this._mixer.dispatchEvent({
  27202. type: 'finished',
  27203. action: this,
  27204. direction: deltaTime < 0 ? -1 : 1
  27205. });
  27206. }
  27207. } else {
  27208. // repetitive Repeat or PingPong
  27209. if (loopCount === -1) {
  27210. // just started
  27211. if (deltaTime >= 0) {
  27212. loopCount = 0;
  27213. this._setEndings(true, this.repetitions === 0, pingPong);
  27214. } else {
  27215. // when looping in reverse direction, the initial
  27216. // transition through zero counts as a repetition,
  27217. // so leave loopCount at -1
  27218. this._setEndings(this.repetitions === 0, true, pingPong);
  27219. }
  27220. }
  27221. if (time >= duration || time < 0) {
  27222. // wrap around
  27223. var loopDelta = Math.floor(time / duration); // signed
  27224. time -= duration * loopDelta;
  27225. loopCount += Math.abs(loopDelta);
  27226. var pending = this.repetitions - loopCount;
  27227. if (pending <= 0) {
  27228. // have to stop (switch state, clamp time, fire event)
  27229. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27230. time = deltaTime > 0 ? duration : 0;
  27231. this.time = time;
  27232. this._mixer.dispatchEvent({
  27233. type: 'finished',
  27234. action: this,
  27235. direction: deltaTime > 0 ? 1 : -1
  27236. });
  27237. } else {
  27238. // keep running
  27239. if (pending === 1) {
  27240. // entering the last round
  27241. var atStart = deltaTime < 0;
  27242. this._setEndings(atStart, !atStart, pingPong);
  27243. } else {
  27244. this._setEndings(false, false, pingPong);
  27245. }
  27246. this._loopCount = loopCount;
  27247. this.time = time;
  27248. this._mixer.dispatchEvent({
  27249. type: 'loop',
  27250. action: this,
  27251. loopDelta: loopDelta
  27252. });
  27253. }
  27254. } else {
  27255. this.time = time;
  27256. }
  27257. if (pingPong && (loopCount & 1) === 1) {
  27258. // invert time for the "pong round"
  27259. return duration - time;
  27260. }
  27261. }
  27262. return time;
  27263. },
  27264. _setEndings: function (atStart, atEnd, pingPong) {
  27265. var settings = this._interpolantSettings;
  27266. if (pingPong) {
  27267. settings.endingStart = ZeroSlopeEnding;
  27268. settings.endingEnd = ZeroSlopeEnding;
  27269. } else {
  27270. // assuming for LoopOnce atStart == atEnd == true
  27271. if (atStart) {
  27272. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27273. } else {
  27274. settings.endingStart = WrapAroundEnding;
  27275. }
  27276. if (atEnd) {
  27277. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27278. } else {
  27279. settings.endingEnd = WrapAroundEnding;
  27280. }
  27281. }
  27282. },
  27283. _scheduleFading: function (duration, weightNow, weightThen) {
  27284. var mixer = this._mixer,
  27285. now = mixer.time,
  27286. interpolant = this._weightInterpolant;
  27287. if (interpolant === null) {
  27288. interpolant = mixer._lendControlInterpolant();
  27289. this._weightInterpolant = interpolant;
  27290. }
  27291. var times = interpolant.parameterPositions,
  27292. values = interpolant.sampleValues;
  27293. times[0] = now;
  27294. values[0] = weightNow;
  27295. times[1] = now + duration;
  27296. values[1] = weightThen;
  27297. return this;
  27298. }
  27299. });
  27300. /**
  27301. *
  27302. * Player for AnimationClips.
  27303. *
  27304. *
  27305. * @author Ben Houston / http://clara.io/
  27306. * @author David Sarno / http://lighthaus.us/
  27307. * @author tschw
  27308. */
  27309. function AnimationMixer(root) {
  27310. this._root = root;
  27311. this._initMemoryManager();
  27312. this._accuIndex = 0;
  27313. this.time = 0;
  27314. this.timeScale = 1.0;
  27315. }
  27316. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27317. constructor: AnimationMixer,
  27318. _bindAction: function (action, prototypeAction) {
  27319. var root = action._localRoot || this._root,
  27320. tracks = action._clip.tracks,
  27321. nTracks = tracks.length,
  27322. bindings = action._propertyBindings,
  27323. interpolants = action._interpolants,
  27324. rootUuid = root.uuid,
  27325. bindingsByRoot = this._bindingsByRootAndName,
  27326. bindingsByName = bindingsByRoot[rootUuid];
  27327. if (bindingsByName === undefined) {
  27328. bindingsByName = {};
  27329. bindingsByRoot[rootUuid] = bindingsByName;
  27330. }
  27331. for (var i = 0; i !== nTracks; ++i) {
  27332. var track = tracks[i],
  27333. trackName = track.name,
  27334. binding = bindingsByName[trackName];
  27335. if (binding !== undefined) {
  27336. bindings[i] = binding;
  27337. } else {
  27338. binding = bindings[i];
  27339. if (binding !== undefined) {
  27340. // existing binding, make sure the cache knows
  27341. if (binding._cacheIndex === null) {
  27342. ++binding.referenceCount;
  27343. this._addInactiveBinding(binding, rootUuid, trackName);
  27344. }
  27345. continue;
  27346. }
  27347. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27348. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27349. ++binding.referenceCount;
  27350. this._addInactiveBinding(binding, rootUuid, trackName);
  27351. bindings[i] = binding;
  27352. }
  27353. interpolants[i].resultBuffer = binding.buffer;
  27354. }
  27355. },
  27356. _activateAction: function (action) {
  27357. if (!this._isActiveAction(action)) {
  27358. if (action._cacheIndex === null) {
  27359. // this action has been forgotten by the cache, but the user
  27360. // appears to be still using it -> rebind
  27361. var rootUuid = (action._localRoot || this._root).uuid,
  27362. clipUuid = action._clip.uuid,
  27363. actionsForClip = this._actionsByClip[clipUuid];
  27364. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27365. this._addInactiveAction(action, clipUuid, rootUuid);
  27366. }
  27367. var bindings = action._propertyBindings; // increment reference counts / sort out state
  27368. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27369. var binding = bindings[i];
  27370. if (binding.useCount++ === 0) {
  27371. this._lendBinding(binding);
  27372. binding.saveOriginalState();
  27373. }
  27374. }
  27375. this._lendAction(action);
  27376. }
  27377. },
  27378. _deactivateAction: function (action) {
  27379. if (this._isActiveAction(action)) {
  27380. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  27381. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27382. var binding = bindings[i];
  27383. if (--binding.useCount === 0) {
  27384. binding.restoreOriginalState();
  27385. this._takeBackBinding(binding);
  27386. }
  27387. }
  27388. this._takeBackAction(action);
  27389. }
  27390. },
  27391. // Memory manager
  27392. _initMemoryManager: function () {
  27393. this._actions = []; // 'nActiveActions' followed by inactive ones
  27394. this._nActiveActions = 0;
  27395. this._actionsByClip = {}; // inside:
  27396. // {
  27397. // knownActions: Array< AnimationAction > - used as prototypes
  27398. // actionByRoot: AnimationAction - lookup
  27399. // }
  27400. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27401. this._nActiveBindings = 0;
  27402. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27403. this._controlInterpolants = []; // same game as above
  27404. this._nActiveControlInterpolants = 0;
  27405. var scope = this;
  27406. this.stats = {
  27407. actions: {
  27408. get total() {
  27409. return scope._actions.length;
  27410. },
  27411. get inUse() {
  27412. return scope._nActiveActions;
  27413. }
  27414. },
  27415. bindings: {
  27416. get total() {
  27417. return scope._bindings.length;
  27418. },
  27419. get inUse() {
  27420. return scope._nActiveBindings;
  27421. }
  27422. },
  27423. controlInterpolants: {
  27424. get total() {
  27425. return scope._controlInterpolants.length;
  27426. },
  27427. get inUse() {
  27428. return scope._nActiveControlInterpolants;
  27429. }
  27430. }
  27431. };
  27432. },
  27433. // Memory management for AnimationAction objects
  27434. _isActiveAction: function (action) {
  27435. var index = action._cacheIndex;
  27436. return index !== null && index < this._nActiveActions;
  27437. },
  27438. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27439. var actions = this._actions,
  27440. actionsByClip = this._actionsByClip,
  27441. actionsForClip = actionsByClip[clipUuid];
  27442. if (actionsForClip === undefined) {
  27443. actionsForClip = {
  27444. knownActions: [action],
  27445. actionByRoot: {}
  27446. };
  27447. action._byClipCacheIndex = 0;
  27448. actionsByClip[clipUuid] = actionsForClip;
  27449. } else {
  27450. var knownActions = actionsForClip.knownActions;
  27451. action._byClipCacheIndex = knownActions.length;
  27452. knownActions.push(action);
  27453. }
  27454. action._cacheIndex = actions.length;
  27455. actions.push(action);
  27456. actionsForClip.actionByRoot[rootUuid] = action;
  27457. },
  27458. _removeInactiveAction: function (action) {
  27459. var actions = this._actions,
  27460. lastInactiveAction = actions[actions.length - 1],
  27461. cacheIndex = action._cacheIndex;
  27462. lastInactiveAction._cacheIndex = cacheIndex;
  27463. actions[cacheIndex] = lastInactiveAction;
  27464. actions.pop();
  27465. action._cacheIndex = null;
  27466. var clipUuid = action._clip.uuid,
  27467. actionsByClip = this._actionsByClip,
  27468. actionsForClip = actionsByClip[clipUuid],
  27469. knownActionsForClip = actionsForClip.knownActions,
  27470. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27471. byClipCacheIndex = action._byClipCacheIndex;
  27472. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27473. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27474. knownActionsForClip.pop();
  27475. action._byClipCacheIndex = null;
  27476. var actionByRoot = actionsForClip.actionByRoot,
  27477. rootUuid = (action._localRoot || this._root).uuid;
  27478. delete actionByRoot[rootUuid];
  27479. if (knownActionsForClip.length === 0) {
  27480. delete actionsByClip[clipUuid];
  27481. }
  27482. this._removeInactiveBindingsForAction(action);
  27483. },
  27484. _removeInactiveBindingsForAction: function (action) {
  27485. var bindings = action._propertyBindings;
  27486. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27487. var binding = bindings[i];
  27488. if (--binding.referenceCount === 0) {
  27489. this._removeInactiveBinding(binding);
  27490. }
  27491. }
  27492. },
  27493. _lendAction: function (action) {
  27494. // [ active actions | inactive actions ]
  27495. // [ active actions >| inactive actions ]
  27496. // s a
  27497. // <-swap->
  27498. // a s
  27499. var actions = this._actions,
  27500. prevIndex = action._cacheIndex,
  27501. lastActiveIndex = this._nActiveActions++,
  27502. firstInactiveAction = actions[lastActiveIndex];
  27503. action._cacheIndex = lastActiveIndex;
  27504. actions[lastActiveIndex] = action;
  27505. firstInactiveAction._cacheIndex = prevIndex;
  27506. actions[prevIndex] = firstInactiveAction;
  27507. },
  27508. _takeBackAction: function (action) {
  27509. // [ active actions | inactive actions ]
  27510. // [ active actions |< inactive actions ]
  27511. // a s
  27512. // <-swap->
  27513. // s a
  27514. var actions = this._actions,
  27515. prevIndex = action._cacheIndex,
  27516. firstInactiveIndex = --this._nActiveActions,
  27517. lastActiveAction = actions[firstInactiveIndex];
  27518. action._cacheIndex = firstInactiveIndex;
  27519. actions[firstInactiveIndex] = action;
  27520. lastActiveAction._cacheIndex = prevIndex;
  27521. actions[prevIndex] = lastActiveAction;
  27522. },
  27523. // Memory management for PropertyMixer objects
  27524. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27525. var bindingsByRoot = this._bindingsByRootAndName,
  27526. bindingByName = bindingsByRoot[rootUuid],
  27527. bindings = this._bindings;
  27528. if (bindingByName === undefined) {
  27529. bindingByName = {};
  27530. bindingsByRoot[rootUuid] = bindingByName;
  27531. }
  27532. bindingByName[trackName] = binding;
  27533. binding._cacheIndex = bindings.length;
  27534. bindings.push(binding);
  27535. },
  27536. _removeInactiveBinding: function (binding) {
  27537. var bindings = this._bindings,
  27538. propBinding = binding.binding,
  27539. rootUuid = propBinding.rootNode.uuid,
  27540. trackName = propBinding.path,
  27541. bindingsByRoot = this._bindingsByRootAndName,
  27542. bindingByName = bindingsByRoot[rootUuid],
  27543. lastInactiveBinding = bindings[bindings.length - 1],
  27544. cacheIndex = binding._cacheIndex;
  27545. lastInactiveBinding._cacheIndex = cacheIndex;
  27546. bindings[cacheIndex] = lastInactiveBinding;
  27547. bindings.pop();
  27548. delete bindingByName[trackName];
  27549. if (Object.keys(bindingByName).length === 0) {
  27550. delete bindingsByRoot[rootUuid];
  27551. }
  27552. },
  27553. _lendBinding: function (binding) {
  27554. var bindings = this._bindings,
  27555. prevIndex = binding._cacheIndex,
  27556. lastActiveIndex = this._nActiveBindings++,
  27557. firstInactiveBinding = bindings[lastActiveIndex];
  27558. binding._cacheIndex = lastActiveIndex;
  27559. bindings[lastActiveIndex] = binding;
  27560. firstInactiveBinding._cacheIndex = prevIndex;
  27561. bindings[prevIndex] = firstInactiveBinding;
  27562. },
  27563. _takeBackBinding: function (binding) {
  27564. var bindings = this._bindings,
  27565. prevIndex = binding._cacheIndex,
  27566. firstInactiveIndex = --this._nActiveBindings,
  27567. lastActiveBinding = bindings[firstInactiveIndex];
  27568. binding._cacheIndex = firstInactiveIndex;
  27569. bindings[firstInactiveIndex] = binding;
  27570. lastActiveBinding._cacheIndex = prevIndex;
  27571. bindings[prevIndex] = lastActiveBinding;
  27572. },
  27573. // Memory management of Interpolants for weight and time scale
  27574. _lendControlInterpolant: function () {
  27575. var interpolants = this._controlInterpolants,
  27576. lastActiveIndex = this._nActiveControlInterpolants++,
  27577. interpolant = interpolants[lastActiveIndex];
  27578. if (interpolant === undefined) {
  27579. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27580. interpolant.__cacheIndex = lastActiveIndex;
  27581. interpolants[lastActiveIndex] = interpolant;
  27582. }
  27583. return interpolant;
  27584. },
  27585. _takeBackControlInterpolant: function (interpolant) {
  27586. var interpolants = this._controlInterpolants,
  27587. prevIndex = interpolant.__cacheIndex,
  27588. firstInactiveIndex = --this._nActiveControlInterpolants,
  27589. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27590. interpolant.__cacheIndex = firstInactiveIndex;
  27591. interpolants[firstInactiveIndex] = interpolant;
  27592. lastActiveInterpolant.__cacheIndex = prevIndex;
  27593. interpolants[prevIndex] = lastActiveInterpolant;
  27594. },
  27595. _controlInterpolantsResultBuffer: new Float32Array(1),
  27596. // return an action for a clip optionally using a custom root target
  27597. // object (this method allocates a lot of dynamic memory in case a
  27598. // previously unknown clip/root combination is specified)
  27599. clipAction: function (clip, optionalRoot) {
  27600. var root = optionalRoot || this._root,
  27601. rootUuid = root.uuid,
  27602. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27603. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27604. actionsForClip = this._actionsByClip[clipUuid],
  27605. prototypeAction = null;
  27606. if (actionsForClip !== undefined) {
  27607. var existingAction = actionsForClip.actionByRoot[rootUuid];
  27608. if (existingAction !== undefined) {
  27609. return existingAction;
  27610. } // we know the clip, so we don't have to parse all
  27611. // the bindings again but can just copy
  27612. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27613. if (clipObject === null) clipObject = prototypeAction._clip;
  27614. } // clip must be known when specified via string
  27615. if (clipObject === null) return null; // allocate all resources required to run it
  27616. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  27617. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27618. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27619. return newAction;
  27620. },
  27621. // get an existing action
  27622. existingAction: function (clip, optionalRoot) {
  27623. var root = optionalRoot || this._root,
  27624. rootUuid = root.uuid,
  27625. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27626. clipUuid = clipObject ? clipObject.uuid : clip,
  27627. actionsForClip = this._actionsByClip[clipUuid];
  27628. if (actionsForClip !== undefined) {
  27629. return actionsForClip.actionByRoot[rootUuid] || null;
  27630. }
  27631. return null;
  27632. },
  27633. // deactivates all previously scheduled actions
  27634. stopAllAction: function () {
  27635. var actions = this._actions,
  27636. nActions = this._nActiveActions,
  27637. bindings = this._bindings,
  27638. nBindings = this._nActiveBindings;
  27639. this._nActiveActions = 0;
  27640. this._nActiveBindings = 0;
  27641. for (var i = 0; i !== nActions; ++i) {
  27642. actions[i].reset();
  27643. }
  27644. for (var i = 0; i !== nBindings; ++i) {
  27645. bindings[i].useCount = 0;
  27646. }
  27647. return this;
  27648. },
  27649. // advance the time and update apply the animation
  27650. update: function (deltaTime) {
  27651. deltaTime *= this.timeScale;
  27652. var actions = this._actions,
  27653. nActions = this._nActiveActions,
  27654. time = this.time += deltaTime,
  27655. timeDirection = Math.sign(deltaTime),
  27656. accuIndex = this._accuIndex ^= 1; // run active actions
  27657. for (var i = 0; i !== nActions; ++i) {
  27658. var action = actions[i];
  27659. action._update(time, deltaTime, timeDirection, accuIndex);
  27660. } // update scene graph
  27661. var bindings = this._bindings,
  27662. nBindings = this._nActiveBindings;
  27663. for (var i = 0; i !== nBindings; ++i) {
  27664. bindings[i].apply(accuIndex);
  27665. }
  27666. return this;
  27667. },
  27668. // Allows you to seek to a specific time in an animation.
  27669. setTime: function (timeInSeconds) {
  27670. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27671. for (var i = 0; i < this._actions.length; i++) {
  27672. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27673. }
  27674. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27675. },
  27676. // return this mixer's root target object
  27677. getRoot: function () {
  27678. return this._root;
  27679. },
  27680. // free all resources specific to a particular clip
  27681. uncacheClip: function (clip) {
  27682. var actions = this._actions,
  27683. clipUuid = clip.uuid,
  27684. actionsByClip = this._actionsByClip,
  27685. actionsForClip = actionsByClip[clipUuid];
  27686. if (actionsForClip !== undefined) {
  27687. // note: just calling _removeInactiveAction would mess up the
  27688. // iteration state and also require updating the state we can
  27689. // just throw away
  27690. var actionsToRemove = actionsForClip.knownActions;
  27691. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27692. var action = actionsToRemove[i];
  27693. this._deactivateAction(action);
  27694. var cacheIndex = action._cacheIndex,
  27695. lastInactiveAction = actions[actions.length - 1];
  27696. action._cacheIndex = null;
  27697. action._byClipCacheIndex = null;
  27698. lastInactiveAction._cacheIndex = cacheIndex;
  27699. actions[cacheIndex] = lastInactiveAction;
  27700. actions.pop();
  27701. this._removeInactiveBindingsForAction(action);
  27702. }
  27703. delete actionsByClip[clipUuid];
  27704. }
  27705. },
  27706. // free all resources specific to a particular root target object
  27707. uncacheRoot: function (root) {
  27708. var rootUuid = root.uuid,
  27709. actionsByClip = this._actionsByClip;
  27710. for (var clipUuid in actionsByClip) {
  27711. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27712. action = actionByRoot[rootUuid];
  27713. if (action !== undefined) {
  27714. this._deactivateAction(action);
  27715. this._removeInactiveAction(action);
  27716. }
  27717. }
  27718. var bindingsByRoot = this._bindingsByRootAndName,
  27719. bindingByName = bindingsByRoot[rootUuid];
  27720. if (bindingByName !== undefined) {
  27721. for (var trackName in bindingByName) {
  27722. var binding = bindingByName[trackName];
  27723. binding.restoreOriginalState();
  27724. this._removeInactiveBinding(binding);
  27725. }
  27726. }
  27727. },
  27728. // remove a targeted clip from the cache
  27729. uncacheAction: function (clip, optionalRoot) {
  27730. var action = this.existingAction(clip, optionalRoot);
  27731. if (action !== null) {
  27732. this._deactivateAction(action);
  27733. this._removeInactiveAction(action);
  27734. }
  27735. }
  27736. });
  27737. /**
  27738. * @author mrdoob / http://mrdoob.com/
  27739. */
  27740. function Uniform(value) {
  27741. if (typeof value === 'string') {
  27742. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27743. value = arguments[1];
  27744. }
  27745. this.value = value;
  27746. }
  27747. Uniform.prototype.clone = function () {
  27748. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27749. };
  27750. /**
  27751. * @author benaadams / https://twitter.com/ben_a_adams
  27752. */
  27753. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27754. InterleavedBuffer.call(this, array, stride);
  27755. this.meshPerAttribute = meshPerAttribute || 1;
  27756. }
  27757. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27758. constructor: InstancedInterleavedBuffer,
  27759. isInstancedInterleavedBuffer: true,
  27760. copy: function (source) {
  27761. InterleavedBuffer.prototype.copy.call(this, source);
  27762. this.meshPerAttribute = source.meshPerAttribute;
  27763. return this;
  27764. }
  27765. });
  27766. /**
  27767. * @author mrdoob / http://mrdoob.com/
  27768. * @author bhouston / http://clara.io/
  27769. * @author stephomi / http://stephaneginier.com/
  27770. */
  27771. function Raycaster(origin, direction, near, far) {
  27772. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27773. this.near = near || 0;
  27774. this.far = far || Infinity;
  27775. this.camera = null;
  27776. this.params = {
  27777. Mesh: {},
  27778. Line: {},
  27779. LOD: {},
  27780. Points: {
  27781. threshold: 1
  27782. },
  27783. Sprite: {}
  27784. };
  27785. Object.defineProperties(this.params, {
  27786. PointCloud: {
  27787. get: function () {
  27788. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27789. return this.Points;
  27790. }
  27791. }
  27792. });
  27793. }
  27794. function ascSort(a, b) {
  27795. return a.distance - b.distance;
  27796. }
  27797. function intersectObject(object, raycaster, intersects, recursive) {
  27798. if (object.visible === false) return;
  27799. object.raycast(raycaster, intersects);
  27800. if (recursive === true) {
  27801. var children = object.children;
  27802. for (var i = 0, l = children.length; i < l; i++) {
  27803. intersectObject(children[i], raycaster, intersects, true);
  27804. }
  27805. }
  27806. }
  27807. Object.assign(Raycaster.prototype, {
  27808. linePrecision: 1,
  27809. set: function (origin, direction) {
  27810. // direction is assumed to be normalized (for accurate distance calculations)
  27811. this.ray.set(origin, direction);
  27812. },
  27813. setFromCamera: function (coords, camera) {
  27814. if (camera && camera.isPerspectiveCamera) {
  27815. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27816. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27817. this.camera = camera;
  27818. } else if (camera && camera.isOrthographicCamera) {
  27819. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27820. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27821. this.camera = camera;
  27822. } else {
  27823. console.error('THREE.Raycaster: Unsupported camera type.');
  27824. }
  27825. },
  27826. intersectObject: function (object, recursive, optionalTarget) {
  27827. var intersects = optionalTarget || [];
  27828. intersectObject(object, this, intersects, recursive);
  27829. intersects.sort(ascSort);
  27830. return intersects;
  27831. },
  27832. intersectObjects: function (objects, recursive, optionalTarget) {
  27833. var intersects = optionalTarget || [];
  27834. if (Array.isArray(objects) === false) {
  27835. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27836. return intersects;
  27837. }
  27838. for (var i = 0, l = objects.length; i < l; i++) {
  27839. intersectObject(objects[i], this, intersects, recursive);
  27840. }
  27841. intersects.sort(ascSort);
  27842. return intersects;
  27843. }
  27844. });
  27845. /**
  27846. * @author bhouston / http://clara.io
  27847. * @author WestLangley / http://github.com/WestLangley
  27848. *
  27849. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27850. *
  27851. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27852. * The azimuthal angle (theta) is measured from the positive z-axiz.
  27853. */
  27854. function Spherical(radius, phi, theta) {
  27855. this.radius = radius !== undefined ? radius : 1.0;
  27856. this.phi = phi !== undefined ? phi : 0; // polar angle
  27857. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27858. return this;
  27859. }
  27860. Object.assign(Spherical.prototype, {
  27861. set: function (radius, phi, theta) {
  27862. this.radius = radius;
  27863. this.phi = phi;
  27864. this.theta = theta;
  27865. return this;
  27866. },
  27867. clone: function () {
  27868. return new this.constructor().copy(this);
  27869. },
  27870. copy: function (other) {
  27871. this.radius = other.radius;
  27872. this.phi = other.phi;
  27873. this.theta = other.theta;
  27874. return this;
  27875. },
  27876. // restrict phi to be betwee EPS and PI-EPS
  27877. makeSafe: function () {
  27878. var EPS = 0.000001;
  27879. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27880. return this;
  27881. },
  27882. setFromVector3: function (v) {
  27883. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27884. },
  27885. setFromCartesianCoords: function (x, y, z) {
  27886. this.radius = Math.sqrt(x * x + y * y + z * z);
  27887. if (this.radius === 0) {
  27888. this.theta = 0;
  27889. this.phi = 0;
  27890. } else {
  27891. this.theta = Math.atan2(x, z);
  27892. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  27893. }
  27894. return this;
  27895. }
  27896. });
  27897. /**
  27898. * @author Mugen87 / https://github.com/Mugen87
  27899. *
  27900. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27901. *
  27902. */
  27903. function Cylindrical(radius, theta, y) {
  27904. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27905. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27906. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27907. return this;
  27908. }
  27909. Object.assign(Cylindrical.prototype, {
  27910. set: function (radius, theta, y) {
  27911. this.radius = radius;
  27912. this.theta = theta;
  27913. this.y = y;
  27914. return this;
  27915. },
  27916. clone: function () {
  27917. return new this.constructor().copy(this);
  27918. },
  27919. copy: function (other) {
  27920. this.radius = other.radius;
  27921. this.theta = other.theta;
  27922. this.y = other.y;
  27923. return this;
  27924. },
  27925. setFromVector3: function (v) {
  27926. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27927. },
  27928. setFromCartesianCoords: function (x, y, z) {
  27929. this.radius = Math.sqrt(x * x + z * z);
  27930. this.theta = Math.atan2(x, z);
  27931. this.y = y;
  27932. return this;
  27933. }
  27934. });
  27935. /**
  27936. * @author bhouston / http://clara.io
  27937. */
  27938. var _vector$6 = new Vector2();
  27939. function Box2(min, max) {
  27940. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27941. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27942. }
  27943. Object.assign(Box2.prototype, {
  27944. set: function (min, max) {
  27945. this.min.copy(min);
  27946. this.max.copy(max);
  27947. return this;
  27948. },
  27949. setFromPoints: function (points) {
  27950. this.makeEmpty();
  27951. for (var i = 0, il = points.length; i < il; i++) {
  27952. this.expandByPoint(points[i]);
  27953. }
  27954. return this;
  27955. },
  27956. setFromCenterAndSize: function (center, size) {
  27957. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  27958. this.min.copy(center).sub(halfSize);
  27959. this.max.copy(center).add(halfSize);
  27960. return this;
  27961. },
  27962. clone: function () {
  27963. return new this.constructor().copy(this);
  27964. },
  27965. copy: function (box) {
  27966. this.min.copy(box.min);
  27967. this.max.copy(box.max);
  27968. return this;
  27969. },
  27970. makeEmpty: function () {
  27971. this.min.x = this.min.y = +Infinity;
  27972. this.max.x = this.max.y = -Infinity;
  27973. return this;
  27974. },
  27975. isEmpty: function () {
  27976. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27977. return this.max.x < this.min.x || this.max.y < this.min.y;
  27978. },
  27979. getCenter: function (target) {
  27980. if (target === undefined) {
  27981. console.warn('THREE.Box2: .getCenter() target is now required');
  27982. target = new Vector2();
  27983. }
  27984. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27985. },
  27986. getSize: function (target) {
  27987. if (target === undefined) {
  27988. console.warn('THREE.Box2: .getSize() target is now required');
  27989. target = new Vector2();
  27990. }
  27991. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27992. },
  27993. expandByPoint: function (point) {
  27994. this.min.min(point);
  27995. this.max.max(point);
  27996. return this;
  27997. },
  27998. expandByVector: function (vector) {
  27999. this.min.sub(vector);
  28000. this.max.add(vector);
  28001. return this;
  28002. },
  28003. expandByScalar: function (scalar) {
  28004. this.min.addScalar(-scalar);
  28005. this.max.addScalar(scalar);
  28006. return this;
  28007. },
  28008. containsPoint: function (point) {
  28009. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28010. },
  28011. containsBox: function (box) {
  28012. 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;
  28013. },
  28014. getParameter: function (point, target) {
  28015. // This can potentially have a divide by zero if the box
  28016. // has a size dimension of 0.
  28017. if (target === undefined) {
  28018. console.warn('THREE.Box2: .getParameter() target is now required');
  28019. target = new Vector2();
  28020. }
  28021. 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));
  28022. },
  28023. intersectsBox: function (box) {
  28024. // using 4 splitting planes to rule out intersections
  28025. 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;
  28026. },
  28027. clampPoint: function (point, target) {
  28028. if (target === undefined) {
  28029. console.warn('THREE.Box2: .clampPoint() target is now required');
  28030. target = new Vector2();
  28031. }
  28032. return target.copy(point).clamp(this.min, this.max);
  28033. },
  28034. distanceToPoint: function (point) {
  28035. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  28036. return clampedPoint.sub(point).length();
  28037. },
  28038. intersect: function (box) {
  28039. this.min.max(box.min);
  28040. this.max.min(box.max);
  28041. return this;
  28042. },
  28043. union: function (box) {
  28044. this.min.min(box.min);
  28045. this.max.max(box.max);
  28046. return this;
  28047. },
  28048. translate: function (offset) {
  28049. this.min.add(offset);
  28050. this.max.add(offset);
  28051. return this;
  28052. },
  28053. equals: function (box) {
  28054. return box.min.equals(this.min) && box.max.equals(this.max);
  28055. }
  28056. });
  28057. /**
  28058. * @author bhouston / http://clara.io
  28059. */
  28060. var _startP = new Vector3();
  28061. var _startEnd = new Vector3();
  28062. function Line3(start, end) {
  28063. this.start = start !== undefined ? start : new Vector3();
  28064. this.end = end !== undefined ? end : new Vector3();
  28065. }
  28066. Object.assign(Line3.prototype, {
  28067. set: function (start, end) {
  28068. this.start.copy(start);
  28069. this.end.copy(end);
  28070. return this;
  28071. },
  28072. clone: function () {
  28073. return new this.constructor().copy(this);
  28074. },
  28075. copy: function (line) {
  28076. this.start.copy(line.start);
  28077. this.end.copy(line.end);
  28078. return this;
  28079. },
  28080. getCenter: function (target) {
  28081. if (target === undefined) {
  28082. console.warn('THREE.Line3: .getCenter() target is now required');
  28083. target = new Vector3();
  28084. }
  28085. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28086. },
  28087. delta: function (target) {
  28088. if (target === undefined) {
  28089. console.warn('THREE.Line3: .delta() target is now required');
  28090. target = new Vector3();
  28091. }
  28092. return target.subVectors(this.end, this.start);
  28093. },
  28094. distanceSq: function () {
  28095. return this.start.distanceToSquared(this.end);
  28096. },
  28097. distance: function () {
  28098. return this.start.distanceTo(this.end);
  28099. },
  28100. at: function (t, target) {
  28101. if (target === undefined) {
  28102. console.warn('THREE.Line3: .at() target is now required');
  28103. target = new Vector3();
  28104. }
  28105. return this.delta(target).multiplyScalar(t).add(this.start);
  28106. },
  28107. closestPointToPointParameter: function (point, clampToLine) {
  28108. _startP.subVectors(point, this.start);
  28109. _startEnd.subVectors(this.end, this.start);
  28110. var startEnd2 = _startEnd.dot(_startEnd);
  28111. var startEnd_startP = _startEnd.dot(_startP);
  28112. var t = startEnd_startP / startEnd2;
  28113. if (clampToLine) {
  28114. t = _Math.clamp(t, 0, 1);
  28115. }
  28116. return t;
  28117. },
  28118. closestPointToPoint: function (point, clampToLine, target) {
  28119. var t = this.closestPointToPointParameter(point, clampToLine);
  28120. if (target === undefined) {
  28121. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  28122. target = new Vector3();
  28123. }
  28124. return this.delta(target).multiplyScalar(t).add(this.start);
  28125. },
  28126. applyMatrix4: function (matrix) {
  28127. this.start.applyMatrix4(matrix);
  28128. this.end.applyMatrix4(matrix);
  28129. return this;
  28130. },
  28131. equals: function (line) {
  28132. return line.start.equals(this.start) && line.end.equals(this.end);
  28133. }
  28134. });
  28135. /**
  28136. * @author alteredq / http://alteredqualia.com/
  28137. */
  28138. function ImmediateRenderObject(material) {
  28139. Object3D.call(this);
  28140. this.material = material;
  28141. this.render = function ()
  28142. /* renderCallback */
  28143. {};
  28144. }
  28145. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28146. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28147. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28148. /**
  28149. * @author mrdoob / http://mrdoob.com/
  28150. * @author WestLangley / http://github.com/WestLangley
  28151. */
  28152. var _v1$5 = new Vector3();
  28153. var _v2$3 = new Vector3();
  28154. var _normalMatrix$1 = new Matrix3();
  28155. var _keys = ['a', 'b', 'c'];
  28156. function VertexNormalsHelper(object, size, hex, linewidth) {
  28157. this.object = object;
  28158. this.size = size !== undefined ? size : 1;
  28159. var color = hex !== undefined ? hex : 0xff0000;
  28160. var width = linewidth !== undefined ? linewidth : 1; //
  28161. var nNormals = 0;
  28162. var objGeometry = this.object.geometry;
  28163. if (objGeometry && objGeometry.isGeometry) {
  28164. nNormals = objGeometry.faces.length * 3;
  28165. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28166. nNormals = objGeometry.attributes.normal.count;
  28167. } //
  28168. var geometry = new BufferGeometry();
  28169. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28170. geometry.addAttribute('position', positions);
  28171. LineSegments.call(this, geometry, new LineBasicMaterial({
  28172. color: color,
  28173. linewidth: width
  28174. })); //
  28175. this.matrixAutoUpdate = false;
  28176. this.update();
  28177. }
  28178. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28179. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28180. VertexNormalsHelper.prototype.update = function () {
  28181. this.object.updateMatrixWorld(true);
  28182. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  28183. var matrixWorld = this.object.matrixWorld;
  28184. var position = this.geometry.attributes.position; //
  28185. var objGeometry = this.object.geometry;
  28186. if (objGeometry && objGeometry.isGeometry) {
  28187. var vertices = objGeometry.vertices;
  28188. var faces = objGeometry.faces;
  28189. var idx = 0;
  28190. for (var i = 0, l = faces.length; i < l; i++) {
  28191. var face = faces[i];
  28192. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  28193. var vertex = vertices[face[_keys[j]]];
  28194. var normal = face.vertexNormals[j];
  28195. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  28196. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28197. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28198. idx = idx + 1;
  28199. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28200. idx = idx + 1;
  28201. }
  28202. }
  28203. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28204. var objPos = objGeometry.attributes.position;
  28205. var objNorm = objGeometry.attributes.normal;
  28206. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  28207. for (var j = 0, jl = objPos.count; j < jl; j++) {
  28208. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  28209. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  28210. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28211. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28212. idx = idx + 1;
  28213. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28214. idx = idx + 1;
  28215. }
  28216. }
  28217. position.needsUpdate = true;
  28218. };
  28219. /**
  28220. * @author alteredq / http://alteredqualia.com/
  28221. * @author mrdoob / http://mrdoob.com/
  28222. * @author WestLangley / http://github.com/WestLangley
  28223. */
  28224. var _vector$7 = new Vector3();
  28225. function SpotLightHelper(light, color) {
  28226. Object3D.call(this);
  28227. this.light = light;
  28228. this.light.updateMatrixWorld();
  28229. this.matrix = light.matrixWorld;
  28230. this.matrixAutoUpdate = false;
  28231. this.color = color;
  28232. var geometry = new BufferGeometry();
  28233. 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];
  28234. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  28235. var p1 = i / l * Math.PI * 2;
  28236. var p2 = j / l * Math.PI * 2;
  28237. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28238. }
  28239. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28240. var material = new LineBasicMaterial({
  28241. fog: false
  28242. });
  28243. this.cone = new LineSegments(geometry, material);
  28244. this.add(this.cone);
  28245. this.update();
  28246. }
  28247. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  28248. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28249. SpotLightHelper.prototype.dispose = function () {
  28250. this.cone.geometry.dispose();
  28251. this.cone.material.dispose();
  28252. };
  28253. SpotLightHelper.prototype.update = function () {
  28254. this.light.updateMatrixWorld();
  28255. var coneLength = this.light.distance ? this.light.distance : 1000;
  28256. var coneWidth = coneLength * Math.tan(this.light.angle);
  28257. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28258. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  28259. this.cone.lookAt(_vector$7);
  28260. if (this.color !== undefined) {
  28261. this.cone.material.color.set(this.color);
  28262. } else {
  28263. this.cone.material.color.copy(this.light.color);
  28264. }
  28265. };
  28266. /**
  28267. * @author Sean Griffin / http://twitter.com/sgrif
  28268. * @author Michael Guerrero / http://realitymeltdown.com
  28269. * @author mrdoob / http://mrdoob.com/
  28270. * @author ikerr / http://verold.com
  28271. * @author Mugen87 / https://github.com/Mugen87
  28272. */
  28273. var _vector$8 = new Vector3();
  28274. var _boneMatrix = new Matrix4();
  28275. var _matrixWorldInv = new Matrix4();
  28276. function getBoneList(object) {
  28277. var boneList = [];
  28278. if (object && object.isBone) {
  28279. boneList.push(object);
  28280. }
  28281. for (var i = 0; i < object.children.length; i++) {
  28282. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28283. }
  28284. return boneList;
  28285. }
  28286. function SkeletonHelper(object) {
  28287. var bones = getBoneList(object);
  28288. var geometry = new BufferGeometry();
  28289. var vertices = [];
  28290. var colors = [];
  28291. var color1 = new Color(0, 0, 1);
  28292. var color2 = new Color(0, 1, 0);
  28293. for (var i = 0; i < bones.length; i++) {
  28294. var bone = bones[i];
  28295. if (bone.parent && bone.parent.isBone) {
  28296. vertices.push(0, 0, 0);
  28297. vertices.push(0, 0, 0);
  28298. colors.push(color1.r, color1.g, color1.b);
  28299. colors.push(color2.r, color2.g, color2.b);
  28300. }
  28301. }
  28302. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28303. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28304. var material = new LineBasicMaterial({
  28305. vertexColors: VertexColors,
  28306. depthTest: false,
  28307. depthWrite: false,
  28308. transparent: true
  28309. });
  28310. LineSegments.call(this, geometry, material);
  28311. this.root = object;
  28312. this.bones = bones;
  28313. this.matrix = object.matrixWorld;
  28314. this.matrixAutoUpdate = false;
  28315. }
  28316. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  28317. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28318. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  28319. var bones = this.bones;
  28320. var geometry = this.geometry;
  28321. var position = geometry.getAttribute('position');
  28322. _matrixWorldInv.getInverse(this.root.matrixWorld);
  28323. for (var i = 0, j = 0; i < bones.length; i++) {
  28324. var bone = bones[i];
  28325. if (bone.parent && bone.parent.isBone) {
  28326. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28327. _vector$8.setFromMatrixPosition(_boneMatrix);
  28328. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  28329. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28330. _vector$8.setFromMatrixPosition(_boneMatrix);
  28331. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  28332. j += 2;
  28333. }
  28334. }
  28335. geometry.getAttribute('position').needsUpdate = true;
  28336. Object3D.prototype.updateMatrixWorld.call(this, force);
  28337. };
  28338. /**
  28339. * @author alteredq / http://alteredqualia.com/
  28340. * @author mrdoob / http://mrdoob.com/
  28341. */
  28342. function PointLightHelper(light, sphereSize, color) {
  28343. this.light = light;
  28344. this.light.updateMatrixWorld();
  28345. this.color = color;
  28346. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28347. var material = new MeshBasicMaterial({
  28348. wireframe: true,
  28349. fog: false
  28350. });
  28351. Mesh.call(this, geometry, material);
  28352. this.matrix = this.light.matrixWorld;
  28353. this.matrixAutoUpdate = false;
  28354. this.update();
  28355. /*
  28356. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28357. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28358. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28359. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28360. var d = light.distance;
  28361. if ( d === 0.0 ) {
  28362. this.lightDistance.visible = false;
  28363. } else {
  28364. this.lightDistance.scale.set( d, d, d );
  28365. }
  28366. this.add( this.lightDistance );
  28367. */
  28368. }
  28369. PointLightHelper.prototype = Object.create(Mesh.prototype);
  28370. PointLightHelper.prototype.constructor = PointLightHelper;
  28371. PointLightHelper.prototype.dispose = function () {
  28372. this.geometry.dispose();
  28373. this.material.dispose();
  28374. };
  28375. PointLightHelper.prototype.update = function () {
  28376. if (this.color !== undefined) {
  28377. this.material.color.set(this.color);
  28378. } else {
  28379. this.material.color.copy(this.light.color);
  28380. }
  28381. /*
  28382. var d = this.light.distance;
  28383. if ( d === 0.0 ) {
  28384. this.lightDistance.visible = false;
  28385. } else {
  28386. this.lightDistance.visible = true;
  28387. this.lightDistance.scale.set( d, d, d );
  28388. }
  28389. */
  28390. };
  28391. /**
  28392. * @author abelnation / http://github.com/abelnation
  28393. * @author Mugen87 / http://github.com/Mugen87
  28394. * @author WestLangley / http://github.com/WestLangley
  28395. *
  28396. * This helper must be added as a child of the light
  28397. */
  28398. function RectAreaLightHelper(light, color) {
  28399. this.type = 'RectAreaLightHelper';
  28400. this.light = light;
  28401. this.color = color; // optional hardwired color for the helper
  28402. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28403. var geometry = new BufferGeometry();
  28404. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28405. geometry.computeBoundingSphere();
  28406. var material = new LineBasicMaterial({
  28407. fog: false
  28408. });
  28409. Line.call(this, geometry, material); //
  28410. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28411. var geometry2 = new BufferGeometry();
  28412. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  28413. geometry2.computeBoundingSphere();
  28414. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28415. side: BackSide,
  28416. fog: false
  28417. })));
  28418. this.update();
  28419. }
  28420. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  28421. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28422. RectAreaLightHelper.prototype.update = function () {
  28423. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  28424. if (this.color !== undefined) {
  28425. this.material.color.set(this.color);
  28426. this.children[0].material.color.set(this.color);
  28427. } else {
  28428. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  28429. var c = this.material.color;
  28430. var max = Math.max(c.r, c.g, c.b);
  28431. if (max > 1) c.multiplyScalar(1 / max);
  28432. this.children[0].material.color.copy(this.material.color);
  28433. }
  28434. };
  28435. RectAreaLightHelper.prototype.dispose = function () {
  28436. this.geometry.dispose();
  28437. this.material.dispose();
  28438. this.children[0].geometry.dispose();
  28439. this.children[0].material.dispose();
  28440. };
  28441. /**
  28442. * @author alteredq / http://alteredqualia.com/
  28443. * @author mrdoob / http://mrdoob.com/
  28444. * @author Mugen87 / https://github.com/Mugen87
  28445. */
  28446. var _vector$9 = new Vector3();
  28447. var _color1 = new Color();
  28448. var _color2 = new Color();
  28449. function HemisphereLightHelper(light, size, color) {
  28450. Object3D.call(this);
  28451. this.light = light;
  28452. this.light.updateMatrixWorld();
  28453. this.matrix = light.matrixWorld;
  28454. this.matrixAutoUpdate = false;
  28455. this.color = color;
  28456. var geometry = new OctahedronBufferGeometry(size);
  28457. geometry.rotateY(Math.PI * 0.5);
  28458. this.material = new MeshBasicMaterial({
  28459. wireframe: true,
  28460. fog: false
  28461. });
  28462. if (this.color === undefined) this.material.vertexColors = VertexColors;
  28463. var position = geometry.getAttribute('position');
  28464. var colors = new Float32Array(position.count * 3);
  28465. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  28466. this.add(new Mesh(geometry, this.material));
  28467. this.update();
  28468. }
  28469. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  28470. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28471. HemisphereLightHelper.prototype.dispose = function () {
  28472. this.children[0].geometry.dispose();
  28473. this.children[0].material.dispose();
  28474. };
  28475. HemisphereLightHelper.prototype.update = function () {
  28476. var mesh = this.children[0];
  28477. if (this.color !== undefined) {
  28478. this.material.color.set(this.color);
  28479. } else {
  28480. var colors = mesh.geometry.getAttribute('color');
  28481. _color1.copy(this.light.color);
  28482. _color2.copy(this.light.groundColor);
  28483. for (var i = 0, l = colors.count; i < l; i++) {
  28484. var color = i < l / 2 ? _color1 : _color2;
  28485. colors.setXYZ(i, color.r, color.g, color.b);
  28486. }
  28487. colors.needsUpdate = true;
  28488. }
  28489. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  28490. };
  28491. /**
  28492. * @author WestLangley / http://github.com/WestLangley
  28493. */
  28494. function LightProbeHelper(lightProbe, size) {
  28495. this.lightProbe = lightProbe;
  28496. this.size = size;
  28497. var defines = {};
  28498. defines['GAMMA_OUTPUT'] = ""; // material
  28499. var material = new ShaderMaterial({
  28500. defines: defines,
  28501. uniforms: {
  28502. sh: {
  28503. value: this.lightProbe.sh.coefficients
  28504. },
  28505. // by reference
  28506. intensity: {
  28507. value: this.lightProbe.intensity
  28508. }
  28509. },
  28510. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  28511. fragmentShader: ['#define RECIPROCAL_PI 0.318309886', 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {', ' // matrix is assumed to be orthogonal', ' return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );', '}', 'vec3 linearToOutput( in vec3 a ) {', ' #ifdef GAMMA_OUTPUT', ' return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );', ' #else', ' return a;', ' #endif', '}', '// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf', 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {', ' // normal is assumed to have unit length', ' float x = normal.x, y = normal.y, z = normal.z;', ' // band 0', ' vec3 result = shCoefficients[ 0 ] * 0.886227;', ' // band 1', ' result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;', ' result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;', ' result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;', ' // band 2', ' result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;', ' result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;', ' result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );', ' result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;', ' result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );', ' return result;', '}', 'uniform vec3 sh[ 9 ]; // sh coefficients', 'uniform float intensity; // light probe intensity', 'varying vec3 vNormal;', 'void main() {', ' vec3 normal = normalize( vNormal );', ' vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );', ' vec3 irradiance = shGetIrradianceAt( worldNormal, sh );', ' vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;', ' outgoingLight = linearToOutput( outgoingLight );', ' gl_FragColor = vec4( outgoingLight, 1.0 );', '}'].join('\n')
  28512. });
  28513. var geometry = new SphereBufferGeometry(1, 32, 16);
  28514. Mesh.call(this, geometry, material);
  28515. this.onBeforeRender();
  28516. }
  28517. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  28518. LightProbeHelper.prototype.constructor = LightProbeHelper;
  28519. LightProbeHelper.prototype.dispose = function () {
  28520. this.geometry.dispose();
  28521. this.material.dispose();
  28522. };
  28523. LightProbeHelper.prototype.onBeforeRender = function () {
  28524. this.position.copy(this.lightProbe.position);
  28525. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  28526. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  28527. };
  28528. /**
  28529. * @author mrdoob / http://mrdoob.com/
  28530. */
  28531. function GridHelper(size, divisions, color1, color2) {
  28532. size = size || 10;
  28533. divisions = divisions || 10;
  28534. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28535. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28536. var center = divisions / 2;
  28537. var step = size / divisions;
  28538. var halfSize = size / 2;
  28539. var vertices = [],
  28540. colors = [];
  28541. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28542. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28543. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28544. var color = i === center ? color1 : color2;
  28545. color.toArray(colors, j);
  28546. j += 3;
  28547. color.toArray(colors, j);
  28548. j += 3;
  28549. color.toArray(colors, j);
  28550. j += 3;
  28551. color.toArray(colors, j);
  28552. j += 3;
  28553. }
  28554. var geometry = new BufferGeometry();
  28555. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28556. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28557. var material = new LineBasicMaterial({
  28558. vertexColors: VertexColors
  28559. });
  28560. LineSegments.call(this, geometry, material);
  28561. }
  28562. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  28563. constructor: GridHelper,
  28564. copy: function (source) {
  28565. LineSegments.prototype.copy.call(this, source);
  28566. this.geometry.copy(source.geometry);
  28567. this.material.copy(source.material);
  28568. return this;
  28569. },
  28570. clone: function () {
  28571. return new this.constructor().copy(this);
  28572. }
  28573. });
  28574. /**
  28575. * @author mrdoob / http://mrdoob.com/
  28576. * @author Mugen87 / http://github.com/Mugen87
  28577. * @author Hectate / http://www.github.com/Hectate
  28578. */
  28579. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  28580. radius = radius || 10;
  28581. radials = radials || 16;
  28582. circles = circles || 8;
  28583. divisions = divisions || 64;
  28584. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28585. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28586. var vertices = [];
  28587. var colors = [];
  28588. var x, z;
  28589. var v, i, j, r, color; // create the radials
  28590. for (i = 0; i <= radials; i++) {
  28591. v = i / radials * (Math.PI * 2);
  28592. x = Math.sin(v) * radius;
  28593. z = Math.cos(v) * radius;
  28594. vertices.push(0, 0, 0);
  28595. vertices.push(x, 0, z);
  28596. color = i & 1 ? color1 : color2;
  28597. colors.push(color.r, color.g, color.b);
  28598. colors.push(color.r, color.g, color.b);
  28599. } // create the circles
  28600. for (i = 0; i <= circles; i++) {
  28601. color = i & 1 ? color1 : color2;
  28602. r = radius - radius / circles * i;
  28603. for (j = 0; j < divisions; j++) {
  28604. // first vertex
  28605. v = j / divisions * (Math.PI * 2);
  28606. x = Math.sin(v) * r;
  28607. z = Math.cos(v) * r;
  28608. vertices.push(x, 0, z);
  28609. colors.push(color.r, color.g, color.b); // second vertex
  28610. v = (j + 1) / divisions * (Math.PI * 2);
  28611. x = Math.sin(v) * r;
  28612. z = Math.cos(v) * r;
  28613. vertices.push(x, 0, z);
  28614. colors.push(color.r, color.g, color.b);
  28615. }
  28616. }
  28617. var geometry = new BufferGeometry();
  28618. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28619. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28620. var material = new LineBasicMaterial({
  28621. vertexColors: VertexColors
  28622. });
  28623. LineSegments.call(this, geometry, material);
  28624. }
  28625. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  28626. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28627. /**
  28628. * @author Mugen87 / http://github.com/Mugen87
  28629. */
  28630. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  28631. this.audio = audio;
  28632. this.range = range || 1;
  28633. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  28634. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  28635. var geometry = new BufferGeometry();
  28636. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  28637. var positions = new Float32Array((divisions * 3 + 3) * 3);
  28638. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28639. var materialInnerAngle = new LineBasicMaterial({
  28640. color: 0x00ff00
  28641. });
  28642. var materialOuterAngle = new LineBasicMaterial({
  28643. color: 0xffff00
  28644. });
  28645. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  28646. this.update();
  28647. }
  28648. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  28649. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  28650. PositionalAudioHelper.prototype.update = function () {
  28651. var audio = this.audio;
  28652. var range = this.range;
  28653. var divisionsInnerAngle = this.divisionsInnerAngle;
  28654. var divisionsOuterAngle = this.divisionsOuterAngle;
  28655. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  28656. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  28657. var halfConeInnerAngle = coneInnerAngle / 2;
  28658. var halfConeOuterAngle = coneOuterAngle / 2;
  28659. var start = 0;
  28660. var count = 0;
  28661. var i, stride;
  28662. var geometry = this.geometry;
  28663. var positionAttribute = geometry.attributes.position;
  28664. geometry.clearGroups(); //
  28665. function generateSegment(from, to, divisions, materialIndex) {
  28666. var step = (to - from) / divisions;
  28667. positionAttribute.setXYZ(start, 0, 0, 0);
  28668. count++;
  28669. for (i = from; i < to; i += step) {
  28670. stride = start + count;
  28671. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  28672. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  28673. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  28674. count += 3;
  28675. }
  28676. geometry.addGroup(start, count, materialIndex);
  28677. start += count;
  28678. count = 0;
  28679. } //
  28680. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  28681. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  28682. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  28683. positionAttribute.needsUpdate = true;
  28684. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  28685. };
  28686. PositionalAudioHelper.prototype.dispose = function () {
  28687. this.geometry.dispose();
  28688. this.material[0].dispose();
  28689. this.material[1].dispose();
  28690. };
  28691. /**
  28692. * @author mrdoob / http://mrdoob.com/
  28693. * @author WestLangley / http://github.com/WestLangley
  28694. */
  28695. var _v1$6 = new Vector3();
  28696. var _v2$4 = new Vector3();
  28697. var _normalMatrix$2 = new Matrix3();
  28698. function FaceNormalsHelper(object, size, hex, linewidth) {
  28699. // FaceNormalsHelper only supports THREE.Geometry
  28700. this.object = object;
  28701. this.size = size !== undefined ? size : 1;
  28702. var color = hex !== undefined ? hex : 0xffff00;
  28703. var width = linewidth !== undefined ? linewidth : 1; //
  28704. var nNormals = 0;
  28705. var objGeometry = this.object.geometry;
  28706. if (objGeometry && objGeometry.isGeometry) {
  28707. nNormals = objGeometry.faces.length;
  28708. } else {
  28709. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  28710. } //
  28711. var geometry = new BufferGeometry();
  28712. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28713. geometry.addAttribute('position', positions);
  28714. LineSegments.call(this, geometry, new LineBasicMaterial({
  28715. color: color,
  28716. linewidth: width
  28717. })); //
  28718. this.matrixAutoUpdate = false;
  28719. this.update();
  28720. }
  28721. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28722. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28723. FaceNormalsHelper.prototype.update = function () {
  28724. this.object.updateMatrixWorld(true);
  28725. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  28726. var matrixWorld = this.object.matrixWorld;
  28727. var position = this.geometry.attributes.position; //
  28728. var objGeometry = this.object.geometry;
  28729. var vertices = objGeometry.vertices;
  28730. var faces = objGeometry.faces;
  28731. var idx = 0;
  28732. for (var i = 0, l = faces.length; i < l; i++) {
  28733. var face = faces[i];
  28734. var normal = face.normal;
  28735. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  28736. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  28737. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  28738. idx = idx + 1;
  28739. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  28740. idx = idx + 1;
  28741. }
  28742. position.needsUpdate = true;
  28743. };
  28744. /**
  28745. * @author alteredq / http://alteredqualia.com/
  28746. * @author mrdoob / http://mrdoob.com/
  28747. * @author WestLangley / http://github.com/WestLangley
  28748. */
  28749. var _v1$7 = new Vector3();
  28750. var _v2$5 = new Vector3();
  28751. var _v3$1 = new Vector3();
  28752. function DirectionalLightHelper(light, size, color) {
  28753. Object3D.call(this);
  28754. this.light = light;
  28755. this.light.updateMatrixWorld();
  28756. this.matrix = light.matrixWorld;
  28757. this.matrixAutoUpdate = false;
  28758. this.color = color;
  28759. if (size === undefined) size = 1;
  28760. var geometry = new BufferGeometry();
  28761. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28762. var material = new LineBasicMaterial({
  28763. fog: false
  28764. });
  28765. this.lightPlane = new Line(geometry, material);
  28766. this.add(this.lightPlane);
  28767. geometry = new BufferGeometry();
  28768. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28769. this.targetLine = new Line(geometry, material);
  28770. this.add(this.targetLine);
  28771. this.update();
  28772. }
  28773. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  28774. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28775. DirectionalLightHelper.prototype.dispose = function () {
  28776. this.lightPlane.geometry.dispose();
  28777. this.lightPlane.material.dispose();
  28778. this.targetLine.geometry.dispose();
  28779. this.targetLine.material.dispose();
  28780. };
  28781. DirectionalLightHelper.prototype.update = function () {
  28782. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  28783. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  28784. _v3$1.subVectors(_v2$5, _v1$7);
  28785. this.lightPlane.lookAt(_v2$5);
  28786. if (this.color !== undefined) {
  28787. this.lightPlane.material.color.set(this.color);
  28788. this.targetLine.material.color.set(this.color);
  28789. } else {
  28790. this.lightPlane.material.color.copy(this.light.color);
  28791. this.targetLine.material.color.copy(this.light.color);
  28792. }
  28793. this.targetLine.lookAt(_v2$5);
  28794. this.targetLine.scale.z = _v3$1.length();
  28795. };
  28796. /**
  28797. * @author alteredq / http://alteredqualia.com/
  28798. * @author Mugen87 / https://github.com/Mugen87
  28799. *
  28800. * - shows frustum, line of sight and up of the camera
  28801. * - suitable for fast updates
  28802. * - based on frustum visualization in lightgl.js shadowmap example
  28803. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28804. */
  28805. var _vector$a = new Vector3();
  28806. var _camera = new Camera();
  28807. function CameraHelper(camera) {
  28808. var geometry = new BufferGeometry();
  28809. var material = new LineBasicMaterial({
  28810. color: 0xffffff,
  28811. vertexColors: FaceColors
  28812. });
  28813. var vertices = [];
  28814. var colors = [];
  28815. var pointMap = {}; // colors
  28816. var colorFrustum = new Color(0xffaa00);
  28817. var colorCone = new Color(0xff0000);
  28818. var colorUp = new Color(0x00aaff);
  28819. var colorTarget = new Color(0xffffff);
  28820. var colorCross = new Color(0x333333); // near
  28821. addLine('n1', 'n2', colorFrustum);
  28822. addLine('n2', 'n4', colorFrustum);
  28823. addLine('n4', 'n3', colorFrustum);
  28824. addLine('n3', 'n1', colorFrustum); // far
  28825. addLine('f1', 'f2', colorFrustum);
  28826. addLine('f2', 'f4', colorFrustum);
  28827. addLine('f4', 'f3', colorFrustum);
  28828. addLine('f3', 'f1', colorFrustum); // sides
  28829. addLine('n1', 'f1', colorFrustum);
  28830. addLine('n2', 'f2', colorFrustum);
  28831. addLine('n3', 'f3', colorFrustum);
  28832. addLine('n4', 'f4', colorFrustum); // cone
  28833. addLine('p', 'n1', colorCone);
  28834. addLine('p', 'n2', colorCone);
  28835. addLine('p', 'n3', colorCone);
  28836. addLine('p', 'n4', colorCone); // up
  28837. addLine('u1', 'u2', colorUp);
  28838. addLine('u2', 'u3', colorUp);
  28839. addLine('u3', 'u1', colorUp); // target
  28840. addLine('c', 't', colorTarget);
  28841. addLine('p', 'c', colorCross); // cross
  28842. addLine('cn1', 'cn2', colorCross);
  28843. addLine('cn3', 'cn4', colorCross);
  28844. addLine('cf1', 'cf2', colorCross);
  28845. addLine('cf3', 'cf4', colorCross);
  28846. function addLine(a, b, color) {
  28847. addPoint(a, color);
  28848. addPoint(b, color);
  28849. }
  28850. function addPoint(id, color) {
  28851. vertices.push(0, 0, 0);
  28852. colors.push(color.r, color.g, color.b);
  28853. if (pointMap[id] === undefined) {
  28854. pointMap[id] = [];
  28855. }
  28856. pointMap[id].push(vertices.length / 3 - 1);
  28857. }
  28858. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28859. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28860. LineSegments.call(this, geometry, material);
  28861. this.camera = camera;
  28862. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28863. this.matrix = camera.matrixWorld;
  28864. this.matrixAutoUpdate = false;
  28865. this.pointMap = pointMap;
  28866. this.update();
  28867. }
  28868. CameraHelper.prototype = Object.create(LineSegments.prototype);
  28869. CameraHelper.prototype.constructor = CameraHelper;
  28870. CameraHelper.prototype.update = function () {
  28871. var geometry = this.geometry;
  28872. var pointMap = this.pointMap;
  28873. var w = 1,
  28874. h = 1; // we need just camera projection matrix inverse
  28875. // world matrix must be identity
  28876. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28877. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28878. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28879. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28880. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28881. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28882. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28883. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28884. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28885. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28886. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28887. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28888. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28889. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28890. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28891. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28892. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28893. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28894. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28895. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28896. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28897. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28898. geometry.getAttribute('position').needsUpdate = true;
  28899. };
  28900. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28901. _vector$a.set(x, y, z).unproject(camera);
  28902. var points = pointMap[point];
  28903. if (points !== undefined) {
  28904. var position = geometry.getAttribute('position');
  28905. for (var i = 0, l = points.length; i < l; i++) {
  28906. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  28907. }
  28908. }
  28909. }
  28910. /**
  28911. * @author mrdoob / http://mrdoob.com/
  28912. * @author Mugen87 / http://github.com/Mugen87
  28913. */
  28914. var _box$2 = new Box3();
  28915. function BoxHelper(object, color) {
  28916. this.object = object;
  28917. if (color === undefined) color = 0xffff00;
  28918. 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]);
  28919. var positions = new Float32Array(8 * 3);
  28920. var geometry = new BufferGeometry();
  28921. geometry.setIndex(new BufferAttribute(indices, 1));
  28922. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28923. LineSegments.call(this, geometry, new LineBasicMaterial({
  28924. color: color
  28925. }));
  28926. this.matrixAutoUpdate = false;
  28927. this.update();
  28928. }
  28929. BoxHelper.prototype = Object.create(LineSegments.prototype);
  28930. BoxHelper.prototype.constructor = BoxHelper;
  28931. BoxHelper.prototype.update = function (object) {
  28932. if (object !== undefined) {
  28933. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28934. }
  28935. if (this.object !== undefined) {
  28936. _box$2.setFromObject(this.object);
  28937. }
  28938. if (_box$2.isEmpty()) return;
  28939. var min = _box$2.min;
  28940. var max = _box$2.max;
  28941. /*
  28942. 5____4
  28943. 1/___0/|
  28944. | 6__|_7
  28945. 2/___3/
  28946. 0: max.x, max.y, max.z
  28947. 1: min.x, max.y, max.z
  28948. 2: min.x, min.y, max.z
  28949. 3: max.x, min.y, max.z
  28950. 4: max.x, max.y, min.z
  28951. 5: min.x, max.y, min.z
  28952. 6: min.x, min.y, min.z
  28953. 7: max.x, min.y, min.z
  28954. */
  28955. var position = this.geometry.attributes.position;
  28956. var array = position.array;
  28957. array[0] = max.x;
  28958. array[1] = max.y;
  28959. array[2] = max.z;
  28960. array[3] = min.x;
  28961. array[4] = max.y;
  28962. array[5] = max.z;
  28963. array[6] = min.x;
  28964. array[7] = min.y;
  28965. array[8] = max.z;
  28966. array[9] = max.x;
  28967. array[10] = min.y;
  28968. array[11] = max.z;
  28969. array[12] = max.x;
  28970. array[13] = max.y;
  28971. array[14] = min.z;
  28972. array[15] = min.x;
  28973. array[16] = max.y;
  28974. array[17] = min.z;
  28975. array[18] = min.x;
  28976. array[19] = min.y;
  28977. array[20] = min.z;
  28978. array[21] = max.x;
  28979. array[22] = min.y;
  28980. array[23] = min.z;
  28981. position.needsUpdate = true;
  28982. this.geometry.computeBoundingSphere();
  28983. };
  28984. BoxHelper.prototype.setFromObject = function (object) {
  28985. this.object = object;
  28986. this.update();
  28987. return this;
  28988. };
  28989. BoxHelper.prototype.copy = function (source) {
  28990. LineSegments.prototype.copy.call(this, source);
  28991. this.object = source.object;
  28992. return this;
  28993. };
  28994. BoxHelper.prototype.clone = function () {
  28995. return new this.constructor().copy(this);
  28996. };
  28997. /**
  28998. * @author WestLangley / http://github.com/WestLangley
  28999. */
  29000. function Box3Helper(box, color) {
  29001. this.type = 'Box3Helper';
  29002. this.box = box;
  29003. color = color || 0xffff00;
  29004. 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]);
  29005. 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];
  29006. var geometry = new BufferGeometry();
  29007. geometry.setIndex(new BufferAttribute(indices, 1));
  29008. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29009. LineSegments.call(this, geometry, new LineBasicMaterial({
  29010. color: color
  29011. }));
  29012. this.geometry.computeBoundingSphere();
  29013. }
  29014. Box3Helper.prototype = Object.create(LineSegments.prototype);
  29015. Box3Helper.prototype.constructor = Box3Helper;
  29016. Box3Helper.prototype.updateMatrixWorld = function (force) {
  29017. var box = this.box;
  29018. if (box.isEmpty()) return;
  29019. box.getCenter(this.position);
  29020. box.getSize(this.scale);
  29021. this.scale.multiplyScalar(0.5);
  29022. Object3D.prototype.updateMatrixWorld.call(this, force);
  29023. };
  29024. /**
  29025. * @author WestLangley / http://github.com/WestLangley
  29026. */
  29027. function PlaneHelper(plane, size, hex) {
  29028. this.type = 'PlaneHelper';
  29029. this.plane = plane;
  29030. this.size = size === undefined ? 1 : size;
  29031. var color = hex !== undefined ? hex : 0xffff00;
  29032. 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];
  29033. var geometry = new BufferGeometry();
  29034. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29035. geometry.computeBoundingSphere();
  29036. Line.call(this, geometry, new LineBasicMaterial({
  29037. color: color
  29038. })); //
  29039. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  29040. var geometry2 = new BufferGeometry();
  29041. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  29042. geometry2.computeBoundingSphere();
  29043. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29044. color: color,
  29045. opacity: 0.2,
  29046. transparent: true,
  29047. depthWrite: false
  29048. })));
  29049. }
  29050. PlaneHelper.prototype = Object.create(Line.prototype);
  29051. PlaneHelper.prototype.constructor = PlaneHelper;
  29052. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  29053. var scale = -this.plane.constant;
  29054. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  29055. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  29056. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29057. this.lookAt(this.plane.normal);
  29058. Object3D.prototype.updateMatrixWorld.call(this, force);
  29059. };
  29060. /**
  29061. * @author WestLangley / http://github.com/WestLangley
  29062. * @author zz85 / http://github.com/zz85
  29063. * @author bhouston / http://clara.io
  29064. *
  29065. * Creates an arrow for visualizing directions
  29066. *
  29067. * Parameters:
  29068. * dir - Vector3
  29069. * origin - Vector3
  29070. * length - Number
  29071. * color - color in hex value
  29072. * headLength - Number
  29073. * headWidth - Number
  29074. */
  29075. var _axis = new Vector3();
  29076. var _lineGeometry, _coneGeometry;
  29077. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  29078. // dir is assumed to be normalized
  29079. Object3D.call(this);
  29080. if (dir === undefined) dir = new Vector3(0, 0, 1);
  29081. if (origin === undefined) origin = new Vector3(0, 0, 0);
  29082. if (length === undefined) length = 1;
  29083. if (color === undefined) color = 0xffff00;
  29084. if (headLength === undefined) headLength = 0.2 * length;
  29085. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29086. if (_lineGeometry === undefined) {
  29087. _lineGeometry = new BufferGeometry();
  29088. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29089. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  29090. _coneGeometry.translate(0, -0.5, 0);
  29091. }
  29092. this.position.copy(origin);
  29093. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29094. color: color
  29095. }));
  29096. this.line.matrixAutoUpdate = false;
  29097. this.add(this.line);
  29098. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29099. color: color
  29100. }));
  29101. this.cone.matrixAutoUpdate = false;
  29102. this.add(this.cone);
  29103. this.setDirection(dir);
  29104. this.setLength(length, headLength, headWidth);
  29105. }
  29106. ArrowHelper.prototype = Object.create(Object3D.prototype);
  29107. ArrowHelper.prototype.constructor = ArrowHelper;
  29108. ArrowHelper.prototype.setDirection = function (dir) {
  29109. // dir is assumed to be normalized
  29110. if (dir.y > 0.99999) {
  29111. this.quaternion.set(0, 0, 0, 1);
  29112. } else if (dir.y < -0.99999) {
  29113. this.quaternion.set(1, 0, 0, 0);
  29114. } else {
  29115. _axis.set(dir.z, 0, -dir.x).normalize();
  29116. var radians = Math.acos(dir.y);
  29117. this.quaternion.setFromAxisAngle(_axis, radians);
  29118. }
  29119. };
  29120. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  29121. if (headLength === undefined) headLength = 0.2 * length;
  29122. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29123. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29124. this.line.updateMatrix();
  29125. this.cone.scale.set(headWidth, headLength, headWidth);
  29126. this.cone.position.y = length;
  29127. this.cone.updateMatrix();
  29128. };
  29129. ArrowHelper.prototype.setColor = function (color) {
  29130. this.line.material.color.set(color);
  29131. this.cone.material.color.set(color);
  29132. };
  29133. ArrowHelper.prototype.copy = function (source) {
  29134. Object3D.prototype.copy.call(this, source, false);
  29135. this.line.copy(source.line);
  29136. this.cone.copy(source.cone);
  29137. return this;
  29138. };
  29139. ArrowHelper.prototype.clone = function () {
  29140. return new this.constructor().copy(this);
  29141. };
  29142. /**
  29143. * @author sroucheray / http://sroucheray.org/
  29144. * @author mrdoob / http://mrdoob.com/
  29145. */
  29146. function AxesHelper(size) {
  29147. size = size || 1;
  29148. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29149. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29150. var geometry = new BufferGeometry();
  29151. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  29152. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  29153. var material = new LineBasicMaterial({
  29154. vertexColors: VertexColors
  29155. });
  29156. LineSegments.call(this, geometry, material);
  29157. }
  29158. AxesHelper.prototype = Object.create(LineSegments.prototype);
  29159. AxesHelper.prototype.constructor = AxesHelper;
  29160. /**
  29161. * @author mrdoob / http://mrdoob.com/
  29162. */
  29163. function Face4(a, b, c, d, normal, color, materialIndex) {
  29164. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29165. return new Face3(a, b, c, normal, color, materialIndex);
  29166. }
  29167. var LineStrip = 0;
  29168. exports.LineStrip = LineStrip;
  29169. var LinePieces = 1;
  29170. exports.LinePieces = LinePieces;
  29171. function MeshFaceMaterial(materials) {
  29172. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29173. return materials;
  29174. }
  29175. function MultiMaterial(materials) {
  29176. if (materials === undefined) materials = [];
  29177. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29178. materials.isMultiMaterial = true;
  29179. materials.materials = materials;
  29180. materials.clone = function () {
  29181. return materials.slice();
  29182. };
  29183. return materials;
  29184. }
  29185. function PointCloud(geometry, material) {
  29186. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29187. return new Points(geometry, material);
  29188. }
  29189. function Particle(material) {
  29190. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29191. return new Sprite(material);
  29192. }
  29193. function ParticleSystem(geometry, material) {
  29194. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29195. return new Points(geometry, material);
  29196. }
  29197. function PointCloudMaterial(parameters) {
  29198. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29199. return new PointsMaterial(parameters);
  29200. }
  29201. function ParticleBasicMaterial(parameters) {
  29202. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29203. return new PointsMaterial(parameters);
  29204. }
  29205. function ParticleSystemMaterial(parameters) {
  29206. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29207. return new PointsMaterial(parameters);
  29208. }
  29209. function Vertex(x, y, z) {
  29210. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29211. return new Vector3(x, y, z);
  29212. } //
  29213. function DynamicBufferAttribute(array, itemSize) {
  29214. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  29215. return new BufferAttribute(array, itemSize).setDynamic(true);
  29216. }
  29217. function Int8Attribute(array, itemSize) {
  29218. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29219. return new Int8BufferAttribute(array, itemSize);
  29220. }
  29221. function Uint8Attribute(array, itemSize) {
  29222. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29223. return new Uint8BufferAttribute(array, itemSize);
  29224. }
  29225. function Uint8ClampedAttribute(array, itemSize) {
  29226. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29227. return new Uint8ClampedBufferAttribute(array, itemSize);
  29228. }
  29229. function Int16Attribute(array, itemSize) {
  29230. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29231. return new Int16BufferAttribute(array, itemSize);
  29232. }
  29233. function Uint16Attribute(array, itemSize) {
  29234. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29235. return new Uint16BufferAttribute(array, itemSize);
  29236. }
  29237. function Int32Attribute(array, itemSize) {
  29238. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29239. return new Int32BufferAttribute(array, itemSize);
  29240. }
  29241. function Uint32Attribute(array, itemSize) {
  29242. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29243. return new Uint32BufferAttribute(array, itemSize);
  29244. }
  29245. function Float32Attribute(array, itemSize) {
  29246. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29247. return new Float32BufferAttribute(array, itemSize);
  29248. }
  29249. function Float64Attribute(array, itemSize) {
  29250. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29251. return new Float64BufferAttribute(array, itemSize);
  29252. } //
  29253. Curve.create = function (construct, getPoint) {
  29254. console.log('THREE.Curve.create() has been deprecated');
  29255. construct.prototype = Object.create(Curve.prototype);
  29256. construct.prototype.constructor = construct;
  29257. construct.prototype.getPoint = getPoint;
  29258. return construct;
  29259. }; //
  29260. Object.assign(CurvePath.prototype, {
  29261. createPointsGeometry: function (divisions) {
  29262. 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)
  29263. var pts = this.getPoints(divisions);
  29264. return this.createGeometry(pts);
  29265. },
  29266. createSpacedPointsGeometry: function (divisions) {
  29267. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29268. var pts = this.getSpacedPoints(divisions);
  29269. return this.createGeometry(pts);
  29270. },
  29271. createGeometry: function (points) {
  29272. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29273. var geometry = new Geometry();
  29274. for (var i = 0, l = points.length; i < l; i++) {
  29275. var point = points[i];
  29276. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29277. }
  29278. return geometry;
  29279. }
  29280. }); //
  29281. Object.assign(Path.prototype, {
  29282. fromPoints: function (points) {
  29283. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29284. this.setFromPoints(points);
  29285. }
  29286. }); //
  29287. function ClosedSplineCurve3(points) {
  29288. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29289. CatmullRomCurve3.call(this, points);
  29290. this.type = 'catmullrom';
  29291. this.closed = true;
  29292. }
  29293. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29294. function SplineCurve3(points) {
  29295. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29296. CatmullRomCurve3.call(this, points);
  29297. this.type = 'catmullrom';
  29298. }
  29299. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29300. function Spline(points) {
  29301. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29302. CatmullRomCurve3.call(this, points);
  29303. this.type = 'catmullrom';
  29304. }
  29305. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29306. Object.assign(Spline.prototype, {
  29307. initFromArray: function ()
  29308. /* a */
  29309. {
  29310. console.error('THREE.Spline: .initFromArray() has been removed.');
  29311. },
  29312. getControlPointsArray: function ()
  29313. /* optionalTarget */
  29314. {
  29315. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29316. },
  29317. reparametrizeByArcLength: function ()
  29318. /* samplingCoef */
  29319. {
  29320. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29321. }
  29322. }); //
  29323. function AxisHelper(size) {
  29324. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29325. return new AxesHelper(size);
  29326. }
  29327. function BoundingBoxHelper(object, color) {
  29328. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29329. return new BoxHelper(object, color);
  29330. }
  29331. function EdgesHelper(object, hex) {
  29332. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29333. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29334. color: hex !== undefined ? hex : 0xffffff
  29335. }));
  29336. }
  29337. GridHelper.prototype.setColors = function () {
  29338. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29339. };
  29340. SkeletonHelper.prototype.update = function () {
  29341. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29342. };
  29343. function WireframeHelper(object, hex) {
  29344. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29345. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29346. color: hex !== undefined ? hex : 0xffffff
  29347. }));
  29348. } //
  29349. Object.assign(Loader.prototype, {
  29350. extractUrlBase: function (url) {
  29351. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29352. return LoaderUtils.extractUrlBase(url);
  29353. }
  29354. });
  29355. Loader.Handlers = {
  29356. add: function ()
  29357. /* regex, loader */
  29358. {
  29359. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29360. },
  29361. get: function ()
  29362. /* file */
  29363. {
  29364. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29365. }
  29366. };
  29367. function XHRLoader(manager) {
  29368. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29369. return new FileLoader(manager);
  29370. }
  29371. function BinaryTextureLoader(manager) {
  29372. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29373. return new DataTextureLoader(manager);
  29374. }
  29375. Object.assign(ObjectLoader.prototype, {
  29376. setTexturePath: function (value) {
  29377. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29378. return this.setResourcePath(value);
  29379. }
  29380. }); //
  29381. Object.assign(Box2.prototype, {
  29382. center: function (optionalTarget) {
  29383. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29384. return this.getCenter(optionalTarget);
  29385. },
  29386. empty: function () {
  29387. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29388. return this.isEmpty();
  29389. },
  29390. isIntersectionBox: function (box) {
  29391. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29392. return this.intersectsBox(box);
  29393. },
  29394. size: function (optionalTarget) {
  29395. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29396. return this.getSize(optionalTarget);
  29397. }
  29398. });
  29399. Object.assign(Box3.prototype, {
  29400. center: function (optionalTarget) {
  29401. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29402. return this.getCenter(optionalTarget);
  29403. },
  29404. empty: function () {
  29405. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29406. return this.isEmpty();
  29407. },
  29408. isIntersectionBox: function (box) {
  29409. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29410. return this.intersectsBox(box);
  29411. },
  29412. isIntersectionSphere: function (sphere) {
  29413. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29414. return this.intersectsSphere(sphere);
  29415. },
  29416. size: function (optionalTarget) {
  29417. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29418. return this.getSize(optionalTarget);
  29419. }
  29420. });
  29421. Line3.prototype.center = function (optionalTarget) {
  29422. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29423. return this.getCenter(optionalTarget);
  29424. };
  29425. Object.assign(_Math, {
  29426. random16: function () {
  29427. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29428. return Math.random();
  29429. },
  29430. nearestPowerOfTwo: function (value) {
  29431. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29432. return _Math.floorPowerOfTwo(value);
  29433. },
  29434. nextPowerOfTwo: function (value) {
  29435. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29436. return _Math.ceilPowerOfTwo(value);
  29437. }
  29438. });
  29439. Object.assign(Matrix3.prototype, {
  29440. flattenToArrayOffset: function (array, offset) {
  29441. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29442. return this.toArray(array, offset);
  29443. },
  29444. multiplyVector3: function (vector) {
  29445. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29446. return vector.applyMatrix3(this);
  29447. },
  29448. multiplyVector3Array: function ()
  29449. /* a */
  29450. {
  29451. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29452. },
  29453. applyToBuffer: function (buffer
  29454. /*, offset, length */
  29455. ) {
  29456. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29457. return this.applyToBufferAttribute(buffer);
  29458. },
  29459. applyToVector3Array: function ()
  29460. /* array, offset, length */
  29461. {
  29462. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29463. }
  29464. });
  29465. Object.assign(Matrix4.prototype, {
  29466. extractPosition: function (m) {
  29467. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29468. return this.copyPosition(m);
  29469. },
  29470. flattenToArrayOffset: function (array, offset) {
  29471. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29472. return this.toArray(array, offset);
  29473. },
  29474. getPosition: function () {
  29475. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29476. return new Vector3().setFromMatrixColumn(this, 3);
  29477. },
  29478. setRotationFromQuaternion: function (q) {
  29479. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29480. return this.makeRotationFromQuaternion(q);
  29481. },
  29482. multiplyToArray: function () {
  29483. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29484. },
  29485. multiplyVector3: function (vector) {
  29486. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29487. return vector.applyMatrix4(this);
  29488. },
  29489. multiplyVector4: function (vector) {
  29490. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29491. return vector.applyMatrix4(this);
  29492. },
  29493. multiplyVector3Array: function ()
  29494. /* a */
  29495. {
  29496. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29497. },
  29498. rotateAxis: function (v) {
  29499. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29500. v.transformDirection(this);
  29501. },
  29502. crossVector: function (vector) {
  29503. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29504. return vector.applyMatrix4(this);
  29505. },
  29506. translate: function () {
  29507. console.error('THREE.Matrix4: .translate() has been removed.');
  29508. },
  29509. rotateX: function () {
  29510. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29511. },
  29512. rotateY: function () {
  29513. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29514. },
  29515. rotateZ: function () {
  29516. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29517. },
  29518. rotateByAxis: function () {
  29519. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29520. },
  29521. applyToBuffer: function (buffer
  29522. /*, offset, length */
  29523. ) {
  29524. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29525. return this.applyToBufferAttribute(buffer);
  29526. },
  29527. applyToVector3Array: function ()
  29528. /* array, offset, length */
  29529. {
  29530. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29531. },
  29532. makeFrustum: function (left, right, bottom, top, near, far) {
  29533. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29534. return this.makePerspective(left, right, top, bottom, near, far);
  29535. }
  29536. });
  29537. Plane.prototype.isIntersectionLine = function (line) {
  29538. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29539. return this.intersectsLine(line);
  29540. };
  29541. Quaternion.prototype.multiplyVector3 = function (vector) {
  29542. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29543. return vector.applyQuaternion(this);
  29544. };
  29545. Object.assign(Ray.prototype, {
  29546. isIntersectionBox: function (box) {
  29547. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29548. return this.intersectsBox(box);
  29549. },
  29550. isIntersectionPlane: function (plane) {
  29551. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29552. return this.intersectsPlane(plane);
  29553. },
  29554. isIntersectionSphere: function (sphere) {
  29555. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29556. return this.intersectsSphere(sphere);
  29557. }
  29558. });
  29559. Object.assign(Triangle.prototype, {
  29560. area: function () {
  29561. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29562. return this.getArea();
  29563. },
  29564. barycoordFromPoint: function (point, target) {
  29565. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29566. return this.getBarycoord(point, target);
  29567. },
  29568. midpoint: function (target) {
  29569. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29570. return this.getMidpoint(target);
  29571. },
  29572. normal: function (target) {
  29573. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29574. return this.getNormal(target);
  29575. },
  29576. plane: function (target) {
  29577. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29578. return this.getPlane(target);
  29579. }
  29580. });
  29581. Object.assign(Triangle, {
  29582. barycoordFromPoint: function (point, a, b, c, target) {
  29583. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29584. return Triangle.getBarycoord(point, a, b, c, target);
  29585. },
  29586. normal: function (a, b, c, target) {
  29587. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29588. return Triangle.getNormal(a, b, c, target);
  29589. }
  29590. });
  29591. Object.assign(Shape.prototype, {
  29592. extractAllPoints: function (divisions) {
  29593. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29594. return this.extractPoints(divisions);
  29595. },
  29596. extrude: function (options) {
  29597. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29598. return new ExtrudeGeometry(this, options);
  29599. },
  29600. makeGeometry: function (options) {
  29601. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29602. return new ShapeGeometry(this, options);
  29603. }
  29604. });
  29605. Object.assign(Vector2.prototype, {
  29606. fromAttribute: function (attribute, index, offset) {
  29607. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29608. return this.fromBufferAttribute(attribute, index, offset);
  29609. },
  29610. distanceToManhattan: function (v) {
  29611. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29612. return this.manhattanDistanceTo(v);
  29613. },
  29614. lengthManhattan: function () {
  29615. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29616. return this.manhattanLength();
  29617. }
  29618. });
  29619. Object.assign(Vector3.prototype, {
  29620. setEulerFromRotationMatrix: function () {
  29621. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29622. },
  29623. setEulerFromQuaternion: function () {
  29624. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29625. },
  29626. getPositionFromMatrix: function (m) {
  29627. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29628. return this.setFromMatrixPosition(m);
  29629. },
  29630. getScaleFromMatrix: function (m) {
  29631. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29632. return this.setFromMatrixScale(m);
  29633. },
  29634. getColumnFromMatrix: function (index, matrix) {
  29635. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29636. return this.setFromMatrixColumn(matrix, index);
  29637. },
  29638. applyProjection: function (m) {
  29639. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29640. return this.applyMatrix4(m);
  29641. },
  29642. fromAttribute: function (attribute, index, offset) {
  29643. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29644. return this.fromBufferAttribute(attribute, index, offset);
  29645. },
  29646. distanceToManhattan: function (v) {
  29647. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29648. return this.manhattanDistanceTo(v);
  29649. },
  29650. lengthManhattan: function () {
  29651. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29652. return this.manhattanLength();
  29653. }
  29654. });
  29655. Object.assign(Vector4.prototype, {
  29656. fromAttribute: function (attribute, index, offset) {
  29657. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29658. return this.fromBufferAttribute(attribute, index, offset);
  29659. },
  29660. lengthManhattan: function () {
  29661. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29662. return this.manhattanLength();
  29663. }
  29664. }); //
  29665. Object.assign(Geometry.prototype, {
  29666. computeTangents: function () {
  29667. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29668. },
  29669. computeLineDistances: function () {
  29670. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29671. }
  29672. });
  29673. Object.assign(Object3D.prototype, {
  29674. getChildByName: function (name) {
  29675. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29676. return this.getObjectByName(name);
  29677. },
  29678. renderDepth: function () {
  29679. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29680. },
  29681. translate: function (distance, axis) {
  29682. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29683. return this.translateOnAxis(axis, distance);
  29684. },
  29685. getWorldRotation: function () {
  29686. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29687. }
  29688. });
  29689. Object.defineProperties(Object3D.prototype, {
  29690. eulerOrder: {
  29691. get: function () {
  29692. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29693. return this.rotation.order;
  29694. },
  29695. set: function (value) {
  29696. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29697. this.rotation.order = value;
  29698. }
  29699. },
  29700. useQuaternion: {
  29701. get: function () {
  29702. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29703. },
  29704. set: function () {
  29705. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29706. }
  29707. }
  29708. });
  29709. Object.defineProperties(LOD.prototype, {
  29710. objects: {
  29711. get: function () {
  29712. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29713. return this.levels;
  29714. }
  29715. }
  29716. });
  29717. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29718. get: function () {
  29719. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29720. },
  29721. set: function () {
  29722. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29723. }
  29724. });
  29725. SkinnedMesh.prototype.initBones = function () {
  29726. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29727. };
  29728. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29729. get: function () {
  29730. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29731. return this.arcLengthDivisions;
  29732. },
  29733. set: function (value) {
  29734. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29735. this.arcLengthDivisions = value;
  29736. }
  29737. }); //
  29738. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29739. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29740. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29741. this.setFocalLength(focalLength);
  29742. }; //
  29743. Object.defineProperties(Light.prototype, {
  29744. onlyShadow: {
  29745. set: function () {
  29746. console.warn('THREE.Light: .onlyShadow has been removed.');
  29747. }
  29748. },
  29749. shadowCameraFov: {
  29750. set: function (value) {
  29751. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29752. this.shadow.camera.fov = value;
  29753. }
  29754. },
  29755. shadowCameraLeft: {
  29756. set: function (value) {
  29757. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29758. this.shadow.camera.left = value;
  29759. }
  29760. },
  29761. shadowCameraRight: {
  29762. set: function (value) {
  29763. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29764. this.shadow.camera.right = value;
  29765. }
  29766. },
  29767. shadowCameraTop: {
  29768. set: function (value) {
  29769. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29770. this.shadow.camera.top = value;
  29771. }
  29772. },
  29773. shadowCameraBottom: {
  29774. set: function (value) {
  29775. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29776. this.shadow.camera.bottom = value;
  29777. }
  29778. },
  29779. shadowCameraNear: {
  29780. set: function (value) {
  29781. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29782. this.shadow.camera.near = value;
  29783. }
  29784. },
  29785. shadowCameraFar: {
  29786. set: function (value) {
  29787. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29788. this.shadow.camera.far = value;
  29789. }
  29790. },
  29791. shadowCameraVisible: {
  29792. set: function () {
  29793. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29794. }
  29795. },
  29796. shadowBias: {
  29797. set: function (value) {
  29798. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29799. this.shadow.bias = value;
  29800. }
  29801. },
  29802. shadowDarkness: {
  29803. set: function () {
  29804. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29805. }
  29806. },
  29807. shadowMapWidth: {
  29808. set: function (value) {
  29809. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29810. this.shadow.mapSize.width = value;
  29811. }
  29812. },
  29813. shadowMapHeight: {
  29814. set: function (value) {
  29815. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29816. this.shadow.mapSize.height = value;
  29817. }
  29818. }
  29819. }); //
  29820. Object.defineProperties(BufferAttribute.prototype, {
  29821. length: {
  29822. get: function () {
  29823. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29824. return this.array.length;
  29825. }
  29826. }
  29827. });
  29828. Object.assign(BufferAttribute.prototype, {
  29829. copyIndicesArray: function ()
  29830. /* indices */
  29831. {
  29832. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29833. },
  29834. setArray: function (array) {
  29835. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29836. this.count = array !== undefined ? array.length / this.itemSize : 0;
  29837. this.array = array;
  29838. return this;
  29839. }
  29840. });
  29841. Object.assign(BufferGeometry.prototype, {
  29842. addIndex: function (index) {
  29843. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29844. this.setIndex(index);
  29845. },
  29846. addDrawCall: function (start, count, indexOffset) {
  29847. if (indexOffset !== undefined) {
  29848. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29849. }
  29850. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29851. this.addGroup(start, count);
  29852. },
  29853. clearDrawCalls: function () {
  29854. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29855. this.clearGroups();
  29856. },
  29857. computeTangents: function () {
  29858. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29859. },
  29860. computeOffsets: function () {
  29861. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29862. }
  29863. });
  29864. Object.defineProperties(BufferGeometry.prototype, {
  29865. drawcalls: {
  29866. get: function () {
  29867. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29868. return this.groups;
  29869. }
  29870. },
  29871. offsets: {
  29872. get: function () {
  29873. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29874. return this.groups;
  29875. }
  29876. }
  29877. });
  29878. Object.assign(InterleavedBuffer.prototype, {
  29879. setArray: function (array) {
  29880. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29881. this.count = array !== undefined ? array.length / this.stride : 0;
  29882. this.array = array;
  29883. return this;
  29884. }
  29885. }); //
  29886. Object.assign(ExtrudeBufferGeometry.prototype, {
  29887. getArrays: function () {
  29888. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29889. },
  29890. addShapeList: function () {
  29891. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29892. },
  29893. addShape: function () {
  29894. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29895. }
  29896. }); //
  29897. Object.defineProperties(Uniform.prototype, {
  29898. dynamic: {
  29899. set: function () {
  29900. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29901. }
  29902. },
  29903. onUpdate: {
  29904. value: function () {
  29905. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29906. return this;
  29907. }
  29908. }
  29909. }); //
  29910. Object.defineProperties(Material.prototype, {
  29911. wrapAround: {
  29912. get: function () {
  29913. console.warn('THREE.Material: .wrapAround has been removed.');
  29914. },
  29915. set: function () {
  29916. console.warn('THREE.Material: .wrapAround has been removed.');
  29917. }
  29918. },
  29919. overdraw: {
  29920. get: function () {
  29921. console.warn('THREE.Material: .overdraw has been removed.');
  29922. },
  29923. set: function () {
  29924. console.warn('THREE.Material: .overdraw has been removed.');
  29925. }
  29926. },
  29927. wrapRGB: {
  29928. get: function () {
  29929. console.warn('THREE.Material: .wrapRGB has been removed.');
  29930. return new Color();
  29931. }
  29932. },
  29933. shading: {
  29934. get: function () {
  29935. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29936. },
  29937. set: function (value) {
  29938. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29939. this.flatShading = value === FlatShading;
  29940. }
  29941. },
  29942. stencilMask: {
  29943. get: function () {
  29944. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29945. return this.stencilFuncMask;
  29946. },
  29947. set: function (value) {
  29948. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29949. this.stencilFuncMask = value;
  29950. }
  29951. }
  29952. });
  29953. Object.defineProperties(MeshPhongMaterial.prototype, {
  29954. metal: {
  29955. get: function () {
  29956. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29957. return false;
  29958. },
  29959. set: function () {
  29960. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29961. }
  29962. }
  29963. });
  29964. Object.defineProperties(ShaderMaterial.prototype, {
  29965. derivatives: {
  29966. get: function () {
  29967. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29968. return this.extensions.derivatives;
  29969. },
  29970. set: function (value) {
  29971. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29972. this.extensions.derivatives = value;
  29973. }
  29974. }
  29975. }); //
  29976. Object.assign(WebGLRenderer.prototype, {
  29977. clearTarget: function (renderTarget, color, depth, stencil) {
  29978. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29979. this.setRenderTarget(renderTarget);
  29980. this.clear(color, depth, stencil);
  29981. },
  29982. animate: function (callback) {
  29983. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29984. this.setAnimationLoop(callback);
  29985. },
  29986. getCurrentRenderTarget: function () {
  29987. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29988. return this.getRenderTarget();
  29989. },
  29990. getMaxAnisotropy: function () {
  29991. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29992. return this.capabilities.getMaxAnisotropy();
  29993. },
  29994. getPrecision: function () {
  29995. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29996. return this.capabilities.precision;
  29997. },
  29998. resetGLState: function () {
  29999. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  30000. return this.state.reset();
  30001. },
  30002. supportsFloatTextures: function () {
  30003. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30004. return this.extensions.get('OES_texture_float');
  30005. },
  30006. supportsHalfFloatTextures: function () {
  30007. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30008. return this.extensions.get('OES_texture_half_float');
  30009. },
  30010. supportsStandardDerivatives: function () {
  30011. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30012. return this.extensions.get('OES_standard_derivatives');
  30013. },
  30014. supportsCompressedTextureS3TC: function () {
  30015. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30016. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30017. },
  30018. supportsCompressedTexturePVRTC: function () {
  30019. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30020. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30021. },
  30022. supportsBlendMinMax: function () {
  30023. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30024. return this.extensions.get('EXT_blend_minmax');
  30025. },
  30026. supportsVertexTextures: function () {
  30027. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30028. return this.capabilities.vertexTextures;
  30029. },
  30030. supportsInstancedArrays: function () {
  30031. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30032. return this.extensions.get('ANGLE_instanced_arrays');
  30033. },
  30034. enableScissorTest: function (boolean) {
  30035. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30036. this.setScissorTest(boolean);
  30037. },
  30038. initMaterial: function () {
  30039. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30040. },
  30041. addPrePlugin: function () {
  30042. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30043. },
  30044. addPostPlugin: function () {
  30045. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30046. },
  30047. updateShadowMap: function () {
  30048. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30049. },
  30050. setFaceCulling: function () {
  30051. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30052. },
  30053. allocTextureUnit: function () {
  30054. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30055. },
  30056. setTexture: function () {
  30057. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30058. },
  30059. setTexture2D: function () {
  30060. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30061. },
  30062. setTextureCube: function () {
  30063. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30064. },
  30065. getActiveMipMapLevel: function () {
  30066. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30067. return this.getActiveMipmapLevel();
  30068. }
  30069. });
  30070. Object.defineProperties(WebGLRenderer.prototype, {
  30071. shadowMapEnabled: {
  30072. get: function () {
  30073. return this.shadowMap.enabled;
  30074. },
  30075. set: function (value) {
  30076. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30077. this.shadowMap.enabled = value;
  30078. }
  30079. },
  30080. shadowMapType: {
  30081. get: function () {
  30082. return this.shadowMap.type;
  30083. },
  30084. set: function (value) {
  30085. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30086. this.shadowMap.type = value;
  30087. }
  30088. },
  30089. shadowMapCullFace: {
  30090. get: function () {
  30091. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30092. return undefined;
  30093. },
  30094. set: function ()
  30095. /* value */
  30096. {
  30097. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30098. }
  30099. },
  30100. context: {
  30101. get: function () {
  30102. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30103. return this.getContext();
  30104. }
  30105. }
  30106. });
  30107. Object.defineProperties(WebGLShadowMap.prototype, {
  30108. cullFace: {
  30109. get: function () {
  30110. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30111. return undefined;
  30112. },
  30113. set: function ()
  30114. /* cullFace */
  30115. {
  30116. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30117. }
  30118. },
  30119. renderReverseSided: {
  30120. get: function () {
  30121. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30122. return undefined;
  30123. },
  30124. set: function () {
  30125. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30126. }
  30127. },
  30128. renderSingleSided: {
  30129. get: function () {
  30130. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30131. return undefined;
  30132. },
  30133. set: function () {
  30134. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30135. }
  30136. }
  30137. }); //
  30138. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  30139. activeCubeFace: {
  30140. set: function ()
  30141. /* value */
  30142. {
  30143. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  30144. }
  30145. },
  30146. activeMipMapLevel: {
  30147. set: function ()
  30148. /* value */
  30149. {
  30150. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  30151. }
  30152. }
  30153. }); //
  30154. Object.defineProperties(WebGLRenderTarget.prototype, {
  30155. wrapS: {
  30156. get: function () {
  30157. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30158. return this.texture.wrapS;
  30159. },
  30160. set: function (value) {
  30161. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30162. this.texture.wrapS = value;
  30163. }
  30164. },
  30165. wrapT: {
  30166. get: function () {
  30167. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30168. return this.texture.wrapT;
  30169. },
  30170. set: function (value) {
  30171. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30172. this.texture.wrapT = value;
  30173. }
  30174. },
  30175. magFilter: {
  30176. get: function () {
  30177. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30178. return this.texture.magFilter;
  30179. },
  30180. set: function (value) {
  30181. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30182. this.texture.magFilter = value;
  30183. }
  30184. },
  30185. minFilter: {
  30186. get: function () {
  30187. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30188. return this.texture.minFilter;
  30189. },
  30190. set: function (value) {
  30191. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30192. this.texture.minFilter = value;
  30193. }
  30194. },
  30195. anisotropy: {
  30196. get: function () {
  30197. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30198. return this.texture.anisotropy;
  30199. },
  30200. set: function (value) {
  30201. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30202. this.texture.anisotropy = value;
  30203. }
  30204. },
  30205. offset: {
  30206. get: function () {
  30207. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30208. return this.texture.offset;
  30209. },
  30210. set: function (value) {
  30211. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30212. this.texture.offset = value;
  30213. }
  30214. },
  30215. repeat: {
  30216. get: function () {
  30217. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30218. return this.texture.repeat;
  30219. },
  30220. set: function (value) {
  30221. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30222. this.texture.repeat = value;
  30223. }
  30224. },
  30225. format: {
  30226. get: function () {
  30227. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30228. return this.texture.format;
  30229. },
  30230. set: function (value) {
  30231. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30232. this.texture.format = value;
  30233. }
  30234. },
  30235. type: {
  30236. get: function () {
  30237. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30238. return this.texture.type;
  30239. },
  30240. set: function (value) {
  30241. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30242. this.texture.type = value;
  30243. }
  30244. },
  30245. generateMipmaps: {
  30246. get: function () {
  30247. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30248. return this.texture.generateMipmaps;
  30249. },
  30250. set: function (value) {
  30251. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30252. this.texture.generateMipmaps = value;
  30253. }
  30254. }
  30255. }); //
  30256. Object.defineProperties(WebVRManager.prototype, {
  30257. standing: {
  30258. set: function ()
  30259. /* value */
  30260. {
  30261. console.warn('THREE.WebVRManager: .standing has been removed.');
  30262. }
  30263. },
  30264. userHeight: {
  30265. set: function ()
  30266. /* value */
  30267. {
  30268. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  30269. }
  30270. }
  30271. }); //
  30272. Audio.prototype.load = function (file) {
  30273. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30274. var scope = this;
  30275. var audioLoader = new AudioLoader();
  30276. audioLoader.load(file, function (buffer) {
  30277. scope.setBuffer(buffer);
  30278. });
  30279. return this;
  30280. };
  30281. AudioAnalyser.prototype.getData = function () {
  30282. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30283. return this.getFrequencyData();
  30284. }; //
  30285. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30286. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30287. return this.update(renderer, scene);
  30288. }; //
  30289. var GeometryUtils = {
  30290. merge: function (geometry1, geometry2, materialIndexOffset) {
  30291. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30292. var matrix;
  30293. if (geometry2.isMesh) {
  30294. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30295. matrix = geometry2.matrix;
  30296. geometry2 = geometry2.geometry;
  30297. }
  30298. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30299. },
  30300. center: function (geometry) {
  30301. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30302. return geometry.center();
  30303. }
  30304. };
  30305. exports.GeometryUtils = GeometryUtils;
  30306. ImageUtils.crossOrigin = undefined;
  30307. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30308. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30309. var loader = new TextureLoader();
  30310. loader.setCrossOrigin(this.crossOrigin);
  30311. var texture = loader.load(url, onLoad, undefined, onError);
  30312. if (mapping) texture.mapping = mapping;
  30313. return texture;
  30314. };
  30315. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30316. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30317. var loader = new CubeTextureLoader();
  30318. loader.setCrossOrigin(this.crossOrigin);
  30319. var texture = loader.load(urls, onLoad, undefined, onError);
  30320. if (mapping) texture.mapping = mapping;
  30321. return texture;
  30322. };
  30323. ImageUtils.loadCompressedTexture = function () {
  30324. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30325. };
  30326. ImageUtils.loadCompressedTextureCube = function () {
  30327. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30328. }; //
  30329. function CanvasRenderer() {
  30330. console.error('THREE.CanvasRenderer has been removed');
  30331. } //
  30332. function JSONLoader() {
  30333. console.error('THREE.JSONLoader has been removed.');
  30334. } //
  30335. var SceneUtils = {
  30336. createMultiMaterialObject: function ()
  30337. /* geometry, materials */
  30338. {
  30339. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30340. },
  30341. detach: function ()
  30342. /* child, parent, scene */
  30343. {
  30344. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30345. },
  30346. attach: function ()
  30347. /* child, scene, parent */
  30348. {
  30349. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30350. }
  30351. }; //
  30352. exports.SceneUtils = SceneUtils;
  30353. function LensFlare() {
  30354. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  30355. }
  30356. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30357. /* eslint-disable no-undef */
  30358. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30359. detail: {
  30360. revision: REVISION
  30361. }
  30362. }));
  30363. /* eslint-enable no-undef */
  30364. }
  30365. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30366. "use strict";
  30367. Object.defineProperty(exports, "__esModule", {
  30368. value: true
  30369. });
  30370. exports.GLTFLoader = void 0;
  30371. var _threeModule = require("../../../build/three.module.js");
  30372. /**
  30373. * @author Rich Tibbett / https://github.com/richtr
  30374. * @author mrdoob / http://mrdoob.com/
  30375. * @author Tony Parisi / http://www.tonyparisi.com/
  30376. * @author Takahiro / https://github.com/takahirox
  30377. * @author Don McCurdy / https://www.donmccurdy.com
  30378. */
  30379. var GLTFLoader = function () {
  30380. function GLTFLoader(manager) {
  30381. _threeModule.Loader.call(this, manager);
  30382. this.dracoLoader = null;
  30383. this.ddsLoader = null;
  30384. }
  30385. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30386. constructor: GLTFLoader,
  30387. load: function (url, onLoad, onProgress, onError) {
  30388. var scope = this;
  30389. var resourcePath;
  30390. if (this.resourcePath !== '') {
  30391. resourcePath = this.resourcePath;
  30392. } else if (this.path !== '') {
  30393. resourcePath = this.path;
  30394. } else {
  30395. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30396. } // Tells the LoadingManager to track an extra item, which resolves after
  30397. // the model is fully loaded. This means the count of items loaded will
  30398. // be incorrect, but ensures manager.onLoad() does not fire early.
  30399. scope.manager.itemStart(url);
  30400. var _onError = function (e) {
  30401. if (onError) {
  30402. onError(e);
  30403. } else {
  30404. console.error(e);
  30405. }
  30406. scope.manager.itemError(url);
  30407. scope.manager.itemEnd(url);
  30408. };
  30409. var loader = new _threeModule.FileLoader(scope.manager);
  30410. loader.setPath(this.path);
  30411. loader.setResponseType('arraybuffer');
  30412. if (scope.crossOrigin === 'use-credentials') {
  30413. loader.setWithCredentials(true);
  30414. }
  30415. loader.load(url, function (data) {
  30416. try {
  30417. scope.parse(data, resourcePath, function (gltf) {
  30418. onLoad(gltf);
  30419. scope.manager.itemEnd(url);
  30420. }, _onError);
  30421. } catch (e) {
  30422. _onError(e);
  30423. }
  30424. }, onProgress, _onError);
  30425. },
  30426. setDRACOLoader: function (dracoLoader) {
  30427. this.dracoLoader = dracoLoader;
  30428. return this;
  30429. },
  30430. setDDSLoader: function (ddsLoader) {
  30431. this.ddsLoader = ddsLoader;
  30432. return this;
  30433. },
  30434. parse: function (data, path, onLoad, onError) {
  30435. var content;
  30436. var extensions = {};
  30437. if (typeof data === 'string') {
  30438. content = data;
  30439. } else {
  30440. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30441. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30442. try {
  30443. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30444. } catch (error) {
  30445. if (onError) onError(error);
  30446. return;
  30447. }
  30448. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30449. } else {
  30450. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30451. }
  30452. }
  30453. var json = JSON.parse(content);
  30454. if (json.asset === undefined || json.asset.version[0] < 2) {
  30455. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30456. return;
  30457. }
  30458. if (json.extensionsUsed) {
  30459. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30460. var extensionName = json.extensionsUsed[i];
  30461. var extensionsRequired = json.extensionsRequired || [];
  30462. switch (extensionName) {
  30463. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30464. extensions[extensionName] = new GLTFLightsExtension(json);
  30465. break;
  30466. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30467. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30468. break;
  30469. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30470. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30471. break;
  30472. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30473. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30474. break;
  30475. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30476. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30477. break;
  30478. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30479. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30480. break;
  30481. default:
  30482. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30483. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30484. }
  30485. }
  30486. }
  30487. }
  30488. var parser = new GLTFParser(json, extensions, {
  30489. path: path || this.resourcePath || '',
  30490. crossOrigin: this.crossOrigin,
  30491. manager: this.manager
  30492. });
  30493. parser.parse(onLoad, onError);
  30494. }
  30495. });
  30496. /* GLTFREGISTRY */
  30497. function GLTFRegistry() {
  30498. var objects = {};
  30499. return {
  30500. get: function (key) {
  30501. return objects[key];
  30502. },
  30503. add: function (key, object) {
  30504. objects[key] = object;
  30505. },
  30506. remove: function (key) {
  30507. delete objects[key];
  30508. },
  30509. removeAll: function () {
  30510. objects = {};
  30511. }
  30512. };
  30513. }
  30514. /*********************************/
  30515. /********** EXTENSIONS ***********/
  30516. /*********************************/
  30517. var EXTENSIONS = {
  30518. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30519. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30520. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30521. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30522. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30523. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30524. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30525. };
  30526. /**
  30527. * DDS Texture Extension
  30528. *
  30529. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30530. *
  30531. */
  30532. function GLTFTextureDDSExtension(ddsLoader) {
  30533. if (!ddsLoader) {
  30534. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30535. }
  30536. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30537. this.ddsLoader = ddsLoader;
  30538. }
  30539. /**
  30540. * Punctual Lights Extension
  30541. *
  30542. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30543. */
  30544. function GLTFLightsExtension(json) {
  30545. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30546. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30547. this.lightDefs = extension.lights || [];
  30548. }
  30549. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30550. var lightDef = this.lightDefs[lightIndex];
  30551. var lightNode;
  30552. var color = new _threeModule.Color(0xffffff);
  30553. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30554. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30555. switch (lightDef.type) {
  30556. case 'directional':
  30557. lightNode = new _threeModule.DirectionalLight(color);
  30558. lightNode.target.position.set(0, 0, -1);
  30559. lightNode.add(lightNode.target);
  30560. break;
  30561. case 'point':
  30562. lightNode = new _threeModule.PointLight(color);
  30563. lightNode.distance = range;
  30564. break;
  30565. case 'spot':
  30566. lightNode = new _threeModule.SpotLight(color);
  30567. lightNode.distance = range; // Handle spotlight properties.
  30568. lightDef.spot = lightDef.spot || {};
  30569. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30570. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30571. lightNode.angle = lightDef.spot.outerConeAngle;
  30572. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30573. lightNode.target.position.set(0, 0, -1);
  30574. lightNode.add(lightNode.target);
  30575. break;
  30576. default:
  30577. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30578. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30579. // here, because node-level parsing will only override position if explicitly specified.
  30580. lightNode.position.set(0, 0, 0);
  30581. lightNode.decay = 2;
  30582. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30583. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30584. return Promise.resolve(lightNode);
  30585. };
  30586. /**
  30587. * Unlit Materials Extension
  30588. *
  30589. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30590. */
  30591. function GLTFMaterialsUnlitExtension() {
  30592. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30593. }
  30594. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30595. return _threeModule.MeshBasicMaterial;
  30596. };
  30597. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30598. var pending = [];
  30599. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30600. materialParams.opacity = 1.0;
  30601. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30602. if (metallicRoughness) {
  30603. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30604. var array = metallicRoughness.baseColorFactor;
  30605. materialParams.color.fromArray(array);
  30606. materialParams.opacity = array[3];
  30607. }
  30608. if (metallicRoughness.baseColorTexture !== undefined) {
  30609. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30610. }
  30611. }
  30612. return Promise.all(pending);
  30613. };
  30614. /* BINARY EXTENSION */
  30615. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30616. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30617. var BINARY_EXTENSION_CHUNK_TYPES = {
  30618. JSON: 0x4E4F534A,
  30619. BIN: 0x004E4942
  30620. };
  30621. function GLTFBinaryExtension(data) {
  30622. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30623. this.content = null;
  30624. this.body = null;
  30625. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30626. this.header = {
  30627. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30628. version: headerView.getUint32(4, true),
  30629. length: headerView.getUint32(8, true)
  30630. };
  30631. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30632. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30633. } else if (this.header.version < 2.0) {
  30634. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30635. }
  30636. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30637. var chunkIndex = 0;
  30638. while (chunkIndex < chunkView.byteLength) {
  30639. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30640. chunkIndex += 4;
  30641. var chunkType = chunkView.getUint32(chunkIndex, true);
  30642. chunkIndex += 4;
  30643. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30644. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30645. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30646. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30647. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30648. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30649. } // Clients must ignore chunks with unknown types.
  30650. chunkIndex += chunkLength;
  30651. }
  30652. if (this.content === null) {
  30653. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30654. }
  30655. }
  30656. /**
  30657. * DRACO Mesh Compression Extension
  30658. *
  30659. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30660. */
  30661. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30662. if (!dracoLoader) {
  30663. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30664. }
  30665. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30666. this.json = json;
  30667. this.dracoLoader = dracoLoader;
  30668. }
  30669. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30670. var json = this.json;
  30671. var dracoLoader = this.dracoLoader;
  30672. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30673. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30674. var threeAttributeMap = {};
  30675. var attributeNormalizedMap = {};
  30676. var attributeTypeMap = {};
  30677. for (var attributeName in gltfAttributeMap) {
  30678. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30679. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30680. }
  30681. for (attributeName in primitive.attributes) {
  30682. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30683. if (gltfAttributeMap[attributeName] !== undefined) {
  30684. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30685. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30686. attributeTypeMap[threeAttributeName] = componentType;
  30687. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30688. }
  30689. }
  30690. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30691. return new Promise(function (resolve) {
  30692. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30693. for (var attributeName in geometry.attributes) {
  30694. var attribute = geometry.attributes[attributeName];
  30695. var normalized = attributeNormalizedMap[attributeName];
  30696. if (normalized !== undefined) attribute.normalized = normalized;
  30697. }
  30698. resolve(geometry);
  30699. }, threeAttributeMap, attributeTypeMap);
  30700. });
  30701. });
  30702. };
  30703. /**
  30704. * Texture Transform Extension
  30705. *
  30706. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30707. */
  30708. function GLTFTextureTransformExtension() {
  30709. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30710. }
  30711. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30712. texture = texture.clone();
  30713. if (transform.offset !== undefined) {
  30714. texture.offset.fromArray(transform.offset);
  30715. }
  30716. if (transform.rotation !== undefined) {
  30717. texture.rotation = transform.rotation;
  30718. }
  30719. if (transform.scale !== undefined) {
  30720. texture.repeat.fromArray(transform.scale);
  30721. }
  30722. if (transform.texCoord !== undefined) {
  30723. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30724. }
  30725. texture.needsUpdate = true;
  30726. return texture;
  30727. };
  30728. /**
  30729. * Specular-Glossiness Extension
  30730. *
  30731. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30732. */
  30733. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30734. return {
  30735. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30736. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30737. getMaterialType: function () {
  30738. return _threeModule.ShaderMaterial;
  30739. },
  30740. extendParams: function (materialParams, materialDef, parser) {
  30741. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30742. var shader = _threeModule.ShaderLib['standard'];
  30743. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30744. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30745. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30746. 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');
  30747. 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');
  30748. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30749. var fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  30750. delete uniforms.roughness;
  30751. delete uniforms.metalness;
  30752. delete uniforms.roughnessMap;
  30753. delete uniforms.metalnessMap;
  30754. uniforms.specular = {
  30755. value: new _threeModule.Color().setHex(0x111111)
  30756. };
  30757. uniforms.glossiness = {
  30758. value: 0.5
  30759. };
  30760. uniforms.specularMap = {
  30761. value: null
  30762. };
  30763. uniforms.glossinessMap = {
  30764. value: null
  30765. };
  30766. materialParams.vertexShader = shader.vertexShader;
  30767. materialParams.fragmentShader = fragmentShader;
  30768. materialParams.uniforms = uniforms;
  30769. materialParams.defines = {
  30770. 'STANDARD': ''
  30771. };
  30772. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30773. materialParams.opacity = 1.0;
  30774. var pending = [];
  30775. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30776. var array = pbrSpecularGlossiness.diffuseFactor;
  30777. materialParams.color.fromArray(array);
  30778. materialParams.opacity = array[3];
  30779. }
  30780. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30781. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30782. }
  30783. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30784. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30785. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30786. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30787. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30788. }
  30789. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30790. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30791. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30792. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30793. }
  30794. return Promise.all(pending);
  30795. },
  30796. createMaterial: function (params) {
  30797. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30798. var material = new _threeModule.ShaderMaterial({
  30799. defines: params.defines,
  30800. vertexShader: params.vertexShader,
  30801. fragmentShader: params.fragmentShader,
  30802. uniforms: params.uniforms,
  30803. fog: true,
  30804. lights: true,
  30805. opacity: params.opacity,
  30806. transparent: params.transparent
  30807. });
  30808. material.isGLTFSpecularGlossinessMaterial = true;
  30809. material.color = params.color;
  30810. material.map = params.map === undefined ? null : params.map;
  30811. material.lightMap = null;
  30812. material.lightMapIntensity = 1.0;
  30813. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30814. material.aoMapIntensity = 1.0;
  30815. material.emissive = params.emissive;
  30816. material.emissiveIntensity = 1.0;
  30817. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30818. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30819. material.bumpScale = 1;
  30820. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30821. if (params.normalScale) material.normalScale = params.normalScale;
  30822. material.displacementMap = null;
  30823. material.displacementScale = 1;
  30824. material.displacementBias = 0;
  30825. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30826. material.specular = params.specular;
  30827. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30828. material.glossiness = params.glossiness;
  30829. material.alphaMap = null;
  30830. material.envMap = params.envMap === undefined ? null : params.envMap;
  30831. material.envMapIntensity = 1.0;
  30832. material.refractionRatio = 0.98;
  30833. material.extensions.derivatives = true;
  30834. return material;
  30835. },
  30836. /**
  30837. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30838. * copy only properties it knows about or inherits, and misses many properties that would
  30839. * normally be defined by MeshStandardMaterial.
  30840. *
  30841. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30842. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30843. * AND also updating `.onBeforeRender` on the parent mesh.
  30844. *
  30845. * @param {ShaderMaterial} source
  30846. * @return {ShaderMaterial}
  30847. */
  30848. cloneMaterial: function (source) {
  30849. var target = source.clone();
  30850. target.isGLTFSpecularGlossinessMaterial = true;
  30851. var params = this.specularGlossinessParams;
  30852. for (var i = 0, il = params.length; i < il; i++) {
  30853. var value = source[params[i]];
  30854. target[params[i]] = value && value.isColor ? value.clone() : value;
  30855. }
  30856. return target;
  30857. },
  30858. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30859. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30860. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30861. return;
  30862. }
  30863. var uniforms = material.uniforms;
  30864. var defines = material.defines;
  30865. uniforms.opacity.value = material.opacity;
  30866. uniforms.diffuse.value.copy(material.color);
  30867. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30868. uniforms.map.value = material.map;
  30869. uniforms.specularMap.value = material.specularMap;
  30870. uniforms.alphaMap.value = material.alphaMap;
  30871. uniforms.lightMap.value = material.lightMap;
  30872. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30873. uniforms.aoMap.value = material.aoMap;
  30874. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30875. // 1. color map
  30876. // 2. specular map
  30877. // 3. normal map
  30878. // 4. bump map
  30879. // 5. alpha map
  30880. // 6. emissive map
  30881. var uvScaleMap;
  30882. if (material.map) {
  30883. uvScaleMap = material.map;
  30884. } else if (material.specularMap) {
  30885. uvScaleMap = material.specularMap;
  30886. } else if (material.displacementMap) {
  30887. uvScaleMap = material.displacementMap;
  30888. } else if (material.normalMap) {
  30889. uvScaleMap = material.normalMap;
  30890. } else if (material.bumpMap) {
  30891. uvScaleMap = material.bumpMap;
  30892. } else if (material.glossinessMap) {
  30893. uvScaleMap = material.glossinessMap;
  30894. } else if (material.alphaMap) {
  30895. uvScaleMap = material.alphaMap;
  30896. } else if (material.emissiveMap) {
  30897. uvScaleMap = material.emissiveMap;
  30898. }
  30899. if (uvScaleMap !== undefined) {
  30900. // backwards compatibility
  30901. if (uvScaleMap.isWebGLRenderTarget) {
  30902. uvScaleMap = uvScaleMap.texture;
  30903. }
  30904. if (uvScaleMap.matrixAutoUpdate === true) {
  30905. uvScaleMap.updateMatrix();
  30906. }
  30907. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30908. }
  30909. if (material.envMap) {
  30910. uniforms.envMap.value = material.envMap;
  30911. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30912. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30913. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30914. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30915. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30916. uniforms.reflectivity.value = material.reflectivity;
  30917. uniforms.refractionRatio.value = material.refractionRatio;
  30918. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30919. }
  30920. uniforms.specular.value.copy(material.specular);
  30921. uniforms.glossiness.value = material.glossiness;
  30922. uniforms.glossinessMap.value = material.glossinessMap;
  30923. uniforms.emissiveMap.value = material.emissiveMap;
  30924. uniforms.bumpMap.value = material.bumpMap;
  30925. uniforms.normalMap.value = material.normalMap;
  30926. uniforms.displacementMap.value = material.displacementMap;
  30927. uniforms.displacementScale.value = material.displacementScale;
  30928. uniforms.displacementBias.value = material.displacementBias;
  30929. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30930. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30931. defines.USE_ROUGHNESSMAP = '';
  30932. }
  30933. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30934. delete defines.USE_GLOSSINESSMAP;
  30935. delete defines.USE_ROUGHNESSMAP;
  30936. }
  30937. }
  30938. };
  30939. }
  30940. /*********************************/
  30941. /********** INTERPOLATION ********/
  30942. /*********************************/
  30943. // Spline Interpolation
  30944. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30945. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30946. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30947. }
  30948. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30949. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30950. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30951. // Copies a sample value to the result buffer. See description of glTF
  30952. // CUBICSPLINE values layout in interpolate_() function below.
  30953. var result = this.resultBuffer,
  30954. values = this.sampleValues,
  30955. valueSize = this.valueSize,
  30956. offset = index * valueSize * 3 + valueSize;
  30957. for (var i = 0; i !== valueSize; i++) {
  30958. result[i] = values[offset + i];
  30959. }
  30960. return result;
  30961. };
  30962. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30963. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30964. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30965. var result = this.resultBuffer;
  30966. var values = this.sampleValues;
  30967. var stride = this.valueSize;
  30968. var stride2 = stride * 2;
  30969. var stride3 = stride * 3;
  30970. var td = t1 - t0;
  30971. var p = (t - t0) / td;
  30972. var pp = p * p;
  30973. var ppp = pp * p;
  30974. var offset1 = i1 * stride3;
  30975. var offset0 = offset1 - stride3;
  30976. var s2 = -2 * ppp + 3 * pp;
  30977. var s3 = ppp - pp;
  30978. var s0 = 1 - s2;
  30979. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  30980. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  30981. for (var i = 0; i !== stride; i++) {
  30982. var p0 = values[offset0 + i + stride]; // splineVertex_k
  30983. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  30984. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  30985. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  30986. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  30987. }
  30988. return result;
  30989. };
  30990. /*********************************/
  30991. /********** INTERNALS ************/
  30992. /*********************************/
  30993. /* CONSTANTS */
  30994. var WEBGL_CONSTANTS = {
  30995. FLOAT: 5126,
  30996. //FLOAT_MAT2: 35674,
  30997. FLOAT_MAT3: 35675,
  30998. FLOAT_MAT4: 35676,
  30999. FLOAT_VEC2: 35664,
  31000. FLOAT_VEC3: 35665,
  31001. FLOAT_VEC4: 35666,
  31002. LINEAR: 9729,
  31003. REPEAT: 10497,
  31004. SAMPLER_2D: 35678,
  31005. POINTS: 0,
  31006. LINES: 1,
  31007. LINE_LOOP: 2,
  31008. LINE_STRIP: 3,
  31009. TRIANGLES: 4,
  31010. TRIANGLE_STRIP: 5,
  31011. TRIANGLE_FAN: 6,
  31012. UNSIGNED_BYTE: 5121,
  31013. UNSIGNED_SHORT: 5123
  31014. };
  31015. var WEBGL_COMPONENT_TYPES = {
  31016. 5120: Int8Array,
  31017. 5121: Uint8Array,
  31018. 5122: Int16Array,
  31019. 5123: Uint16Array,
  31020. 5125: Uint32Array,
  31021. 5126: Float32Array
  31022. };
  31023. var WEBGL_FILTERS = {
  31024. 9728: _threeModule.NearestFilter,
  31025. 9729: _threeModule.LinearFilter,
  31026. 9984: _threeModule.NearestMipmapNearestFilter,
  31027. 9985: _threeModule.LinearMipmapNearestFilter,
  31028. 9986: _threeModule.NearestMipmapLinearFilter,
  31029. 9987: _threeModule.LinearMipmapLinearFilter
  31030. };
  31031. var WEBGL_WRAPPINGS = {
  31032. 33071: _threeModule.ClampToEdgeWrapping,
  31033. 33648: _threeModule.MirroredRepeatWrapping,
  31034. 10497: _threeModule.RepeatWrapping
  31035. };
  31036. var WEBGL_TYPE_SIZES = {
  31037. 'SCALAR': 1,
  31038. 'VEC2': 2,
  31039. 'VEC3': 3,
  31040. 'VEC4': 4,
  31041. 'MAT2': 4,
  31042. 'MAT3': 9,
  31043. 'MAT4': 16
  31044. };
  31045. var ATTRIBUTES = {
  31046. POSITION: 'position',
  31047. NORMAL: 'normal',
  31048. TANGENT: 'tangent',
  31049. TEXCOORD_0: 'uv',
  31050. TEXCOORD_1: 'uv2',
  31051. COLOR_0: 'color',
  31052. WEIGHTS_0: 'skinWeight',
  31053. JOINTS_0: 'skinIndex'
  31054. };
  31055. var PATH_PROPERTIES = {
  31056. scale: 'scale',
  31057. translation: 'position',
  31058. rotation: 'quaternion',
  31059. weights: 'morphTargetInfluences'
  31060. };
  31061. var INTERPOLATION = {
  31062. CUBICSPLINE: undefined,
  31063. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31064. // keyframe track will be initialized with a default interpolation type, then modified.
  31065. LINEAR: _threeModule.InterpolateLinear,
  31066. STEP: _threeModule.InterpolateDiscrete
  31067. };
  31068. var ALPHA_MODES = {
  31069. OPAQUE: 'OPAQUE',
  31070. MASK: 'MASK',
  31071. BLEND: 'BLEND'
  31072. };
  31073. var MIME_TYPE_FORMATS = {
  31074. 'image/png': _threeModule.RGBAFormat,
  31075. 'image/jpeg': _threeModule.RGBFormat
  31076. };
  31077. /* UTILITY FUNCTIONS */
  31078. function resolveURL(url, path) {
  31079. // Invalid URL
  31080. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31081. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31082. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31083. } // Absolute URL http://,https://,//
  31084. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31085. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31086. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31087. return path + url;
  31088. }
  31089. var defaultMaterial;
  31090. /**
  31091. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31092. */
  31093. function createDefaultMaterial() {
  31094. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31095. color: 0xFFFFFF,
  31096. emissive: 0x000000,
  31097. metalness: 1,
  31098. roughness: 1,
  31099. transparent: false,
  31100. depthTest: true,
  31101. side: _threeModule.FrontSide
  31102. });
  31103. return defaultMaterial;
  31104. }
  31105. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31106. // Add unknown glTF extensions to an object's userData.
  31107. for (var name in objectDef.extensions) {
  31108. if (knownExtensions[name] === undefined) {
  31109. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31110. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31111. }
  31112. }
  31113. }
  31114. /**
  31115. * @param {Object3D|Material|BufferGeometry} object
  31116. * @param {GLTF.definition} gltfDef
  31117. */
  31118. function assignExtrasToUserData(object, gltfDef) {
  31119. if (gltfDef.extras !== undefined) {
  31120. if (typeof gltfDef.extras === 'object') {
  31121. Object.assign(object.userData, gltfDef.extras);
  31122. } else {
  31123. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31124. }
  31125. }
  31126. }
  31127. /**
  31128. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31129. *
  31130. * @param {BufferGeometry} geometry
  31131. * @param {Array<GLTF.Target>} targets
  31132. * @param {GLTFParser} parser
  31133. * @return {Promise<BufferGeometry>}
  31134. */
  31135. function addMorphTargets(geometry, targets, parser) {
  31136. var hasMorphPosition = false;
  31137. var hasMorphNormal = false;
  31138. for (var i = 0, il = targets.length; i < il; i++) {
  31139. var target = targets[i];
  31140. if (target.POSITION !== undefined) hasMorphPosition = true;
  31141. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31142. if (hasMorphPosition && hasMorphNormal) break;
  31143. }
  31144. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31145. var pendingPositionAccessors = [];
  31146. var pendingNormalAccessors = [];
  31147. for (var i = 0, il = targets.length; i < il; i++) {
  31148. var target = targets[i];
  31149. if (hasMorphPosition) {
  31150. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31151. pendingPositionAccessors.push(pendingAccessor);
  31152. }
  31153. if (hasMorphNormal) {
  31154. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31155. pendingNormalAccessors.push(pendingAccessor);
  31156. }
  31157. }
  31158. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31159. var morphPositions = accessors[0];
  31160. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31161. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31162. if (geometry.attributes.position === morphPositions[i]) continue;
  31163. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31164. }
  31165. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31166. if (geometry.attributes.normal === morphNormals[i]) continue;
  31167. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31168. }
  31169. for (var i = 0, il = targets.length; i < il; i++) {
  31170. var target = targets[i];
  31171. var attributeName = 'morphTarget' + i;
  31172. if (hasMorphPosition) {
  31173. // Three.js morph position is absolute value. The formula is
  31174. // basePosition
  31175. // + weight0 * ( morphPosition0 - basePosition )
  31176. // + weight1 * ( morphPosition1 - basePosition )
  31177. // ...
  31178. // while the glTF one is relative
  31179. // basePosition
  31180. // + weight0 * glTFmorphPosition0
  31181. // + weight1 * glTFmorphPosition1
  31182. // ...
  31183. // then we need to convert from relative to absolute here.
  31184. if (target.POSITION !== undefined) {
  31185. var positionAttribute = morphPositions[i];
  31186. positionAttribute.name = attributeName;
  31187. var position = geometry.attributes.position;
  31188. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31189. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31190. }
  31191. }
  31192. }
  31193. if (hasMorphNormal) {
  31194. // see target.POSITION's comment
  31195. if (target.NORMAL !== undefined) {
  31196. var normalAttribute = morphNormals[i];
  31197. normalAttribute.name = attributeName;
  31198. var normal = geometry.attributes.normal;
  31199. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31200. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31201. }
  31202. }
  31203. }
  31204. }
  31205. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31206. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31207. return geometry;
  31208. });
  31209. }
  31210. /**
  31211. * @param {Mesh} mesh
  31212. * @param {GLTF.Mesh} meshDef
  31213. */
  31214. function updateMorphTargets(mesh, meshDef) {
  31215. mesh.updateMorphTargets();
  31216. if (meshDef.weights !== undefined) {
  31217. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31218. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31219. }
  31220. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31221. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31222. var targetNames = meshDef.extras.targetNames;
  31223. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31224. mesh.morphTargetDictionary = {};
  31225. for (var i = 0, il = targetNames.length; i < il; i++) {
  31226. mesh.morphTargetDictionary[targetNames[i]] = i;
  31227. }
  31228. } else {
  31229. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31230. }
  31231. }
  31232. }
  31233. function createPrimitiveKey(primitiveDef) {
  31234. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31235. var geometryKey;
  31236. if (dracoExtension) {
  31237. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31238. } else {
  31239. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31240. }
  31241. return geometryKey;
  31242. }
  31243. function createAttributesKey(attributes) {
  31244. var attributesKey = '';
  31245. var keys = Object.keys(attributes).sort();
  31246. for (var i = 0, il = keys.length; i < il; i++) {
  31247. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31248. }
  31249. return attributesKey;
  31250. }
  31251. function cloneBufferAttribute(attribute) {
  31252. if (attribute.isInterleavedBufferAttribute) {
  31253. var count = attribute.count;
  31254. var itemSize = attribute.itemSize;
  31255. var array = attribute.array.slice(0, count * itemSize);
  31256. for (var i = 0, j = 0; i < count; ++i) {
  31257. array[j++] = attribute.getX(i);
  31258. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31259. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31260. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31261. }
  31262. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31263. }
  31264. return attribute.clone();
  31265. }
  31266. /* GLTF PARSER */
  31267. function GLTFParser(json, extensions, options) {
  31268. this.json = json || {};
  31269. this.extensions = extensions || {};
  31270. this.options = options || {}; // loader object cache
  31271. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31272. this.primitiveCache = {};
  31273. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31274. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31275. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31276. this.fileLoader.setResponseType('arraybuffer');
  31277. if (this.options.crossOrigin === 'use-credentials') {
  31278. this.fileLoader.setWithCredentials(true);
  31279. }
  31280. }
  31281. GLTFParser.prototype.parse = function (onLoad, onError) {
  31282. var parser = this;
  31283. var json = this.json;
  31284. var extensions = this.extensions; // Clear the loader cache
  31285. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31286. this.markDefs();
  31287. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31288. var result = {
  31289. scene: dependencies[0][json.scene || 0],
  31290. scenes: dependencies[0],
  31291. animations: dependencies[1],
  31292. cameras: dependencies[2],
  31293. asset: json.asset,
  31294. parser: parser,
  31295. userData: {}
  31296. };
  31297. addUnknownExtensionsToUserData(extensions, result, json);
  31298. assignExtrasToUserData(result, json);
  31299. onLoad(result);
  31300. }).catch(onError);
  31301. };
  31302. /**
  31303. * Marks the special nodes/meshes in json for efficient parse.
  31304. */
  31305. GLTFParser.prototype.markDefs = function () {
  31306. var nodeDefs = this.json.nodes || [];
  31307. var skinDefs = this.json.skins || [];
  31308. var meshDefs = this.json.meshes || [];
  31309. var meshReferences = {};
  31310. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31311. // Object3D. Use the skins' joint references to mark bones.
  31312. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31313. var joints = skinDefs[skinIndex].joints;
  31314. for (var i = 0, il = joints.length; i < il; i++) {
  31315. nodeDefs[joints[i]].isBone = true;
  31316. }
  31317. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31318. // avoid having more than one Mesh with the same name, count
  31319. // references and rename instances below.
  31320. //
  31321. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31322. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31323. var nodeDef = nodeDefs[nodeIndex];
  31324. if (nodeDef.mesh !== undefined) {
  31325. if (meshReferences[nodeDef.mesh] === undefined) {
  31326. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31327. }
  31328. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31329. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31330. // to mark SkinnedMesh if node has skin.
  31331. if (nodeDef.skin !== undefined) {
  31332. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31333. }
  31334. }
  31335. }
  31336. this.json.meshReferences = meshReferences;
  31337. this.json.meshUses = meshUses;
  31338. };
  31339. /**
  31340. * Requests the specified dependency asynchronously, with caching.
  31341. * @param {string} type
  31342. * @param {number} index
  31343. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31344. */
  31345. GLTFParser.prototype.getDependency = function (type, index) {
  31346. var cacheKey = type + ':' + index;
  31347. var dependency = this.cache.get(cacheKey);
  31348. if (!dependency) {
  31349. switch (type) {
  31350. case 'scene':
  31351. dependency = this.loadScene(index);
  31352. break;
  31353. case 'node':
  31354. dependency = this.loadNode(index);
  31355. break;
  31356. case 'mesh':
  31357. dependency = this.loadMesh(index);
  31358. break;
  31359. case 'accessor':
  31360. dependency = this.loadAccessor(index);
  31361. break;
  31362. case 'bufferView':
  31363. dependency = this.loadBufferView(index);
  31364. break;
  31365. case 'buffer':
  31366. dependency = this.loadBuffer(index);
  31367. break;
  31368. case 'material':
  31369. dependency = this.loadMaterial(index);
  31370. break;
  31371. case 'texture':
  31372. dependency = this.loadTexture(index);
  31373. break;
  31374. case 'skin':
  31375. dependency = this.loadSkin(index);
  31376. break;
  31377. case 'animation':
  31378. dependency = this.loadAnimation(index);
  31379. break;
  31380. case 'camera':
  31381. dependency = this.loadCamera(index);
  31382. break;
  31383. case 'light':
  31384. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31385. break;
  31386. default:
  31387. throw new Error('Unknown type: ' + type);
  31388. }
  31389. this.cache.add(cacheKey, dependency);
  31390. }
  31391. return dependency;
  31392. };
  31393. /**
  31394. * Requests all dependencies of the specified type asynchronously, with caching.
  31395. * @param {string} type
  31396. * @return {Promise<Array<Object>>}
  31397. */
  31398. GLTFParser.prototype.getDependencies = function (type) {
  31399. var dependencies = this.cache.get(type);
  31400. if (!dependencies) {
  31401. var parser = this;
  31402. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31403. dependencies = Promise.all(defs.map(function (def, index) {
  31404. return parser.getDependency(type, index);
  31405. }));
  31406. this.cache.add(type, dependencies);
  31407. }
  31408. return dependencies;
  31409. };
  31410. /**
  31411. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31412. * @param {number} bufferIndex
  31413. * @return {Promise<ArrayBuffer>}
  31414. */
  31415. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31416. var bufferDef = this.json.buffers[bufferIndex];
  31417. var loader = this.fileLoader;
  31418. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31419. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31420. } // If present, GLB container is required to be the first buffer.
  31421. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31422. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31423. }
  31424. var options = this.options;
  31425. return new Promise(function (resolve, reject) {
  31426. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31427. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31428. });
  31429. });
  31430. };
  31431. /**
  31432. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31433. * @param {number} bufferViewIndex
  31434. * @return {Promise<ArrayBuffer>}
  31435. */
  31436. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31437. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31438. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31439. var byteLength = bufferViewDef.byteLength || 0;
  31440. var byteOffset = bufferViewDef.byteOffset || 0;
  31441. return buffer.slice(byteOffset, byteOffset + byteLength);
  31442. });
  31443. };
  31444. /**
  31445. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31446. * @param {number} accessorIndex
  31447. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31448. */
  31449. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31450. var parser = this;
  31451. var json = this.json;
  31452. var accessorDef = this.json.accessors[accessorIndex];
  31453. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31454. // Ignore empty accessors, which may be used to declare runtime
  31455. // information about attributes coming from another source (e.g. Draco
  31456. // compression extension).
  31457. return Promise.resolve(null);
  31458. }
  31459. var pendingBufferViews = [];
  31460. if (accessorDef.bufferView !== undefined) {
  31461. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31462. } else {
  31463. pendingBufferViews.push(null);
  31464. }
  31465. if (accessorDef.sparse !== undefined) {
  31466. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31467. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31468. }
  31469. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31470. var bufferView = bufferViews[0];
  31471. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31472. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31473. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31474. var itemBytes = elementBytes * itemSize;
  31475. var byteOffset = accessorDef.byteOffset || 0;
  31476. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31477. var normalized = accessorDef.normalized === true;
  31478. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31479. if (byteStride && byteStride !== itemBytes) {
  31480. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31481. // This makes sure that IBA.count reflects accessor.count properly
  31482. var ibSlice = Math.floor(byteOffset / byteStride);
  31483. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31484. var ib = parser.cache.get(ibCacheKey);
  31485. if (!ib) {
  31486. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31487. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31488. parser.cache.add(ibCacheKey, ib);
  31489. }
  31490. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31491. } else {
  31492. if (bufferView === null) {
  31493. array = new TypedArray(accessorDef.count * itemSize);
  31494. } else {
  31495. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31496. }
  31497. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31498. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31499. if (accessorDef.sparse !== undefined) {
  31500. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31501. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31502. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31503. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31504. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31505. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31506. if (bufferView !== null) {
  31507. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31508. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31509. }
  31510. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31511. var index = sparseIndices[i];
  31512. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31513. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31514. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31515. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31516. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31517. }
  31518. }
  31519. return bufferAttribute;
  31520. });
  31521. };
  31522. /**
  31523. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31524. * @param {number} textureIndex
  31525. * @return {Promise<THREE.Texture>}
  31526. */
  31527. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31528. var parser = this;
  31529. var json = this.json;
  31530. var options = this.options;
  31531. var textureLoader = this.textureLoader;
  31532. var URL = window.URL || window.webkitURL;
  31533. var textureDef = json.textures[textureIndex];
  31534. var textureExtensions = textureDef.extensions || {};
  31535. var source;
  31536. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31537. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31538. } else {
  31539. source = json.images[textureDef.source];
  31540. }
  31541. var sourceURI = source.uri;
  31542. var isObjectURL = false;
  31543. if (source.bufferView !== undefined) {
  31544. // Load binary image data from bufferView, if provided.
  31545. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31546. isObjectURL = true;
  31547. var blob = new Blob([bufferView], {
  31548. type: source.mimeType
  31549. });
  31550. sourceURI = URL.createObjectURL(blob);
  31551. return sourceURI;
  31552. });
  31553. }
  31554. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31555. // Load Texture resource.
  31556. var loader = options.manager.getHandler(sourceURI);
  31557. if (!loader) {
  31558. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31559. }
  31560. return new Promise(function (resolve, reject) {
  31561. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31562. });
  31563. }).then(function (texture) {
  31564. // Clean up resources and configure Texture.
  31565. if (isObjectURL === true) {
  31566. URL.revokeObjectURL(sourceURI);
  31567. }
  31568. texture.flipY = false;
  31569. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31570. if (source.mimeType in MIME_TYPE_FORMATS) {
  31571. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31572. }
  31573. var samplers = json.samplers || {};
  31574. var sampler = samplers[textureDef.sampler] || {};
  31575. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31576. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31577. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31578. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31579. return texture;
  31580. });
  31581. };
  31582. /**
  31583. * Asynchronously assigns a texture to the given material parameters.
  31584. * @param {Object} materialParams
  31585. * @param {string} mapName
  31586. * @param {Object} mapDef
  31587. * @return {Promise}
  31588. */
  31589. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31590. var parser = this;
  31591. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31592. if (!texture.isCompressedTexture) {
  31593. switch (mapName) {
  31594. case 'aoMap':
  31595. case 'emissiveMap':
  31596. case 'metalnessMap':
  31597. case 'normalMap':
  31598. case 'roughnessMap':
  31599. texture.format = _threeModule.RGBFormat;
  31600. break;
  31601. }
  31602. }
  31603. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31604. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31605. if (transform) {
  31606. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31607. }
  31608. }
  31609. materialParams[mapName] = texture;
  31610. });
  31611. };
  31612. /**
  31613. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31614. * already has a material (generated from the glTF material options alone)
  31615. * but reuse of the same glTF material may require multiple threejs materials
  31616. * to accomodate different primitive types, defines, etc. New materials will
  31617. * be created if necessary, and reused from a cache.
  31618. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31619. */
  31620. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31621. var geometry = mesh.geometry;
  31622. var material = mesh.material;
  31623. var extensions = this.extensions;
  31624. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31625. var useVertexColors = geometry.attributes.color !== undefined;
  31626. var useFlatShading = geometry.attributes.normal === undefined;
  31627. var useSkinning = mesh.isSkinnedMesh === true;
  31628. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31629. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31630. if (mesh.isPoints) {
  31631. var cacheKey = 'PointsMaterial:' + material.uuid;
  31632. var pointsMaterial = this.cache.get(cacheKey);
  31633. if (!pointsMaterial) {
  31634. pointsMaterial = new _threeModule.PointsMaterial();
  31635. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31636. pointsMaterial.color.copy(material.color);
  31637. pointsMaterial.map = material.map;
  31638. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31639. this.cache.add(cacheKey, pointsMaterial);
  31640. }
  31641. material = pointsMaterial;
  31642. } else if (mesh.isLine) {
  31643. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31644. var lineMaterial = this.cache.get(cacheKey);
  31645. if (!lineMaterial) {
  31646. lineMaterial = new _threeModule.LineBasicMaterial();
  31647. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31648. lineMaterial.color.copy(material.color);
  31649. this.cache.add(cacheKey, lineMaterial);
  31650. }
  31651. material = lineMaterial;
  31652. } // Clone the material if it will be modified
  31653. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31654. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31655. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31656. if (useSkinning) cacheKey += 'skinning:';
  31657. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31658. if (useVertexColors) cacheKey += 'vertex-colors:';
  31659. if (useFlatShading) cacheKey += 'flat-shading:';
  31660. if (useMorphTargets) cacheKey += 'morph-targets:';
  31661. if (useMorphNormals) cacheKey += 'morph-normals:';
  31662. var cachedMaterial = this.cache.get(cacheKey);
  31663. if (!cachedMaterial) {
  31664. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31665. if (useSkinning) cachedMaterial.skinning = true;
  31666. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31667. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31668. if (useFlatShading) cachedMaterial.flatShading = true;
  31669. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31670. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31671. this.cache.add(cacheKey, cachedMaterial);
  31672. }
  31673. material = cachedMaterial;
  31674. } // workarounds for mesh and geometry
  31675. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31676. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31677. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31678. }
  31679. if (material.isGLTFSpecularGlossinessMaterial) {
  31680. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31681. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31682. }
  31683. mesh.material = material;
  31684. };
  31685. /**
  31686. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31687. * @param {number} materialIndex
  31688. * @return {Promise<Material>}
  31689. */
  31690. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31691. var parser = this;
  31692. var json = this.json;
  31693. var extensions = this.extensions;
  31694. var materialDef = json.materials[materialIndex];
  31695. var materialType;
  31696. var materialParams = {};
  31697. var materialExtensions = materialDef.extensions || {};
  31698. var pending = [];
  31699. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31700. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31701. materialType = sgExtension.getMaterialType();
  31702. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31703. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31704. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31705. materialType = kmuExtension.getMaterialType();
  31706. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31707. } else {
  31708. // Specification:
  31709. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31710. materialType = _threeModule.MeshStandardMaterial;
  31711. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31712. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31713. materialParams.opacity = 1.0;
  31714. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31715. var array = metallicRoughness.baseColorFactor;
  31716. materialParams.color.fromArray(array);
  31717. materialParams.opacity = array[3];
  31718. }
  31719. if (metallicRoughness.baseColorTexture !== undefined) {
  31720. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31721. }
  31722. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31723. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31724. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31725. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31726. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31727. }
  31728. }
  31729. if (materialDef.doubleSided === true) {
  31730. materialParams.side = _threeModule.DoubleSide;
  31731. }
  31732. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31733. if (alphaMode === ALPHA_MODES.BLEND) {
  31734. materialParams.transparent = true;
  31735. } else {
  31736. materialParams.transparent = false;
  31737. if (alphaMode === ALPHA_MODES.MASK) {
  31738. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31739. }
  31740. }
  31741. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31742. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31743. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31744. if (materialDef.normalTexture.scale !== undefined) {
  31745. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31746. }
  31747. }
  31748. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31749. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31750. if (materialDef.occlusionTexture.strength !== undefined) {
  31751. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31752. }
  31753. }
  31754. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31755. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31756. }
  31757. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31758. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31759. }
  31760. return Promise.all(pending).then(function () {
  31761. var material;
  31762. if (materialType === _threeModule.ShaderMaterial) {
  31763. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31764. } else {
  31765. material = new materialType(materialParams);
  31766. }
  31767. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31768. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31769. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31770. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31771. assignExtrasToUserData(material, materialDef);
  31772. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31773. return material;
  31774. });
  31775. };
  31776. /**
  31777. * @param {BufferGeometry} geometry
  31778. * @param {GLTF.Primitive} primitiveDef
  31779. * @param {GLTFParser} parser
  31780. * @return {Promise<BufferGeometry>}
  31781. */
  31782. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31783. var attributes = primitiveDef.attributes;
  31784. var pending = [];
  31785. function assignAttributeAccessor(accessorIndex, attributeName) {
  31786. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31787. geometry.addAttribute(attributeName, accessor);
  31788. });
  31789. }
  31790. for (var gltfAttributeName in attributes) {
  31791. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31792. if (threeAttributeName in geometry.attributes) continue;
  31793. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31794. }
  31795. if (primitiveDef.indices !== undefined && !geometry.index) {
  31796. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31797. geometry.setIndex(accessor);
  31798. });
  31799. pending.push(accessor);
  31800. }
  31801. assignExtrasToUserData(geometry, primitiveDef);
  31802. return Promise.all(pending).then(function () {
  31803. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31804. });
  31805. }
  31806. /**
  31807. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31808. *
  31809. * Creates BufferGeometries from primitives.
  31810. *
  31811. * @param {Array<GLTF.Primitive>} primitives
  31812. * @return {Promise<Array<BufferGeometry>>}
  31813. */
  31814. GLTFParser.prototype.loadGeometries = function (primitives) {
  31815. var parser = this;
  31816. var extensions = this.extensions;
  31817. var cache = this.primitiveCache;
  31818. function createDracoPrimitive(primitive) {
  31819. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31820. return addPrimitiveAttributes(geometry, primitive, parser);
  31821. });
  31822. }
  31823. var pending = [];
  31824. for (var i = 0, il = primitives.length; i < il; i++) {
  31825. var primitive = primitives[i];
  31826. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31827. var cached = cache[cacheKey];
  31828. if (cached) {
  31829. // Use the cached geometry if it exists
  31830. pending.push(cached.promise);
  31831. } else {
  31832. var geometryPromise;
  31833. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31834. // Use DRACO geometry if available
  31835. geometryPromise = createDracoPrimitive(primitive);
  31836. } else {
  31837. // Otherwise create a new geometry
  31838. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31839. } // Cache this geometry
  31840. cache[cacheKey] = {
  31841. primitive: primitive,
  31842. promise: geometryPromise
  31843. };
  31844. pending.push(geometryPromise);
  31845. }
  31846. }
  31847. return Promise.all(pending);
  31848. };
  31849. /**
  31850. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31851. * @param {number} meshIndex
  31852. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31853. */
  31854. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31855. var parser = this;
  31856. var json = this.json;
  31857. var meshDef = json.meshes[meshIndex];
  31858. var primitives = meshDef.primitives;
  31859. var pending = [];
  31860. for (var i = 0, il = primitives.length; i < il; i++) {
  31861. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31862. pending.push(material);
  31863. }
  31864. return Promise.all(pending).then(function (originalMaterials) {
  31865. return parser.loadGeometries(primitives).then(function (geometries) {
  31866. var meshes = [];
  31867. for (var i = 0, il = geometries.length; i < il; i++) {
  31868. var geometry = geometries[i];
  31869. var primitive = primitives[i]; // 1. create Mesh
  31870. var mesh;
  31871. var material = originalMaterials[i];
  31872. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31873. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31874. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31875. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31876. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31877. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31878. mesh.normalizeSkinWeights();
  31879. }
  31880. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31881. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31882. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31883. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31884. }
  31885. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31886. mesh = new _threeModule.LineSegments(geometry, material);
  31887. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31888. mesh = new _threeModule.Line(geometry, material);
  31889. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31890. mesh = new _threeModule.LineLoop(geometry, material);
  31891. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31892. mesh = new _threeModule.Points(geometry, material);
  31893. } else {
  31894. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31895. }
  31896. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31897. updateMorphTargets(mesh, meshDef);
  31898. }
  31899. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31900. if (geometries.length > 1) mesh.name += '_' + i;
  31901. assignExtrasToUserData(mesh, meshDef);
  31902. parser.assignFinalMaterial(mesh);
  31903. meshes.push(mesh);
  31904. }
  31905. if (meshes.length === 1) {
  31906. return meshes[0];
  31907. }
  31908. var group = new _threeModule.Group();
  31909. for (var i = 0, il = meshes.length; i < il; i++) {
  31910. group.add(meshes[i]);
  31911. }
  31912. return group;
  31913. });
  31914. });
  31915. };
  31916. /**
  31917. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31918. * @param {number} cameraIndex
  31919. * @return {Promise<THREE.Camera>}
  31920. */
  31921. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31922. var camera;
  31923. var cameraDef = this.json.cameras[cameraIndex];
  31924. var params = cameraDef[cameraDef.type];
  31925. if (!params) {
  31926. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31927. return;
  31928. }
  31929. if (cameraDef.type === 'perspective') {
  31930. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31931. } else if (cameraDef.type === 'orthographic') {
  31932. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31933. }
  31934. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31935. assignExtrasToUserData(camera, cameraDef);
  31936. return Promise.resolve(camera);
  31937. };
  31938. /**
  31939. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31940. * @param {number} skinIndex
  31941. * @return {Promise<Object>}
  31942. */
  31943. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31944. var skinDef = this.json.skins[skinIndex];
  31945. var skinEntry = {
  31946. joints: skinDef.joints
  31947. };
  31948. if (skinDef.inverseBindMatrices === undefined) {
  31949. return Promise.resolve(skinEntry);
  31950. }
  31951. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31952. skinEntry.inverseBindMatrices = accessor;
  31953. return skinEntry;
  31954. });
  31955. };
  31956. /**
  31957. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31958. * @param {number} animationIndex
  31959. * @return {Promise<AnimationClip>}
  31960. */
  31961. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31962. var json = this.json;
  31963. var animationDef = json.animations[animationIndex];
  31964. var pendingNodes = [];
  31965. var pendingInputAccessors = [];
  31966. var pendingOutputAccessors = [];
  31967. var pendingSamplers = [];
  31968. var pendingTargets = [];
  31969. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31970. var channel = animationDef.channels[i];
  31971. var sampler = animationDef.samplers[channel.sampler];
  31972. var target = channel.target;
  31973. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  31974. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  31975. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  31976. pendingNodes.push(this.getDependency('node', name));
  31977. pendingInputAccessors.push(this.getDependency('accessor', input));
  31978. pendingOutputAccessors.push(this.getDependency('accessor', output));
  31979. pendingSamplers.push(sampler);
  31980. pendingTargets.push(target);
  31981. }
  31982. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  31983. var nodes = dependencies[0];
  31984. var inputAccessors = dependencies[1];
  31985. var outputAccessors = dependencies[2];
  31986. var samplers = dependencies[3];
  31987. var targets = dependencies[4];
  31988. var tracks = [];
  31989. for (var i = 0, il = nodes.length; i < il; i++) {
  31990. var node = nodes[i];
  31991. var inputAccessor = inputAccessors[i];
  31992. var outputAccessor = outputAccessors[i];
  31993. var sampler = samplers[i];
  31994. var target = targets[i];
  31995. if (node === undefined) continue;
  31996. node.updateMatrix();
  31997. node.matrixAutoUpdate = true;
  31998. var TypedKeyframeTrack;
  31999. switch (PATH_PROPERTIES[target.path]) {
  32000. case PATH_PROPERTIES.weights:
  32001. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32002. break;
  32003. case PATH_PROPERTIES.rotation:
  32004. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32005. break;
  32006. case PATH_PROPERTIES.position:
  32007. case PATH_PROPERTIES.scale:
  32008. default:
  32009. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32010. break;
  32011. }
  32012. var targetName = node.name ? node.name : node.uuid;
  32013. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32014. var targetNames = [];
  32015. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32016. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32017. node.traverse(function (object) {
  32018. if (object.isMesh === true && object.morphTargetInfluences) {
  32019. targetNames.push(object.name ? object.name : object.uuid);
  32020. }
  32021. });
  32022. } else {
  32023. targetNames.push(targetName);
  32024. }
  32025. var outputArray = outputAccessor.array;
  32026. if (outputAccessor.normalized) {
  32027. var scale;
  32028. if (outputArray.constructor === Int8Array) {
  32029. scale = 1 / 127;
  32030. } else if (outputArray.constructor === Uint8Array) {
  32031. scale = 1 / 255;
  32032. } else if (outputArray.constructor == Int16Array) {
  32033. scale = 1 / 32767;
  32034. } else if (outputArray.constructor === Uint16Array) {
  32035. scale = 1 / 65535;
  32036. } else {
  32037. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32038. }
  32039. var scaled = new Float32Array(outputArray.length);
  32040. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32041. scaled[j] = outputArray[j] * scale;
  32042. }
  32043. outputArray = scaled;
  32044. }
  32045. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32046. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32047. if (sampler.interpolation === 'CUBICSPLINE') {
  32048. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32049. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32050. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32051. // must be divided by three to get the interpolant's sampleSize argument.
  32052. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32053. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32054. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32055. }
  32056. tracks.push(track);
  32057. }
  32058. }
  32059. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32060. return new _threeModule.AnimationClip(name, undefined, tracks);
  32061. });
  32062. };
  32063. /**
  32064. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32065. * @param {number} nodeIndex
  32066. * @return {Promise<Object3D>}
  32067. */
  32068. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32069. var json = this.json;
  32070. var extensions = this.extensions;
  32071. var parser = this;
  32072. var meshReferences = json.meshReferences;
  32073. var meshUses = json.meshUses;
  32074. var nodeDef = json.nodes[nodeIndex];
  32075. return function () {
  32076. var pending = [];
  32077. if (nodeDef.mesh !== undefined) {
  32078. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32079. var node;
  32080. if (meshReferences[nodeDef.mesh] > 1) {
  32081. var instanceNum = meshUses[nodeDef.mesh]++;
  32082. node = mesh.clone();
  32083. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32084. node.onBeforeRender = mesh.onBeforeRender;
  32085. for (var i = 0, il = node.children.length; i < il; i++) {
  32086. node.children[i].name += '_instance_' + instanceNum;
  32087. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32088. }
  32089. } else {
  32090. node = mesh;
  32091. } // if weights are provided on the node, override weights on the mesh.
  32092. if (nodeDef.weights !== undefined) {
  32093. node.traverse(function (o) {
  32094. if (!o.isMesh) return;
  32095. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32096. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32097. }
  32098. });
  32099. }
  32100. return node;
  32101. }));
  32102. }
  32103. if (nodeDef.camera !== undefined) {
  32104. pending.push(parser.getDependency('camera', nodeDef.camera));
  32105. }
  32106. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32107. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32108. }
  32109. return Promise.all(pending);
  32110. }().then(function (objects) {
  32111. var node; // .isBone isn't in glTF spec. See .markDefs
  32112. if (nodeDef.isBone === true) {
  32113. node = new _threeModule.Bone();
  32114. } else if (objects.length > 1) {
  32115. node = new _threeModule.Group();
  32116. } else if (objects.length === 1) {
  32117. node = objects[0];
  32118. } else {
  32119. node = new _threeModule.Object3D();
  32120. }
  32121. if (node !== objects[0]) {
  32122. for (var i = 0, il = objects.length; i < il; i++) {
  32123. node.add(objects[i]);
  32124. }
  32125. }
  32126. if (nodeDef.name !== undefined) {
  32127. node.userData.name = nodeDef.name;
  32128. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32129. }
  32130. assignExtrasToUserData(node, nodeDef);
  32131. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32132. if (nodeDef.matrix !== undefined) {
  32133. var matrix = new _threeModule.Matrix4();
  32134. matrix.fromArray(nodeDef.matrix);
  32135. node.applyMatrix(matrix);
  32136. } else {
  32137. if (nodeDef.translation !== undefined) {
  32138. node.position.fromArray(nodeDef.translation);
  32139. }
  32140. if (nodeDef.rotation !== undefined) {
  32141. node.quaternion.fromArray(nodeDef.rotation);
  32142. }
  32143. if (nodeDef.scale !== undefined) {
  32144. node.scale.fromArray(nodeDef.scale);
  32145. }
  32146. }
  32147. return node;
  32148. });
  32149. };
  32150. /**
  32151. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32152. * @param {number} sceneIndex
  32153. * @return {Promise<Scene>}
  32154. */
  32155. GLTFParser.prototype.loadScene = function () {
  32156. // scene node hierachy builder
  32157. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32158. var nodeDef = json.nodes[nodeId];
  32159. return parser.getDependency('node', nodeId).then(function (node) {
  32160. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32161. var skinEntry;
  32162. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32163. skinEntry = skin;
  32164. var pendingJoints = [];
  32165. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32166. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32167. }
  32168. return Promise.all(pendingJoints);
  32169. }).then(function (jointNodes) {
  32170. node.traverse(function (mesh) {
  32171. if (!mesh.isMesh) return;
  32172. var bones = [];
  32173. var boneInverses = [];
  32174. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32175. var jointNode = jointNodes[j];
  32176. if (jointNode) {
  32177. bones.push(jointNode);
  32178. var mat = new _threeModule.Matrix4();
  32179. if (skinEntry.inverseBindMatrices !== undefined) {
  32180. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32181. }
  32182. boneInverses.push(mat);
  32183. } else {
  32184. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32185. }
  32186. }
  32187. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32188. });
  32189. return node;
  32190. });
  32191. }).then(function (node) {
  32192. // build node hierachy
  32193. parentObject.add(node);
  32194. var pending = [];
  32195. if (nodeDef.children) {
  32196. var children = nodeDef.children;
  32197. for (var i = 0, il = children.length; i < il; i++) {
  32198. var child = children[i];
  32199. pending.push(buildNodeHierachy(child, node, json, parser));
  32200. }
  32201. }
  32202. return Promise.all(pending);
  32203. });
  32204. }
  32205. return function loadScene(sceneIndex) {
  32206. var json = this.json;
  32207. var extensions = this.extensions;
  32208. var sceneDef = this.json.scenes[sceneIndex];
  32209. var parser = this;
  32210. var scene = new _threeModule.Scene();
  32211. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32212. assignExtrasToUserData(scene, sceneDef);
  32213. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32214. var nodeIds = sceneDef.nodes || [];
  32215. var pending = [];
  32216. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32217. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32218. }
  32219. return Promise.all(pending).then(function () {
  32220. return scene;
  32221. });
  32222. };
  32223. }();
  32224. return GLTFLoader;
  32225. }();
  32226. exports.GLTFLoader = GLTFLoader;
  32227. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/ThreeB3DMLoader.js":[function(require,module,exports) {
  32228. "use strict";
  32229. Object.defineProperty(exports, "__esModule", {
  32230. value: true
  32231. });
  32232. exports.ThreeB3DMLoader = void 0;
  32233. var _B3DMLoader = require("./B3DMLoader.js");
  32234. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32235. class ThreeB3DMLoader extends _B3DMLoader.B3DMLoader {
  32236. parse(buffer) {
  32237. const b3dm = super.parse(buffer);
  32238. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32239. return new Promise((resolve, reject) => {
  32240. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32241. });
  32242. }
  32243. }
  32244. exports.ThreeB3DMLoader = ThreeB3DMLoader;
  32245. },{"./B3DMLoader.js":"../src/B3DMLoader.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/ThreeTilesRenderer.js":[function(require,module,exports) {
  32246. "use strict";
  32247. Object.defineProperty(exports, "__esModule", {
  32248. value: true
  32249. });
  32250. exports.ThreeTilesRenderer = void 0;
  32251. var _TilesRenderer = require("./TilesRenderer.js");
  32252. var _ThreeB3DMLoader = require("./ThreeB3DMLoader.js");
  32253. var _three = require("three");
  32254. const DEG2RAD = _three.Math.DEG2RAD;
  32255. const tempMat = new _three.Matrix4();
  32256. const tempQuaternion = new _three.Quaternion();
  32257. const tempVector = new _three.Vector3();
  32258. const resVector = new _three.Vector2();
  32259. const vecX = new _three.Vector3();
  32260. const vecY = new _three.Vector3();
  32261. const vecZ = new _three.Vector3();
  32262. const _sphere = new _three.Sphere(); // Specialization of "Group" that only updates world matrices of children if
  32263. // the transform has changed since the last update and ignores the "force"
  32264. // parameter under the assumption that the children tiles will not move.
  32265. class TilesGroup extends _three.Group {
  32266. constructor(tilesRenderer) {
  32267. super();
  32268. this.tilesRenderer = tilesRenderer;
  32269. }
  32270. raycast(raycaster, intersects) {
  32271. // TODO
  32272. const tilesRenderer = this.tilesRenderer;
  32273. }
  32274. updateMatrixWorld(force) {
  32275. if (this.matrixAutoUpdate) {
  32276. this.updateMatrix();
  32277. }
  32278. if (this.matrixWorldNeedsUpdate || force) {
  32279. if (this.parent === null) {
  32280. tempMat.copy(this.matrix);
  32281. } else {
  32282. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32283. }
  32284. this.matrixWorldNeedsUpdate = false;
  32285. const elA = tempMat.elements;
  32286. const elB = this.matrixWorld.elements;
  32287. let isDifferent = false;
  32288. for (let i = 0; i < 16; i++) {
  32289. const itemA = elA[i];
  32290. const itemB = elB[i];
  32291. const diff = Math.abs(itemA - itemB);
  32292. if (diff > Number.EPSILON) {
  32293. isDifferent = true;
  32294. break;
  32295. }
  32296. }
  32297. if (isDifferent) {
  32298. this.matrixWorld.copy(tempMat); // update children
  32299. // the children will not have to change unless the parent group has updated
  32300. const children = this.children;
  32301. for (let i = 0, l = children.length; i < l; i++) {
  32302. children[i].updateMatrixWorld();
  32303. }
  32304. }
  32305. }
  32306. }
  32307. }
  32308. class ThreeTilesRenderer extends _TilesRenderer.TilesRenderer {
  32309. get displayBounds() {
  32310. return this._displayBounds;
  32311. }
  32312. set displayBounds(val) {
  32313. if (val !== this.displayBounds) {
  32314. this._displayBounds = val;
  32315. this.traverse(t => {
  32316. const scene = t.cached.scene;
  32317. const boxHelper = t.cached.boxHelper;
  32318. if (scene) {
  32319. if (val) {
  32320. scene.add(boxHelper);
  32321. boxHelper.updateMatrixWorld(true);
  32322. } else {
  32323. scene.remove(boxHelper);
  32324. }
  32325. }
  32326. });
  32327. }
  32328. }
  32329. constructor(url, cameras, renderer) {
  32330. super(url);
  32331. this.group = new TilesGroup();
  32332. this.cameras = Array.isArray(cameras) ? cameras : [cameras];
  32333. this.frustums = [];
  32334. this.renderer = renderer;
  32335. this.active = [];
  32336. }
  32337. /* Public API */
  32338. getBounds(box) {
  32339. if (!this.root) {
  32340. return false;
  32341. }
  32342. const cached = this.root.cached;
  32343. const boundingBox = cached.box;
  32344. const obbMat = cached.boxTransform;
  32345. const transformMat = cached.transform;
  32346. box.copy(boundingBox);
  32347. tempMat.multiplyMatrices(transformMat, obbMat);
  32348. box.applyMatrix4(tempMat);
  32349. return true;
  32350. }
  32351. /* Overriden */
  32352. update() {
  32353. const group = this.group;
  32354. const renderer = this.renderer;
  32355. const cameras = this.cameras;
  32356. const frustums = this.frustums; // automatically scale the array of frustums to match the cameras
  32357. while (frustums.length > cameras.length) {
  32358. frustums.pop();
  32359. }
  32360. while (frustums.length < cameras.length) {
  32361. frustums.push(new _three.Frustum());
  32362. } // store the camera frustums in the 3d tiles root frame
  32363. for (let i = 0, l = frustums.length; i < l; i++) {
  32364. const camera = cameras[i];
  32365. const frustum = frustums[i];
  32366. tempMat.copy(group.matrixWorld);
  32367. tempMat.premultiply(camera.matrixWorldInverse);
  32368. tempMat.premultiply(camera.projectionMatrix);
  32369. frustum.setFromMatrix(tempMat);
  32370. } // store the resolution of the render
  32371. renderer.getSize(resVector);
  32372. resVector.multiplyScalar(renderer.getPixelRatio());
  32373. super.update();
  32374. }
  32375. preprocessNode(tile, parentTile, tileSetDir) {
  32376. super.preprocessNode(tile, parentTile, tileSetDir);
  32377. const transform = new _three.Matrix4();
  32378. if (tile.transform) {
  32379. const transformArr = tile.transform;
  32380. for (let i = 0; i < 16; i++) {
  32381. transform.elements[i] = transformArr[i];
  32382. }
  32383. } else {
  32384. transform.identity();
  32385. }
  32386. if (parentTile) {
  32387. transform.multiply(parentTile.cached.transform);
  32388. }
  32389. let box = null;
  32390. let boxTransform = null;
  32391. if ('box' in tile.boundingVolume) {
  32392. const data = tile.boundingVolume.box;
  32393. box = new _three.Box3();
  32394. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32395. vecX.set(data[3], data[4], data[5]);
  32396. vecY.set(data[6], data[7], data[8]);
  32397. vecZ.set(data[9], data[10], data[11]);
  32398. const scaleX = vecX.length();
  32399. const scaleY = vecY.length();
  32400. const scaleZ = vecZ.length();
  32401. vecX.normalize();
  32402. vecY.normalize();
  32403. vecZ.normalize(); // create the oriented frame that the box exists in
  32404. 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); // scale the box by the extents
  32405. box.min.set(-scaleX, -scaleY, -scaleZ);
  32406. box.max.set(scaleX, scaleY, scaleZ);
  32407. }
  32408. let sphere = null;
  32409. if ('sphere' in tile.boundingVolume) {
  32410. const data = tile.boundingVolume.sphere;
  32411. sphere = new _three.Sphere();
  32412. sphere.center.set(data[0], data[1], data[2]);
  32413. sphere.radius = data[3];
  32414. } else if ('box' in tile.boundingVolume) {
  32415. sphere = new _three.Sphere();
  32416. box.getBoundingSphere(sphere);
  32417. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32418. }
  32419. let region = null;
  32420. if ('region' in tile.boundingVolume) {
  32421. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32422. }
  32423. tile.cached = {
  32424. loadIndex: 0,
  32425. transform,
  32426. active: false,
  32427. box,
  32428. boxTransform,
  32429. sphere,
  32430. region,
  32431. boxHelper: null,
  32432. scene: null
  32433. };
  32434. }
  32435. parseTile(buffer, tile) {
  32436. tile._loadIndex = tile._loadIndex || 0;
  32437. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32438. const loadIndex = tile._loadIndex;
  32439. return new _ThreeB3DMLoader.ThreeB3DMLoader().parse(buffer).then(res => {
  32440. if (tile._loadIndex !== loadIndex) {
  32441. return;
  32442. }
  32443. const cached = tile.cached;
  32444. const cachedBox = cached.box;
  32445. const cachedBoxMat = cached.boxTransform; // add a helper group to represent the obb rotation matrix
  32446. const boxHelper = new _three.Box3Helper(cachedBox);
  32447. const boxHelperGroup = new _three.Group();
  32448. cachedBoxMat.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  32449. boxHelperGroup.add(boxHelper);
  32450. boxHelperGroup.updateMatrixWorld(true);
  32451. const scene = res.scene;
  32452. cached.transform.decompose(scene.position, scene.quaternion, scene.scale);
  32453. scene.traverse(c => c.frustumCulled = false);
  32454. cached.boxHelper = boxHelperGroup;
  32455. cached.scene = res.scene;
  32456. if (this.displayBounds) {
  32457. cached.scene.add(cached.boxHelper);
  32458. }
  32459. });
  32460. }
  32461. disposeTile(tile) {
  32462. const cached = tile.cached;
  32463. if (cached.scene) {
  32464. const scene = cached.scene;
  32465. if (scene.parent) {
  32466. scene.parent.remove(scene);
  32467. }
  32468. scene.traverse(c => {
  32469. if (c.geometry) {
  32470. c.geometry.dispose();
  32471. }
  32472. if (c.material) {
  32473. c.material.dispose(); // TODO: dispose textures
  32474. }
  32475. });
  32476. cached.scene = null;
  32477. cached.boxHelper = null;
  32478. }
  32479. tile._loadIndex++;
  32480. }
  32481. setTileVisible(tile, visible) {
  32482. const scene = tile.cached.scene;
  32483. if (visible) {
  32484. if (scene && !scene.parent) {
  32485. this.group.add(scene);
  32486. scene.updateMatrixWorld(true);
  32487. }
  32488. } else {
  32489. this.group.remove(scene);
  32490. }
  32491. }
  32492. setTileActive(tile, active) {
  32493. const cached = tile.cached;
  32494. if (active !== cached.active) {
  32495. cached.active = active;
  32496. if (active) {
  32497. this.active.push(cached.scene);
  32498. } else {
  32499. const index = this.active.indexOf(cached.scene);
  32500. this.active.splice(index, 1);
  32501. }
  32502. }
  32503. }
  32504. calculateError(tile) {
  32505. const cached = tile.cached;
  32506. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32507. const boundingVolume = tile.boundingVolume;
  32508. const transformMat = cached.transform;
  32509. if ('box' in boundingVolume) {
  32510. const group = this.group;
  32511. const boundingBox = cached.box;
  32512. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32513. // transformMat can be rolled into oobMat
  32514. tempMat.copy(transformMat);
  32515. tempMat.multiply(obbMat);
  32516. tempMat.getInverse(tempMat);
  32517. let minError = Infinity;
  32518. for (let i = 0, l = cameras.length; i < l; i++) {
  32519. // transform camera position into local frame of the tile bounding box
  32520. const cam = cameras[i];
  32521. tempVector.copy(cam.position);
  32522. tempVector.applyMatrix4(tempMat);
  32523. let error;
  32524. if (cam.isOrthographic) {
  32525. const w = cam.right - cam.left;
  32526. const h = cam.top - cam.bottom;
  32527. const pixelSize = Math.Max(h, w) / Math.Max(resVector.width, resVector.height);
  32528. error = tile.geometricError / pixelSize;
  32529. } else {
  32530. const distance = boundingBox.distanceToPoint(tempVector); // assume the scales on all axes are uniform.
  32531. let scale; // account for tile scale.
  32532. tempVector.setFromMatrixScale(tempMat);
  32533. scale = tempVector.x; // account for parent group scale. Divide because this matrix has not been inverted like the previous one.
  32534. tempVector.setFromMatrixScale(group.matrixWorld);
  32535. scale /= tempVector.x;
  32536. if (Math.abs(Math.max(scale.x - scale.y, scale.x - scale.z)) > 1e-6) {
  32537. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when claculating screen space error.');
  32538. }
  32539. const scaledDistance = distance * scale;
  32540. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32541. error = tile.geometricError * resVector.height / (scaledDistance * sseDenominator);
  32542. }
  32543. minError = Math.min(minError, error);
  32544. }
  32545. return minError;
  32546. } else if ('sphere' in boundingVolume) {
  32547. const sphere = cached.sphere;
  32548. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32549. } else if ('region' in boundingVolume) {
  32550. // unsupported
  32551. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32552. }
  32553. return Infinity;
  32554. }
  32555. tileInView(tile) {
  32556. // TODO: we should use the more precise bounding volumes here if possible
  32557. // cache the root-space planes
  32558. const sphere = tile.cached.sphere;
  32559. if (sphere) {
  32560. _sphere.copy(sphere);
  32561. _sphere.applyMatrix4(tile.cached.transform);
  32562. const frustums = this.frustums;
  32563. for (let i = 0, l = frustums.length; i < l; i++) {
  32564. const frustum = frustums[i];
  32565. if (frustum.intersectsSphere(_sphere)) {
  32566. return true;
  32567. }
  32568. }
  32569. return false;
  32570. }
  32571. return true;
  32572. }
  32573. }
  32574. exports.ThreeTilesRenderer = ThreeTilesRenderer;
  32575. },{"./TilesRenderer.js":"../src/TilesRenderer.js","./ThreeB3DMLoader.js":"../src/ThreeB3DMLoader.js","three":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  32576. "use strict";
  32577. Object.defineProperty(exports, "__esModule", {
  32578. value: true
  32579. });
  32580. exports.MapControls = exports.OrbitControls = void 0;
  32581. var _threeModule = require("../../../build/three.module.js");
  32582. /**
  32583. * @author qiao / https://github.com/qiao
  32584. * @author mrdoob / http://mrdoob.com
  32585. * @author alteredq / http://alteredqualia.com/
  32586. * @author WestLangley / http://github.com/WestLangley
  32587. * @author erich666 / http://erichaines.com
  32588. * @author ScieCode / http://github.com/sciecode
  32589. */
  32590. // This set of controls performs orbiting, dollying (zooming), and panning.
  32591. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32592. //
  32593. // Orbit - left mouse / touch: one-finger move
  32594. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32595. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32596. var OrbitControls = function (object, domElement) {
  32597. this.object = object;
  32598. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  32599. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  32600. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  32601. this.minDistance = 0;
  32602. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  32603. this.minZoom = 0;
  32604. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  32605. // Range is 0 to Math.PI radians.
  32606. this.minPolarAngle = 0; // radians
  32607. this.maxPolarAngle = Math.PI; // radians
  32608. // How far you can orbit horizontally, upper and lower limits.
  32609. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  32610. this.minAzimuthAngle = -Infinity; // radians
  32611. this.maxAzimuthAngle = Infinity; // radians
  32612. // Set to true to enable damping (inertia)
  32613. // If damping is enabled, you must call controls.update() in your animation loop
  32614. this.enableDamping = false;
  32615. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32616. // Set to false to disable zooming
  32617. this.enableZoom = true;
  32618. this.zoomSpeed = 1.0; // Set to false to disable rotating
  32619. this.enableRotate = true;
  32620. this.rotateSpeed = 1.0; // Set to false to disable panning
  32621. this.enablePan = true;
  32622. this.panSpeed = 1.0;
  32623. this.screenSpacePanning = false; // if true, pan in screen-space
  32624. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32625. // Set to true to automatically rotate around the target
  32626. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32627. this.autoRotate = false;
  32628. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  32629. // Set to false to disable use of the keys
  32630. this.enableKeys = true; // The four arrow keys
  32631. this.keys = {
  32632. LEFT: 37,
  32633. UP: 38,
  32634. RIGHT: 39,
  32635. BOTTOM: 40
  32636. }; // Mouse buttons
  32637. this.mouseButtons = {
  32638. LEFT: _threeModule.MOUSE.ROTATE,
  32639. MIDDLE: _threeModule.MOUSE.DOLLY,
  32640. RIGHT: _threeModule.MOUSE.PAN
  32641. }; // Touch fingers
  32642. this.touches = {
  32643. ONE: _threeModule.TOUCH.ROTATE,
  32644. TWO: _threeModule.TOUCH.DOLLY_PAN
  32645. }; // for reset
  32646. this.target0 = this.target.clone();
  32647. this.position0 = this.object.position.clone();
  32648. this.zoom0 = this.object.zoom; //
  32649. // public methods
  32650. //
  32651. this.getPolarAngle = function () {
  32652. return spherical.phi;
  32653. };
  32654. this.getAzimuthalAngle = function () {
  32655. return spherical.theta;
  32656. };
  32657. this.saveState = function () {
  32658. scope.target0.copy(scope.target);
  32659. scope.position0.copy(scope.object.position);
  32660. scope.zoom0 = scope.object.zoom;
  32661. };
  32662. this.reset = function () {
  32663. scope.target.copy(scope.target0);
  32664. scope.object.position.copy(scope.position0);
  32665. scope.object.zoom = scope.zoom0;
  32666. scope.object.updateProjectionMatrix();
  32667. scope.dispatchEvent(changeEvent);
  32668. scope.update();
  32669. state = STATE.NONE;
  32670. }; // this method is exposed, but perhaps it would be better if we can make it private...
  32671. this.update = function () {
  32672. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  32673. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  32674. var quatInverse = quat.clone().inverse();
  32675. var lastPosition = new _threeModule.Vector3();
  32676. var lastQuaternion = new _threeModule.Quaternion();
  32677. return function update() {
  32678. var position = scope.object.position;
  32679. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  32680. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  32681. spherical.setFromVector3(offset);
  32682. if (scope.autoRotate && state === STATE.NONE) {
  32683. rotateLeft(getAutoRotationAngle());
  32684. }
  32685. if (scope.enableDamping) {
  32686. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32687. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32688. } else {
  32689. spherical.theta += sphericalDelta.theta;
  32690. spherical.phi += sphericalDelta.phi;
  32691. } // restrict theta to be between desired limits
  32692. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  32693. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  32694. spherical.makeSafe();
  32695. spherical.radius *= scale; // restrict radius to be between desired limits
  32696. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  32697. if (scope.enableDamping === true) {
  32698. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  32699. } else {
  32700. scope.target.add(panOffset);
  32701. }
  32702. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  32703. offset.applyQuaternion(quatInverse);
  32704. position.copy(scope.target).add(offset);
  32705. scope.object.lookAt(scope.target);
  32706. if (scope.enableDamping === true) {
  32707. sphericalDelta.theta *= 1 - scope.dampingFactor;
  32708. sphericalDelta.phi *= 1 - scope.dampingFactor;
  32709. panOffset.multiplyScalar(1 - scope.dampingFactor);
  32710. } else {
  32711. sphericalDelta.set(0, 0, 0);
  32712. panOffset.set(0, 0, 0);
  32713. }
  32714. scale = 1; // update condition is:
  32715. // min(camera displacement, camera rotation in radians)^2 > EPS
  32716. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32717. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  32718. scope.dispatchEvent(changeEvent);
  32719. lastPosition.copy(scope.object.position);
  32720. lastQuaternion.copy(scope.object.quaternion);
  32721. zoomChanged = false;
  32722. return true;
  32723. }
  32724. return false;
  32725. };
  32726. }();
  32727. this.dispose = function () {
  32728. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  32729. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  32730. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  32731. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  32732. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  32733. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  32734. document.removeEventListener('mousemove', onMouseMove, false);
  32735. document.removeEventListener('mouseup', onMouseUp, false);
  32736. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32737. }; //
  32738. // internals
  32739. //
  32740. var scope = this;
  32741. var changeEvent = {
  32742. type: 'change'
  32743. };
  32744. var startEvent = {
  32745. type: 'start'
  32746. };
  32747. var endEvent = {
  32748. type: 'end'
  32749. };
  32750. var STATE = {
  32751. NONE: -1,
  32752. ROTATE: 0,
  32753. DOLLY: 1,
  32754. PAN: 2,
  32755. TOUCH_ROTATE: 3,
  32756. TOUCH_PAN: 4,
  32757. TOUCH_DOLLY_PAN: 5,
  32758. TOUCH_DOLLY_ROTATE: 6
  32759. };
  32760. var state = STATE.NONE;
  32761. var EPS = 0.000001; // current position in spherical coordinates
  32762. var spherical = new _threeModule.Spherical();
  32763. var sphericalDelta = new _threeModule.Spherical();
  32764. var scale = 1;
  32765. var panOffset = new _threeModule.Vector3();
  32766. var zoomChanged = false;
  32767. var rotateStart = new _threeModule.Vector2();
  32768. var rotateEnd = new _threeModule.Vector2();
  32769. var rotateDelta = new _threeModule.Vector2();
  32770. var panStart = new _threeModule.Vector2();
  32771. var panEnd = new _threeModule.Vector2();
  32772. var panDelta = new _threeModule.Vector2();
  32773. var dollyStart = new _threeModule.Vector2();
  32774. var dollyEnd = new _threeModule.Vector2();
  32775. var dollyDelta = new _threeModule.Vector2();
  32776. function getAutoRotationAngle() {
  32777. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  32778. }
  32779. function getZoomScale() {
  32780. return Math.pow(0.95, scope.zoomSpeed);
  32781. }
  32782. function rotateLeft(angle) {
  32783. sphericalDelta.theta -= angle;
  32784. }
  32785. function rotateUp(angle) {
  32786. sphericalDelta.phi -= angle;
  32787. }
  32788. var panLeft = function () {
  32789. var v = new _threeModule.Vector3();
  32790. return function panLeft(distance, objectMatrix) {
  32791. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  32792. v.multiplyScalar(-distance);
  32793. panOffset.add(v);
  32794. };
  32795. }();
  32796. var panUp = function () {
  32797. var v = new _threeModule.Vector3();
  32798. return function panUp(distance, objectMatrix) {
  32799. if (scope.screenSpacePanning === true) {
  32800. v.setFromMatrixColumn(objectMatrix, 1);
  32801. } else {
  32802. v.setFromMatrixColumn(objectMatrix, 0);
  32803. v.crossVectors(scope.object.up, v);
  32804. }
  32805. v.multiplyScalar(distance);
  32806. panOffset.add(v);
  32807. };
  32808. }(); // deltaX and deltaY are in pixels; right and down are positive
  32809. var pan = function () {
  32810. var offset = new _threeModule.Vector3();
  32811. return function pan(deltaX, deltaY) {
  32812. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32813. if (scope.object.isPerspectiveCamera) {
  32814. // perspective
  32815. var position = scope.object.position;
  32816. offset.copy(position).sub(scope.target);
  32817. var targetDistance = offset.length(); // half of the fov is center to top of screen
  32818. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  32819. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  32820. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  32821. } else if (scope.object.isOrthographicCamera) {
  32822. // orthographic
  32823. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  32824. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  32825. } else {
  32826. // camera neither orthographic nor perspective
  32827. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  32828. scope.enablePan = false;
  32829. }
  32830. };
  32831. }();
  32832. function dollyIn(dollyScale) {
  32833. if (scope.object.isPerspectiveCamera) {
  32834. scale /= dollyScale;
  32835. } else if (scope.object.isOrthographicCamera) {
  32836. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  32837. scope.object.updateProjectionMatrix();
  32838. zoomChanged = true;
  32839. } else {
  32840. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32841. scope.enableZoom = false;
  32842. }
  32843. }
  32844. function dollyOut(dollyScale) {
  32845. if (scope.object.isPerspectiveCamera) {
  32846. scale *= dollyScale;
  32847. } else if (scope.object.isOrthographicCamera) {
  32848. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  32849. scope.object.updateProjectionMatrix();
  32850. zoomChanged = true;
  32851. } else {
  32852. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32853. scope.enableZoom = false;
  32854. }
  32855. } //
  32856. // event callbacks - update the object state
  32857. //
  32858. function handleMouseDownRotate(event) {
  32859. rotateStart.set(event.clientX, event.clientY);
  32860. }
  32861. function handleMouseDownDolly(event) {
  32862. dollyStart.set(event.clientX, event.clientY);
  32863. }
  32864. function handleMouseDownPan(event) {
  32865. panStart.set(event.clientX, event.clientY);
  32866. }
  32867. function handleMouseMoveRotate(event) {
  32868. rotateEnd.set(event.clientX, event.clientY);
  32869. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32870. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32871. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32872. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32873. rotateStart.copy(rotateEnd);
  32874. scope.update();
  32875. }
  32876. function handleMouseMoveDolly(event) {
  32877. dollyEnd.set(event.clientX, event.clientY);
  32878. dollyDelta.subVectors(dollyEnd, dollyStart);
  32879. if (dollyDelta.y > 0) {
  32880. dollyIn(getZoomScale());
  32881. } else if (dollyDelta.y < 0) {
  32882. dollyOut(getZoomScale());
  32883. }
  32884. dollyStart.copy(dollyEnd);
  32885. scope.update();
  32886. }
  32887. function handleMouseMovePan(event) {
  32888. panEnd.set(event.clientX, event.clientY);
  32889. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32890. pan(panDelta.x, panDelta.y);
  32891. panStart.copy(panEnd);
  32892. scope.update();
  32893. }
  32894. function handleMouseUp()
  32895. /*event*/
  32896. {// no-op
  32897. }
  32898. function handleMouseWheel(event) {
  32899. if (event.deltaY < 0) {
  32900. dollyOut(getZoomScale());
  32901. } else if (event.deltaY > 0) {
  32902. dollyIn(getZoomScale());
  32903. }
  32904. scope.update();
  32905. }
  32906. function handleKeyDown(event) {
  32907. var needsUpdate = false;
  32908. switch (event.keyCode) {
  32909. case scope.keys.UP:
  32910. pan(0, scope.keyPanSpeed);
  32911. needsUpdate = true;
  32912. break;
  32913. case scope.keys.BOTTOM:
  32914. pan(0, -scope.keyPanSpeed);
  32915. needsUpdate = true;
  32916. break;
  32917. case scope.keys.LEFT:
  32918. pan(scope.keyPanSpeed, 0);
  32919. needsUpdate = true;
  32920. break;
  32921. case scope.keys.RIGHT:
  32922. pan(-scope.keyPanSpeed, 0);
  32923. needsUpdate = true;
  32924. break;
  32925. }
  32926. if (needsUpdate) {
  32927. // prevent the browser from scrolling on cursor keys
  32928. event.preventDefault();
  32929. scope.update();
  32930. }
  32931. }
  32932. function handleTouchStartRotate(event) {
  32933. if (event.touches.length == 1) {
  32934. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  32935. } else {
  32936. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32937. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32938. rotateStart.set(x, y);
  32939. }
  32940. }
  32941. function handleTouchStartPan(event) {
  32942. if (event.touches.length == 1) {
  32943. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  32944. } else {
  32945. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32946. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32947. panStart.set(x, y);
  32948. }
  32949. }
  32950. function handleTouchStartDolly(event) {
  32951. var dx = event.touches[0].pageX - event.touches[1].pageX;
  32952. var dy = event.touches[0].pageY - event.touches[1].pageY;
  32953. var distance = Math.sqrt(dx * dx + dy * dy);
  32954. dollyStart.set(0, distance);
  32955. }
  32956. function handleTouchStartDollyPan(event) {
  32957. if (scope.enableZoom) handleTouchStartDolly(event);
  32958. if (scope.enablePan) handleTouchStartPan(event);
  32959. }
  32960. function handleTouchStartDollyRotate(event) {
  32961. if (scope.enableZoom) handleTouchStartDolly(event);
  32962. if (scope.enableRotate) handleTouchStartRotate(event);
  32963. }
  32964. function handleTouchMoveRotate(event) {
  32965. if (event.touches.length == 1) {
  32966. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  32967. } else {
  32968. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32969. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32970. rotateEnd.set(x, y);
  32971. }
  32972. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32973. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32974. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32975. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32976. rotateStart.copy(rotateEnd);
  32977. }
  32978. function handleTouchMovePan(event) {
  32979. if (event.touches.length == 1) {
  32980. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  32981. } else {
  32982. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32983. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32984. panEnd.set(x, y);
  32985. }
  32986. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32987. pan(panDelta.x, panDelta.y);
  32988. panStart.copy(panEnd);
  32989. }
  32990. function handleTouchMoveDolly(event) {
  32991. var dx = event.touches[0].pageX - event.touches[1].pageX;
  32992. var dy = event.touches[0].pageY - event.touches[1].pageY;
  32993. var distance = Math.sqrt(dx * dx + dy * dy);
  32994. dollyEnd.set(0, distance);
  32995. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  32996. dollyIn(dollyDelta.y);
  32997. dollyStart.copy(dollyEnd);
  32998. }
  32999. function handleTouchMoveDollyPan(event) {
  33000. if (scope.enableZoom) handleTouchMoveDolly(event);
  33001. if (scope.enablePan) handleTouchMovePan(event);
  33002. }
  33003. function handleTouchMoveDollyRotate(event) {
  33004. if (scope.enableZoom) handleTouchMoveDolly(event);
  33005. if (scope.enableRotate) handleTouchMoveRotate(event);
  33006. }
  33007. function handleTouchEnd()
  33008. /*event*/
  33009. {} // no-op
  33010. //
  33011. // event handlers - FSM: listen for events and reset state
  33012. //
  33013. function onMouseDown(event) {
  33014. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33015. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33016. // prevents the browser from setting it automatically.
  33017. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33018. switch (event.button) {
  33019. case 0:
  33020. switch (scope.mouseButtons.LEFT) {
  33021. case _threeModule.MOUSE.ROTATE:
  33022. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33023. if (scope.enablePan === false) return;
  33024. handleMouseDownPan(event);
  33025. state = STATE.PAN;
  33026. } else {
  33027. if (scope.enableRotate === false) return;
  33028. handleMouseDownRotate(event);
  33029. state = STATE.ROTATE;
  33030. }
  33031. break;
  33032. case _threeModule.MOUSE.PAN:
  33033. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33034. if (scope.enableRotate === false) return;
  33035. handleMouseDownRotate(event);
  33036. state = STATE.ROTATE;
  33037. } else {
  33038. if (scope.enablePan === false) return;
  33039. handleMouseDownPan(event);
  33040. state = STATE.PAN;
  33041. }
  33042. break;
  33043. default:
  33044. state = STATE.NONE;
  33045. }
  33046. break;
  33047. case 1:
  33048. switch (scope.mouseButtons.MIDDLE) {
  33049. case _threeModule.MOUSE.DOLLY:
  33050. if (scope.enableZoom === false) return;
  33051. handleMouseDownDolly(event);
  33052. state = STATE.DOLLY;
  33053. break;
  33054. default:
  33055. state = STATE.NONE;
  33056. }
  33057. break;
  33058. case 2:
  33059. switch (scope.mouseButtons.RIGHT) {
  33060. case _threeModule.MOUSE.ROTATE:
  33061. if (scope.enableRotate === false) return;
  33062. handleMouseDownRotate(event);
  33063. state = STATE.ROTATE;
  33064. break;
  33065. case _threeModule.MOUSE.PAN:
  33066. if (scope.enablePan === false) return;
  33067. handleMouseDownPan(event);
  33068. state = STATE.PAN;
  33069. break;
  33070. default:
  33071. state = STATE.NONE;
  33072. }
  33073. break;
  33074. }
  33075. if (state !== STATE.NONE) {
  33076. document.addEventListener('mousemove', onMouseMove, false);
  33077. document.addEventListener('mouseup', onMouseUp, false);
  33078. scope.dispatchEvent(startEvent);
  33079. }
  33080. }
  33081. function onMouseMove(event) {
  33082. if (scope.enabled === false) return;
  33083. event.preventDefault();
  33084. switch (state) {
  33085. case STATE.ROTATE:
  33086. if (scope.enableRotate === false) return;
  33087. handleMouseMoveRotate(event);
  33088. break;
  33089. case STATE.DOLLY:
  33090. if (scope.enableZoom === false) return;
  33091. handleMouseMoveDolly(event);
  33092. break;
  33093. case STATE.PAN:
  33094. if (scope.enablePan === false) return;
  33095. handleMouseMovePan(event);
  33096. break;
  33097. }
  33098. }
  33099. function onMouseUp(event) {
  33100. if (scope.enabled === false) return;
  33101. handleMouseUp(event);
  33102. document.removeEventListener('mousemove', onMouseMove, false);
  33103. document.removeEventListener('mouseup', onMouseUp, false);
  33104. scope.dispatchEvent(endEvent);
  33105. state = STATE.NONE;
  33106. }
  33107. function onMouseWheel(event) {
  33108. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33109. event.preventDefault();
  33110. event.stopPropagation();
  33111. scope.dispatchEvent(startEvent);
  33112. handleMouseWheel(event);
  33113. scope.dispatchEvent(endEvent);
  33114. }
  33115. function onKeyDown(event) {
  33116. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33117. handleKeyDown(event);
  33118. }
  33119. function onTouchStart(event) {
  33120. if (scope.enabled === false) return;
  33121. event.preventDefault();
  33122. switch (event.touches.length) {
  33123. case 1:
  33124. switch (scope.touches.ONE) {
  33125. case _threeModule.TOUCH.ROTATE:
  33126. if (scope.enableRotate === false) return;
  33127. handleTouchStartRotate(event);
  33128. state = STATE.TOUCH_ROTATE;
  33129. break;
  33130. case _threeModule.TOUCH.PAN:
  33131. if (scope.enablePan === false) return;
  33132. handleTouchStartPan(event);
  33133. state = STATE.TOUCH_PAN;
  33134. break;
  33135. default:
  33136. state = STATE.NONE;
  33137. }
  33138. break;
  33139. case 2:
  33140. switch (scope.touches.TWO) {
  33141. case _threeModule.TOUCH.DOLLY_PAN:
  33142. if (scope.enableZoom === false && scope.enablePan === false) return;
  33143. handleTouchStartDollyPan(event);
  33144. state = STATE.TOUCH_DOLLY_PAN;
  33145. break;
  33146. case _threeModule.TOUCH.DOLLY_ROTATE:
  33147. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33148. handleTouchStartDollyRotate(event);
  33149. state = STATE.TOUCH_DOLLY_ROTATE;
  33150. break;
  33151. default:
  33152. state = STATE.NONE;
  33153. }
  33154. break;
  33155. default:
  33156. state = STATE.NONE;
  33157. }
  33158. if (state !== STATE.NONE) {
  33159. scope.dispatchEvent(startEvent);
  33160. }
  33161. }
  33162. function onTouchMove(event) {
  33163. if (scope.enabled === false) return;
  33164. event.preventDefault();
  33165. event.stopPropagation();
  33166. switch (state) {
  33167. case STATE.TOUCH_ROTATE:
  33168. if (scope.enableRotate === false) return;
  33169. handleTouchMoveRotate(event);
  33170. scope.update();
  33171. break;
  33172. case STATE.TOUCH_PAN:
  33173. if (scope.enablePan === false) return;
  33174. handleTouchMovePan(event);
  33175. scope.update();
  33176. break;
  33177. case STATE.TOUCH_DOLLY_PAN:
  33178. if (scope.enableZoom === false && scope.enablePan === false) return;
  33179. handleTouchMoveDollyPan(event);
  33180. scope.update();
  33181. break;
  33182. case STATE.TOUCH_DOLLY_ROTATE:
  33183. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33184. handleTouchMoveDollyRotate(event);
  33185. scope.update();
  33186. break;
  33187. default:
  33188. state = STATE.NONE;
  33189. }
  33190. }
  33191. function onTouchEnd(event) {
  33192. if (scope.enabled === false) return;
  33193. handleTouchEnd(event);
  33194. scope.dispatchEvent(endEvent);
  33195. state = STATE.NONE;
  33196. }
  33197. function onContextMenu(event) {
  33198. if (scope.enabled === false) return;
  33199. event.preventDefault();
  33200. } //
  33201. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33202. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33203. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33204. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33205. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33206. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33207. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33208. this.update();
  33209. };
  33210. exports.OrbitControls = OrbitControls;
  33211. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33212. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33213. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33214. // This is very similar to OrbitControls, another set of touch behavior
  33215. //
  33216. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33217. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33218. // Pan - left mouse, or arrow keys / touch: one-finger move
  33219. var MapControls = function (object, domElement) {
  33220. OrbitControls.call(this, object, domElement);
  33221. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33222. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33223. this.touches.ONE = _threeModule.TOUCH.PAN;
  33224. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33225. };
  33226. exports.MapControls = MapControls;
  33227. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33228. MapControls.prototype.constructor = MapControls;
  33229. },{"../../../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) {
  33230. "use strict";
  33231. Object.defineProperty(exports, "__esModule", {
  33232. value: true
  33233. });
  33234. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  33235. /**
  33236. * dat-gui JavaScript Controller Library
  33237. * http://code.google.com/p/dat-gui
  33238. *
  33239. * Copyright 2011 Data Arts Team, Google Creative Lab
  33240. *
  33241. * Licensed under the Apache License, Version 2.0 (the "License");
  33242. * you may not use this file except in compliance with the License.
  33243. * You may obtain a copy of the License at
  33244. *
  33245. * http://www.apache.org/licenses/LICENSE-2.0
  33246. */
  33247. function ___$insertStyle(css) {
  33248. if (!css) {
  33249. return;
  33250. }
  33251. if (typeof window === 'undefined') {
  33252. return;
  33253. }
  33254. var style = document.createElement('style');
  33255. style.setAttribute('type', 'text/css');
  33256. style.innerHTML = css;
  33257. document.head.appendChild(style);
  33258. return css;
  33259. }
  33260. function colorToString(color, forceCSSHex) {
  33261. var colorFormat = color.__state.conversionName.toString();
  33262. var r = Math.round(color.r);
  33263. var g = Math.round(color.g);
  33264. var b = Math.round(color.b);
  33265. var a = color.a;
  33266. var h = Math.round(color.h);
  33267. var s = color.s.toFixed(1);
  33268. var v = color.v.toFixed(1);
  33269. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  33270. var str = color.hex.toString(16);
  33271. while (str.length < 6) {
  33272. str = '0' + str;
  33273. }
  33274. return '#' + str;
  33275. } else if (colorFormat === 'CSS_RGB') {
  33276. return 'rgb(' + r + ',' + g + ',' + b + ')';
  33277. } else if (colorFormat === 'CSS_RGBA') {
  33278. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  33279. } else if (colorFormat === 'HEX') {
  33280. return '0x' + color.hex.toString(16);
  33281. } else if (colorFormat === 'RGB_ARRAY') {
  33282. return '[' + r + ',' + g + ',' + b + ']';
  33283. } else if (colorFormat === 'RGBA_ARRAY') {
  33284. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  33285. } else if (colorFormat === 'RGB_OBJ') {
  33286. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  33287. } else if (colorFormat === 'RGBA_OBJ') {
  33288. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  33289. } else if (colorFormat === 'HSV_OBJ') {
  33290. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  33291. } else if (colorFormat === 'HSVA_OBJ') {
  33292. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  33293. }
  33294. return 'unknown format';
  33295. }
  33296. var ARR_EACH = Array.prototype.forEach;
  33297. var ARR_SLICE = Array.prototype.slice;
  33298. var Common = {
  33299. BREAK: {},
  33300. extend: function extend(target) {
  33301. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33302. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33303. keys.forEach(function (key) {
  33304. if (!this.isUndefined(obj[key])) {
  33305. target[key] = obj[key];
  33306. }
  33307. }.bind(this));
  33308. }, this);
  33309. return target;
  33310. },
  33311. defaults: function defaults(target) {
  33312. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33313. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33314. keys.forEach(function (key) {
  33315. if (this.isUndefined(target[key])) {
  33316. target[key] = obj[key];
  33317. }
  33318. }.bind(this));
  33319. }, this);
  33320. return target;
  33321. },
  33322. compose: function compose() {
  33323. var toCall = ARR_SLICE.call(arguments);
  33324. return function () {
  33325. var args = ARR_SLICE.call(arguments);
  33326. for (var i = toCall.length - 1; i >= 0; i--) {
  33327. args = [toCall[i].apply(this, args)];
  33328. }
  33329. return args[0];
  33330. };
  33331. },
  33332. each: function each(obj, itr, scope) {
  33333. if (!obj) {
  33334. return;
  33335. }
  33336. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  33337. obj.forEach(itr, scope);
  33338. } else if (obj.length === obj.length + 0) {
  33339. var key = void 0;
  33340. var l = void 0;
  33341. for (key = 0, l = obj.length; key < l; key++) {
  33342. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  33343. return;
  33344. }
  33345. }
  33346. } else {
  33347. for (var _key in obj) {
  33348. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  33349. return;
  33350. }
  33351. }
  33352. }
  33353. },
  33354. defer: function defer(fnc) {
  33355. setTimeout(fnc, 0);
  33356. },
  33357. debounce: function debounce(func, threshold, callImmediately) {
  33358. var timeout = void 0;
  33359. return function () {
  33360. var obj = this;
  33361. var args = arguments;
  33362. function delayed() {
  33363. timeout = null;
  33364. if (!callImmediately) func.apply(obj, args);
  33365. }
  33366. var callNow = callImmediately || !timeout;
  33367. clearTimeout(timeout);
  33368. timeout = setTimeout(delayed, threshold);
  33369. if (callNow) {
  33370. func.apply(obj, args);
  33371. }
  33372. };
  33373. },
  33374. toArray: function toArray(obj) {
  33375. if (obj.toArray) return obj.toArray();
  33376. return ARR_SLICE.call(obj);
  33377. },
  33378. isUndefined: function isUndefined(obj) {
  33379. return obj === undefined;
  33380. },
  33381. isNull: function isNull(obj) {
  33382. return obj === null;
  33383. },
  33384. isNaN: function (_isNaN) {
  33385. function isNaN() {
  33386. return _isNaN.apply(this, arguments);
  33387. }
  33388. isNaN.toString = function () {
  33389. return _isNaN.toString();
  33390. };
  33391. return isNaN;
  33392. }(function (obj) {
  33393. return isNaN(obj);
  33394. }),
  33395. isArray: Array.isArray || function (obj) {
  33396. return obj.constructor === Array;
  33397. },
  33398. isObject: function isObject(obj) {
  33399. return obj === Object(obj);
  33400. },
  33401. isNumber: function isNumber(obj) {
  33402. return obj === obj + 0;
  33403. },
  33404. isString: function isString(obj) {
  33405. return obj === obj + '';
  33406. },
  33407. isBoolean: function isBoolean(obj) {
  33408. return obj === false || obj === true;
  33409. },
  33410. isFunction: function isFunction(obj) {
  33411. return Object.prototype.toString.call(obj) === '[object Function]';
  33412. }
  33413. };
  33414. var INTERPRETATIONS = [{
  33415. litmus: Common.isString,
  33416. conversions: {
  33417. THREE_CHAR_HEX: {
  33418. read: function read(original) {
  33419. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  33420. if (test === null) {
  33421. return false;
  33422. }
  33423. return {
  33424. space: 'HEX',
  33425. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  33426. };
  33427. },
  33428. write: colorToString
  33429. },
  33430. SIX_CHAR_HEX: {
  33431. read: function read(original) {
  33432. var test = original.match(/^#([A-F0-9]{6})$/i);
  33433. if (test === null) {
  33434. return false;
  33435. }
  33436. return {
  33437. space: 'HEX',
  33438. hex: parseInt('0x' + test[1].toString(), 0)
  33439. };
  33440. },
  33441. write: colorToString
  33442. },
  33443. CSS_RGB: {
  33444. read: function read(original) {
  33445. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33446. if (test === null) {
  33447. return false;
  33448. }
  33449. return {
  33450. space: 'RGB',
  33451. r: parseFloat(test[1]),
  33452. g: parseFloat(test[2]),
  33453. b: parseFloat(test[3])
  33454. };
  33455. },
  33456. write: colorToString
  33457. },
  33458. CSS_RGBA: {
  33459. read: function read(original) {
  33460. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33461. if (test === null) {
  33462. return false;
  33463. }
  33464. return {
  33465. space: 'RGB',
  33466. r: parseFloat(test[1]),
  33467. g: parseFloat(test[2]),
  33468. b: parseFloat(test[3]),
  33469. a: parseFloat(test[4])
  33470. };
  33471. },
  33472. write: colorToString
  33473. }
  33474. }
  33475. }, {
  33476. litmus: Common.isNumber,
  33477. conversions: {
  33478. HEX: {
  33479. read: function read(original) {
  33480. return {
  33481. space: 'HEX',
  33482. hex: original,
  33483. conversionName: 'HEX'
  33484. };
  33485. },
  33486. write: function write(color) {
  33487. return color.hex;
  33488. }
  33489. }
  33490. }
  33491. }, {
  33492. litmus: Common.isArray,
  33493. conversions: {
  33494. RGB_ARRAY: {
  33495. read: function read(original) {
  33496. if (original.length !== 3) {
  33497. return false;
  33498. }
  33499. return {
  33500. space: 'RGB',
  33501. r: original[0],
  33502. g: original[1],
  33503. b: original[2]
  33504. };
  33505. },
  33506. write: function write(color) {
  33507. return [color.r, color.g, color.b];
  33508. }
  33509. },
  33510. RGBA_ARRAY: {
  33511. read: function read(original) {
  33512. if (original.length !== 4) return false;
  33513. return {
  33514. space: 'RGB',
  33515. r: original[0],
  33516. g: original[1],
  33517. b: original[2],
  33518. a: original[3]
  33519. };
  33520. },
  33521. write: function write(color) {
  33522. return [color.r, color.g, color.b, color.a];
  33523. }
  33524. }
  33525. }
  33526. }, {
  33527. litmus: Common.isObject,
  33528. conversions: {
  33529. RGBA_OBJ: {
  33530. read: function read(original) {
  33531. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  33532. return {
  33533. space: 'RGB',
  33534. r: original.r,
  33535. g: original.g,
  33536. b: original.b,
  33537. a: original.a
  33538. };
  33539. }
  33540. return false;
  33541. },
  33542. write: function write(color) {
  33543. return {
  33544. r: color.r,
  33545. g: color.g,
  33546. b: color.b,
  33547. a: color.a
  33548. };
  33549. }
  33550. },
  33551. RGB_OBJ: {
  33552. read: function read(original) {
  33553. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  33554. return {
  33555. space: 'RGB',
  33556. r: original.r,
  33557. g: original.g,
  33558. b: original.b
  33559. };
  33560. }
  33561. return false;
  33562. },
  33563. write: function write(color) {
  33564. return {
  33565. r: color.r,
  33566. g: color.g,
  33567. b: color.b
  33568. };
  33569. }
  33570. },
  33571. HSVA_OBJ: {
  33572. read: function read(original) {
  33573. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  33574. return {
  33575. space: 'HSV',
  33576. h: original.h,
  33577. s: original.s,
  33578. v: original.v,
  33579. a: original.a
  33580. };
  33581. }
  33582. return false;
  33583. },
  33584. write: function write(color) {
  33585. return {
  33586. h: color.h,
  33587. s: color.s,
  33588. v: color.v,
  33589. a: color.a
  33590. };
  33591. }
  33592. },
  33593. HSV_OBJ: {
  33594. read: function read(original) {
  33595. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  33596. return {
  33597. space: 'HSV',
  33598. h: original.h,
  33599. s: original.s,
  33600. v: original.v
  33601. };
  33602. }
  33603. return false;
  33604. },
  33605. write: function write(color) {
  33606. return {
  33607. h: color.h,
  33608. s: color.s,
  33609. v: color.v
  33610. };
  33611. }
  33612. }
  33613. }
  33614. }];
  33615. var result = void 0;
  33616. var toReturn = void 0;
  33617. var interpret = function interpret() {
  33618. toReturn = false;
  33619. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  33620. Common.each(INTERPRETATIONS, function (family) {
  33621. if (family.litmus(original)) {
  33622. Common.each(family.conversions, function (conversion, conversionName) {
  33623. result = conversion.read(original);
  33624. if (toReturn === false && result !== false) {
  33625. toReturn = result;
  33626. result.conversionName = conversionName;
  33627. result.conversion = conversion;
  33628. return Common.BREAK;
  33629. }
  33630. });
  33631. return Common.BREAK;
  33632. }
  33633. });
  33634. return toReturn;
  33635. };
  33636. var tmpComponent = void 0;
  33637. var ColorMath = {
  33638. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  33639. var hi = Math.floor(h / 60) % 6;
  33640. var f = h / 60 - Math.floor(h / 60);
  33641. var p = v * (1.0 - s);
  33642. var q = v * (1.0 - f * s);
  33643. var t = v * (1.0 - (1.0 - f) * s);
  33644. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  33645. return {
  33646. r: c[0] * 255,
  33647. g: c[1] * 255,
  33648. b: c[2] * 255
  33649. };
  33650. },
  33651. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  33652. var min = Math.min(r, g, b);
  33653. var max = Math.max(r, g, b);
  33654. var delta = max - min;
  33655. var h = void 0;
  33656. var s = void 0;
  33657. if (max !== 0) {
  33658. s = delta / max;
  33659. } else {
  33660. return {
  33661. h: NaN,
  33662. s: 0,
  33663. v: 0
  33664. };
  33665. }
  33666. if (r === max) {
  33667. h = (g - b) / delta;
  33668. } else if (g === max) {
  33669. h = 2 + (b - r) / delta;
  33670. } else {
  33671. h = 4 + (r - g) / delta;
  33672. }
  33673. h /= 6;
  33674. if (h < 0) {
  33675. h += 1;
  33676. }
  33677. return {
  33678. h: h * 360,
  33679. s: s,
  33680. v: max / 255
  33681. };
  33682. },
  33683. rgb_to_hex: function rgb_to_hex(r, g, b) {
  33684. var hex = this.hex_with_component(0, 2, r);
  33685. hex = this.hex_with_component(hex, 1, g);
  33686. hex = this.hex_with_component(hex, 0, b);
  33687. return hex;
  33688. },
  33689. component_from_hex: function component_from_hex(hex, componentIndex) {
  33690. return hex >> componentIndex * 8 & 0xFF;
  33691. },
  33692. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  33693. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  33694. }
  33695. };
  33696. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  33697. return typeof obj;
  33698. } : function (obj) {
  33699. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  33700. };
  33701. var classCallCheck = function (instance, Constructor) {
  33702. if (!(instance instanceof Constructor)) {
  33703. throw new TypeError("Cannot call a class as a function");
  33704. }
  33705. };
  33706. var createClass = function () {
  33707. function defineProperties(target, props) {
  33708. for (var i = 0; i < props.length; i++) {
  33709. var descriptor = props[i];
  33710. descriptor.enumerable = descriptor.enumerable || false;
  33711. descriptor.configurable = true;
  33712. if ("value" in descriptor) descriptor.writable = true;
  33713. Object.defineProperty(target, descriptor.key, descriptor);
  33714. }
  33715. }
  33716. return function (Constructor, protoProps, staticProps) {
  33717. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33718. if (staticProps) defineProperties(Constructor, staticProps);
  33719. return Constructor;
  33720. };
  33721. }();
  33722. var get = function get(object, property, receiver) {
  33723. if (object === null) object = Function.prototype;
  33724. var desc = Object.getOwnPropertyDescriptor(object, property);
  33725. if (desc === undefined) {
  33726. var parent = Object.getPrototypeOf(object);
  33727. if (parent === null) {
  33728. return undefined;
  33729. } else {
  33730. return get(parent, property, receiver);
  33731. }
  33732. } else if ("value" in desc) {
  33733. return desc.value;
  33734. } else {
  33735. var getter = desc.get;
  33736. if (getter === undefined) {
  33737. return undefined;
  33738. }
  33739. return getter.call(receiver);
  33740. }
  33741. };
  33742. var inherits = function (subClass, superClass) {
  33743. if (typeof superClass !== "function" && superClass !== null) {
  33744. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  33745. }
  33746. subClass.prototype = Object.create(superClass && superClass.prototype, {
  33747. constructor: {
  33748. value: subClass,
  33749. enumerable: false,
  33750. writable: true,
  33751. configurable: true
  33752. }
  33753. });
  33754. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  33755. };
  33756. var possibleConstructorReturn = function (self, call) {
  33757. if (!self) {
  33758. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  33759. }
  33760. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  33761. };
  33762. var Color = function () {
  33763. function Color() {
  33764. classCallCheck(this, Color);
  33765. this.__state = interpret.apply(this, arguments);
  33766. if (this.__state === false) {
  33767. throw new Error('Failed to interpret color arguments');
  33768. }
  33769. this.__state.a = this.__state.a || 1;
  33770. }
  33771. createClass(Color, [{
  33772. key: 'toString',
  33773. value: function toString() {
  33774. return colorToString(this);
  33775. }
  33776. }, {
  33777. key: 'toHexString',
  33778. value: function toHexString() {
  33779. return colorToString(this, true);
  33780. }
  33781. }, {
  33782. key: 'toOriginal',
  33783. value: function toOriginal() {
  33784. return this.__state.conversion.write(this);
  33785. }
  33786. }]);
  33787. return Color;
  33788. }();
  33789. function defineRGBComponent(target, component, componentHexIndex) {
  33790. Object.defineProperty(target, component, {
  33791. get: function get$$1() {
  33792. if (this.__state.space === 'RGB') {
  33793. return this.__state[component];
  33794. }
  33795. Color.recalculateRGB(this, component, componentHexIndex);
  33796. return this.__state[component];
  33797. },
  33798. set: function set$$1(v) {
  33799. if (this.__state.space !== 'RGB') {
  33800. Color.recalculateRGB(this, component, componentHexIndex);
  33801. this.__state.space = 'RGB';
  33802. }
  33803. this.__state[component] = v;
  33804. }
  33805. });
  33806. }
  33807. function defineHSVComponent(target, component) {
  33808. Object.defineProperty(target, component, {
  33809. get: function get$$1() {
  33810. if (this.__state.space === 'HSV') {
  33811. return this.__state[component];
  33812. }
  33813. Color.recalculateHSV(this);
  33814. return this.__state[component];
  33815. },
  33816. set: function set$$1(v) {
  33817. if (this.__state.space !== 'HSV') {
  33818. Color.recalculateHSV(this);
  33819. this.__state.space = 'HSV';
  33820. }
  33821. this.__state[component] = v;
  33822. }
  33823. });
  33824. }
  33825. Color.recalculateRGB = function (color, component, componentHexIndex) {
  33826. if (color.__state.space === 'HEX') {
  33827. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  33828. } else if (color.__state.space === 'HSV') {
  33829. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  33830. } else {
  33831. throw new Error('Corrupted color state');
  33832. }
  33833. };
  33834. Color.recalculateHSV = function (color) {
  33835. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  33836. Common.extend(color.__state, {
  33837. s: result.s,
  33838. v: result.v
  33839. });
  33840. if (!Common.isNaN(result.h)) {
  33841. color.__state.h = result.h;
  33842. } else if (Common.isUndefined(color.__state.h)) {
  33843. color.__state.h = 0;
  33844. }
  33845. };
  33846. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  33847. defineRGBComponent(Color.prototype, 'r', 2);
  33848. defineRGBComponent(Color.prototype, 'g', 1);
  33849. defineRGBComponent(Color.prototype, 'b', 0);
  33850. defineHSVComponent(Color.prototype, 'h');
  33851. defineHSVComponent(Color.prototype, 's');
  33852. defineHSVComponent(Color.prototype, 'v');
  33853. Object.defineProperty(Color.prototype, 'a', {
  33854. get: function get$$1() {
  33855. return this.__state.a;
  33856. },
  33857. set: function set$$1(v) {
  33858. this.__state.a = v;
  33859. }
  33860. });
  33861. Object.defineProperty(Color.prototype, 'hex', {
  33862. get: function get$$1() {
  33863. if (!this.__state.space !== 'HEX') {
  33864. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  33865. }
  33866. return this.__state.hex;
  33867. },
  33868. set: function set$$1(v) {
  33869. this.__state.space = 'HEX';
  33870. this.__state.hex = v;
  33871. }
  33872. });
  33873. var Controller = function () {
  33874. function Controller(object, property) {
  33875. classCallCheck(this, Controller);
  33876. this.initialValue = object[property];
  33877. this.domElement = document.createElement('div');
  33878. this.object = object;
  33879. this.property = property;
  33880. this.__onChange = undefined;
  33881. this.__onFinishChange = undefined;
  33882. }
  33883. createClass(Controller, [{
  33884. key: 'onChange',
  33885. value: function onChange(fnc) {
  33886. this.__onChange = fnc;
  33887. return this;
  33888. }
  33889. }, {
  33890. key: 'onFinishChange',
  33891. value: function onFinishChange(fnc) {
  33892. this.__onFinishChange = fnc;
  33893. return this;
  33894. }
  33895. }, {
  33896. key: 'setValue',
  33897. value: function setValue(newValue) {
  33898. this.object[this.property] = newValue;
  33899. if (this.__onChange) {
  33900. this.__onChange.call(this, newValue);
  33901. }
  33902. this.updateDisplay();
  33903. return this;
  33904. }
  33905. }, {
  33906. key: 'getValue',
  33907. value: function getValue() {
  33908. return this.object[this.property];
  33909. }
  33910. }, {
  33911. key: 'updateDisplay',
  33912. value: function updateDisplay() {
  33913. return this;
  33914. }
  33915. }, {
  33916. key: 'isModified',
  33917. value: function isModified() {
  33918. return this.initialValue !== this.getValue();
  33919. }
  33920. }]);
  33921. return Controller;
  33922. }();
  33923. var EVENT_MAP = {
  33924. HTMLEvents: ['change'],
  33925. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  33926. KeyboardEvents: ['keydown']
  33927. };
  33928. var EVENT_MAP_INV = {};
  33929. Common.each(EVENT_MAP, function (v, k) {
  33930. Common.each(v, function (e) {
  33931. EVENT_MAP_INV[e] = k;
  33932. });
  33933. });
  33934. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  33935. function cssValueToPixels(val) {
  33936. if (val === '0' || Common.isUndefined(val)) {
  33937. return 0;
  33938. }
  33939. var match = val.match(CSS_VALUE_PIXELS);
  33940. if (!Common.isNull(match)) {
  33941. return parseFloat(match[1]);
  33942. }
  33943. return 0;
  33944. }
  33945. var dom = {
  33946. makeSelectable: function makeSelectable(elem, selectable) {
  33947. if (elem === undefined || elem.style === undefined) return;
  33948. elem.onselectstart = selectable ? function () {
  33949. return false;
  33950. } : function () {};
  33951. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  33952. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  33953. elem.unselectable = selectable ? 'on' : 'off';
  33954. },
  33955. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  33956. var vertical = vert;
  33957. var horizontal = hor;
  33958. if (Common.isUndefined(horizontal)) {
  33959. horizontal = true;
  33960. }
  33961. if (Common.isUndefined(vertical)) {
  33962. vertical = true;
  33963. }
  33964. elem.style.position = 'absolute';
  33965. if (horizontal) {
  33966. elem.style.left = 0;
  33967. elem.style.right = 0;
  33968. }
  33969. if (vertical) {
  33970. elem.style.top = 0;
  33971. elem.style.bottom = 0;
  33972. }
  33973. },
  33974. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  33975. var params = pars || {};
  33976. var className = EVENT_MAP_INV[eventType];
  33977. if (!className) {
  33978. throw new Error('Event type ' + eventType + ' not supported.');
  33979. }
  33980. var evt = document.createEvent(className);
  33981. switch (className) {
  33982. case 'MouseEvents':
  33983. {
  33984. var clientX = params.x || params.clientX || 0;
  33985. var clientY = params.y || params.clientY || 0;
  33986. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  33987. break;
  33988. }
  33989. case 'KeyboardEvents':
  33990. {
  33991. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  33992. Common.defaults(params, {
  33993. cancelable: true,
  33994. ctrlKey: false,
  33995. altKey: false,
  33996. shiftKey: false,
  33997. metaKey: false,
  33998. keyCode: undefined,
  33999. charCode: undefined
  34000. });
  34001. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34002. break;
  34003. }
  34004. default:
  34005. {
  34006. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34007. break;
  34008. }
  34009. }
  34010. Common.defaults(evt, aux);
  34011. elem.dispatchEvent(evt);
  34012. },
  34013. bind: function bind(elem, event, func, newBool) {
  34014. var bool = newBool || false;
  34015. if (elem.addEventListener) {
  34016. elem.addEventListener(event, func, bool);
  34017. } else if (elem.attachEvent) {
  34018. elem.attachEvent('on' + event, func);
  34019. }
  34020. return dom;
  34021. },
  34022. unbind: function unbind(elem, event, func, newBool) {
  34023. var bool = newBool || false;
  34024. if (elem.removeEventListener) {
  34025. elem.removeEventListener(event, func, bool);
  34026. } else if (elem.detachEvent) {
  34027. elem.detachEvent('on' + event, func);
  34028. }
  34029. return dom;
  34030. },
  34031. addClass: function addClass(elem, className) {
  34032. if (elem.className === undefined) {
  34033. elem.className = className;
  34034. } else if (elem.className !== className) {
  34035. var classes = elem.className.split(/ +/);
  34036. if (classes.indexOf(className) === -1) {
  34037. classes.push(className);
  34038. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34039. }
  34040. }
  34041. return dom;
  34042. },
  34043. removeClass: function removeClass(elem, className) {
  34044. if (className) {
  34045. if (elem.className === className) {
  34046. elem.removeAttribute('class');
  34047. } else {
  34048. var classes = elem.className.split(/ +/);
  34049. var index = classes.indexOf(className);
  34050. if (index !== -1) {
  34051. classes.splice(index, 1);
  34052. elem.className = classes.join(' ');
  34053. }
  34054. }
  34055. } else {
  34056. elem.className = undefined;
  34057. }
  34058. return dom;
  34059. },
  34060. hasClass: function hasClass(elem, className) {
  34061. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34062. },
  34063. getWidth: function getWidth(elem) {
  34064. var style = getComputedStyle(elem);
  34065. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34066. },
  34067. getHeight: function getHeight(elem) {
  34068. var style = getComputedStyle(elem);
  34069. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34070. },
  34071. getOffset: function getOffset(el) {
  34072. var elem = el;
  34073. var offset = {
  34074. left: 0,
  34075. top: 0
  34076. };
  34077. if (elem.offsetParent) {
  34078. do {
  34079. offset.left += elem.offsetLeft;
  34080. offset.top += elem.offsetTop;
  34081. elem = elem.offsetParent;
  34082. } while (elem);
  34083. }
  34084. return offset;
  34085. },
  34086. isActive: function isActive(elem) {
  34087. return elem === document.activeElement && (elem.type || elem.href);
  34088. }
  34089. };
  34090. var BooleanController = function (_Controller) {
  34091. inherits(BooleanController, _Controller);
  34092. function BooleanController(object, property) {
  34093. classCallCheck(this, BooleanController);
  34094. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  34095. var _this = _this2;
  34096. _this2.__prev = _this2.getValue();
  34097. _this2.__checkbox = document.createElement('input');
  34098. _this2.__checkbox.setAttribute('type', 'checkbox');
  34099. function onChange() {
  34100. _this.setValue(!_this.__prev);
  34101. }
  34102. dom.bind(_this2.__checkbox, 'change', onChange, false);
  34103. _this2.domElement.appendChild(_this2.__checkbox);
  34104. _this2.updateDisplay();
  34105. return _this2;
  34106. }
  34107. createClass(BooleanController, [{
  34108. key: 'setValue',
  34109. value: function setValue(v) {
  34110. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  34111. if (this.__onFinishChange) {
  34112. this.__onFinishChange.call(this, this.getValue());
  34113. }
  34114. this.__prev = this.getValue();
  34115. return toReturn;
  34116. }
  34117. }, {
  34118. key: 'updateDisplay',
  34119. value: function updateDisplay() {
  34120. if (this.getValue() === true) {
  34121. this.__checkbox.setAttribute('checked', 'checked');
  34122. this.__checkbox.checked = true;
  34123. this.__prev = true;
  34124. } else {
  34125. this.__checkbox.checked = false;
  34126. this.__prev = false;
  34127. }
  34128. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  34129. }
  34130. }]);
  34131. return BooleanController;
  34132. }(Controller);
  34133. var OptionController = function (_Controller) {
  34134. inherits(OptionController, _Controller);
  34135. function OptionController(object, property, opts) {
  34136. classCallCheck(this, OptionController);
  34137. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  34138. var options = opts;
  34139. var _this = _this2;
  34140. _this2.__select = document.createElement('select');
  34141. if (Common.isArray(options)) {
  34142. var map = {};
  34143. Common.each(options, function (element) {
  34144. map[element] = element;
  34145. });
  34146. options = map;
  34147. }
  34148. Common.each(options, function (value, key) {
  34149. var opt = document.createElement('option');
  34150. opt.innerHTML = key;
  34151. opt.setAttribute('value', value);
  34152. _this.__select.appendChild(opt);
  34153. });
  34154. _this2.updateDisplay();
  34155. dom.bind(_this2.__select, 'change', function () {
  34156. var desiredValue = this.options[this.selectedIndex].value;
  34157. _this.setValue(desiredValue);
  34158. });
  34159. _this2.domElement.appendChild(_this2.__select);
  34160. return _this2;
  34161. }
  34162. createClass(OptionController, [{
  34163. key: 'setValue',
  34164. value: function setValue(v) {
  34165. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  34166. if (this.__onFinishChange) {
  34167. this.__onFinishChange.call(this, this.getValue());
  34168. }
  34169. return toReturn;
  34170. }
  34171. }, {
  34172. key: 'updateDisplay',
  34173. value: function updateDisplay() {
  34174. if (dom.isActive(this.__select)) return this;
  34175. this.__select.value = this.getValue();
  34176. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  34177. }
  34178. }]);
  34179. return OptionController;
  34180. }(Controller);
  34181. var StringController = function (_Controller) {
  34182. inherits(StringController, _Controller);
  34183. function StringController(object, property) {
  34184. classCallCheck(this, StringController);
  34185. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  34186. var _this = _this2;
  34187. function onChange() {
  34188. _this.setValue(_this.__input.value);
  34189. }
  34190. function onBlur() {
  34191. if (_this.__onFinishChange) {
  34192. _this.__onFinishChange.call(_this, _this.getValue());
  34193. }
  34194. }
  34195. _this2.__input = document.createElement('input');
  34196. _this2.__input.setAttribute('type', 'text');
  34197. dom.bind(_this2.__input, 'keyup', onChange);
  34198. dom.bind(_this2.__input, 'change', onChange);
  34199. dom.bind(_this2.__input, 'blur', onBlur);
  34200. dom.bind(_this2.__input, 'keydown', function (e) {
  34201. if (e.keyCode === 13) {
  34202. this.blur();
  34203. }
  34204. });
  34205. _this2.updateDisplay();
  34206. _this2.domElement.appendChild(_this2.__input);
  34207. return _this2;
  34208. }
  34209. createClass(StringController, [{
  34210. key: 'updateDisplay',
  34211. value: function updateDisplay() {
  34212. if (!dom.isActive(this.__input)) {
  34213. this.__input.value = this.getValue();
  34214. }
  34215. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  34216. }
  34217. }]);
  34218. return StringController;
  34219. }(Controller);
  34220. function numDecimals(x) {
  34221. var _x = x.toString();
  34222. if (_x.indexOf('.') > -1) {
  34223. return _x.length - _x.indexOf('.') - 1;
  34224. }
  34225. return 0;
  34226. }
  34227. var NumberController = function (_Controller) {
  34228. inherits(NumberController, _Controller);
  34229. function NumberController(object, property, params) {
  34230. classCallCheck(this, NumberController);
  34231. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  34232. var _params = params || {};
  34233. _this.__min = _params.min;
  34234. _this.__max = _params.max;
  34235. _this.__step = _params.step;
  34236. if (Common.isUndefined(_this.__step)) {
  34237. if (_this.initialValue === 0) {
  34238. _this.__impliedStep = 1;
  34239. } else {
  34240. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  34241. }
  34242. } else {
  34243. _this.__impliedStep = _this.__step;
  34244. }
  34245. _this.__precision = numDecimals(_this.__impliedStep);
  34246. return _this;
  34247. }
  34248. createClass(NumberController, [{
  34249. key: 'setValue',
  34250. value: function setValue(v) {
  34251. var _v = v;
  34252. if (this.__min !== undefined && _v < this.__min) {
  34253. _v = this.__min;
  34254. } else if (this.__max !== undefined && _v > this.__max) {
  34255. _v = this.__max;
  34256. }
  34257. if (this.__step !== undefined && _v % this.__step !== 0) {
  34258. _v = Math.round(_v / this.__step) * this.__step;
  34259. }
  34260. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  34261. }
  34262. }, {
  34263. key: 'min',
  34264. value: function min(minValue) {
  34265. this.__min = minValue;
  34266. return this;
  34267. }
  34268. }, {
  34269. key: 'max',
  34270. value: function max(maxValue) {
  34271. this.__max = maxValue;
  34272. return this;
  34273. }
  34274. }, {
  34275. key: 'step',
  34276. value: function step(stepValue) {
  34277. this.__step = stepValue;
  34278. this.__impliedStep = stepValue;
  34279. this.__precision = numDecimals(stepValue);
  34280. return this;
  34281. }
  34282. }]);
  34283. return NumberController;
  34284. }(Controller);
  34285. function roundToDecimal(value, decimals) {
  34286. var tenTo = Math.pow(10, decimals);
  34287. return Math.round(value * tenTo) / tenTo;
  34288. }
  34289. var NumberControllerBox = function (_NumberController) {
  34290. inherits(NumberControllerBox, _NumberController);
  34291. function NumberControllerBox(object, property, params) {
  34292. classCallCheck(this, NumberControllerBox);
  34293. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  34294. _this2.__truncationSuspended = false;
  34295. var _this = _this2;
  34296. var prevY = void 0;
  34297. function onChange() {
  34298. var attempted = parseFloat(_this.__input.value);
  34299. if (!Common.isNaN(attempted)) {
  34300. _this.setValue(attempted);
  34301. }
  34302. }
  34303. function onFinish() {
  34304. if (_this.__onFinishChange) {
  34305. _this.__onFinishChange.call(_this, _this.getValue());
  34306. }
  34307. }
  34308. function onBlur() {
  34309. onFinish();
  34310. }
  34311. function onMouseDrag(e) {
  34312. var diff = prevY - e.clientY;
  34313. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  34314. prevY = e.clientY;
  34315. }
  34316. function onMouseUp() {
  34317. dom.unbind(window, 'mousemove', onMouseDrag);
  34318. dom.unbind(window, 'mouseup', onMouseUp);
  34319. onFinish();
  34320. }
  34321. function onMouseDown(e) {
  34322. dom.bind(window, 'mousemove', onMouseDrag);
  34323. dom.bind(window, 'mouseup', onMouseUp);
  34324. prevY = e.clientY;
  34325. }
  34326. _this2.__input = document.createElement('input');
  34327. _this2.__input.setAttribute('type', 'text');
  34328. dom.bind(_this2.__input, 'change', onChange);
  34329. dom.bind(_this2.__input, 'blur', onBlur);
  34330. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  34331. dom.bind(_this2.__input, 'keydown', function (e) {
  34332. if (e.keyCode === 13) {
  34333. _this.__truncationSuspended = true;
  34334. this.blur();
  34335. _this.__truncationSuspended = false;
  34336. onFinish();
  34337. }
  34338. });
  34339. _this2.updateDisplay();
  34340. _this2.domElement.appendChild(_this2.__input);
  34341. return _this2;
  34342. }
  34343. createClass(NumberControllerBox, [{
  34344. key: 'updateDisplay',
  34345. value: function updateDisplay() {
  34346. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  34347. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  34348. }
  34349. }]);
  34350. return NumberControllerBox;
  34351. }(NumberController);
  34352. function map(v, i1, i2, o1, o2) {
  34353. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  34354. }
  34355. var NumberControllerSlider = function (_NumberController) {
  34356. inherits(NumberControllerSlider, _NumberController);
  34357. function NumberControllerSlider(object, property, min, max, step) {
  34358. classCallCheck(this, NumberControllerSlider);
  34359. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  34360. min: min,
  34361. max: max,
  34362. step: step
  34363. }));
  34364. var _this = _this2;
  34365. _this2.__background = document.createElement('div');
  34366. _this2.__foreground = document.createElement('div');
  34367. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  34368. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  34369. dom.addClass(_this2.__background, 'slider');
  34370. dom.addClass(_this2.__foreground, 'slider-fg');
  34371. function onMouseDown(e) {
  34372. document.activeElement.blur();
  34373. dom.bind(window, 'mousemove', onMouseDrag);
  34374. dom.bind(window, 'mouseup', onMouseUp);
  34375. onMouseDrag(e);
  34376. }
  34377. function onMouseDrag(e) {
  34378. e.preventDefault();
  34379. var bgRect = _this.__background.getBoundingClientRect();
  34380. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34381. return false;
  34382. }
  34383. function onMouseUp() {
  34384. dom.unbind(window, 'mousemove', onMouseDrag);
  34385. dom.unbind(window, 'mouseup', onMouseUp);
  34386. if (_this.__onFinishChange) {
  34387. _this.__onFinishChange.call(_this, _this.getValue());
  34388. }
  34389. }
  34390. function onTouchStart(e) {
  34391. if (e.touches.length !== 1) {
  34392. return;
  34393. }
  34394. dom.bind(window, 'touchmove', onTouchMove);
  34395. dom.bind(window, 'touchend', onTouchEnd);
  34396. onTouchMove(e);
  34397. }
  34398. function onTouchMove(e) {
  34399. var clientX = e.touches[0].clientX;
  34400. var bgRect = _this.__background.getBoundingClientRect();
  34401. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34402. }
  34403. function onTouchEnd() {
  34404. dom.unbind(window, 'touchmove', onTouchMove);
  34405. dom.unbind(window, 'touchend', onTouchEnd);
  34406. if (_this.__onFinishChange) {
  34407. _this.__onFinishChange.call(_this, _this.getValue());
  34408. }
  34409. }
  34410. _this2.updateDisplay();
  34411. _this2.__background.appendChild(_this2.__foreground);
  34412. _this2.domElement.appendChild(_this2.__background);
  34413. return _this2;
  34414. }
  34415. createClass(NumberControllerSlider, [{
  34416. key: 'updateDisplay',
  34417. value: function updateDisplay() {
  34418. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  34419. this.__foreground.style.width = pct * 100 + '%';
  34420. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  34421. }
  34422. }]);
  34423. return NumberControllerSlider;
  34424. }(NumberController);
  34425. var FunctionController = function (_Controller) {
  34426. inherits(FunctionController, _Controller);
  34427. function FunctionController(object, property, text) {
  34428. classCallCheck(this, FunctionController);
  34429. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  34430. var _this = _this2;
  34431. _this2.__button = document.createElement('div');
  34432. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  34433. dom.bind(_this2.__button, 'click', function (e) {
  34434. e.preventDefault();
  34435. _this.fire();
  34436. return false;
  34437. });
  34438. dom.addClass(_this2.__button, 'button');
  34439. _this2.domElement.appendChild(_this2.__button);
  34440. return _this2;
  34441. }
  34442. createClass(FunctionController, [{
  34443. key: 'fire',
  34444. value: function fire() {
  34445. if (this.__onChange) {
  34446. this.__onChange.call(this);
  34447. }
  34448. this.getValue().call(this.object);
  34449. if (this.__onFinishChange) {
  34450. this.__onFinishChange.call(this, this.getValue());
  34451. }
  34452. }
  34453. }]);
  34454. return FunctionController;
  34455. }(Controller);
  34456. var ColorController = function (_Controller) {
  34457. inherits(ColorController, _Controller);
  34458. function ColorController(object, property) {
  34459. classCallCheck(this, ColorController);
  34460. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  34461. _this2.__color = new Color(_this2.getValue());
  34462. _this2.__temp = new Color(0);
  34463. var _this = _this2;
  34464. _this2.domElement = document.createElement('div');
  34465. dom.makeSelectable(_this2.domElement, false);
  34466. _this2.__selector = document.createElement('div');
  34467. _this2.__selector.className = 'selector';
  34468. _this2.__saturation_field = document.createElement('div');
  34469. _this2.__saturation_field.className = 'saturation-field';
  34470. _this2.__field_knob = document.createElement('div');
  34471. _this2.__field_knob.className = 'field-knob';
  34472. _this2.__field_knob_border = '2px solid ';
  34473. _this2.__hue_knob = document.createElement('div');
  34474. _this2.__hue_knob.className = 'hue-knob';
  34475. _this2.__hue_field = document.createElement('div');
  34476. _this2.__hue_field.className = 'hue-field';
  34477. _this2.__input = document.createElement('input');
  34478. _this2.__input.type = 'text';
  34479. _this2.__input_textShadow = '0 1px 1px ';
  34480. dom.bind(_this2.__input, 'keydown', function (e) {
  34481. if (e.keyCode === 13) {
  34482. onBlur.call(this);
  34483. }
  34484. });
  34485. dom.bind(_this2.__input, 'blur', onBlur);
  34486. dom.bind(_this2.__selector, 'mousedown', function () {
  34487. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  34488. dom.removeClass(_this.__selector, 'drag');
  34489. });
  34490. });
  34491. dom.bind(_this2.__selector, 'touchstart', function () {
  34492. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  34493. dom.removeClass(_this.__selector, 'drag');
  34494. });
  34495. });
  34496. var valueField = document.createElement('div');
  34497. Common.extend(_this2.__selector.style, {
  34498. width: '122px',
  34499. height: '102px',
  34500. padding: '3px',
  34501. backgroundColor: '#222',
  34502. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  34503. });
  34504. Common.extend(_this2.__field_knob.style, {
  34505. position: 'absolute',
  34506. width: '12px',
  34507. height: '12px',
  34508. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  34509. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  34510. borderRadius: '12px',
  34511. zIndex: 1
  34512. });
  34513. Common.extend(_this2.__hue_knob.style, {
  34514. position: 'absolute',
  34515. width: '15px',
  34516. height: '2px',
  34517. borderRight: '4px solid #fff',
  34518. zIndex: 1
  34519. });
  34520. Common.extend(_this2.__saturation_field.style, {
  34521. width: '100px',
  34522. height: '100px',
  34523. border: '1px solid #555',
  34524. marginRight: '3px',
  34525. display: 'inline-block',
  34526. cursor: 'pointer'
  34527. });
  34528. Common.extend(valueField.style, {
  34529. width: '100%',
  34530. height: '100%',
  34531. background: 'none'
  34532. });
  34533. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  34534. Common.extend(_this2.__hue_field.style, {
  34535. width: '15px',
  34536. height: '100px',
  34537. border: '1px solid #555',
  34538. cursor: 'ns-resize',
  34539. position: 'absolute',
  34540. top: '3px',
  34541. right: '3px'
  34542. });
  34543. hueGradient(_this2.__hue_field);
  34544. Common.extend(_this2.__input.style, {
  34545. outline: 'none',
  34546. textAlign: 'center',
  34547. color: '#fff',
  34548. border: 0,
  34549. fontWeight: 'bold',
  34550. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  34551. });
  34552. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  34553. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  34554. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  34555. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  34556. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  34557. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  34558. function fieldDown(e) {
  34559. setSV(e);
  34560. dom.bind(window, 'mousemove', setSV);
  34561. dom.bind(window, 'touchmove', setSV);
  34562. dom.bind(window, 'mouseup', fieldUpSV);
  34563. dom.bind(window, 'touchend', fieldUpSV);
  34564. }
  34565. function fieldDownH(e) {
  34566. setH(e);
  34567. dom.bind(window, 'mousemove', setH);
  34568. dom.bind(window, 'touchmove', setH);
  34569. dom.bind(window, 'mouseup', fieldUpH);
  34570. dom.bind(window, 'touchend', fieldUpH);
  34571. }
  34572. function fieldUpSV() {
  34573. dom.unbind(window, 'mousemove', setSV);
  34574. dom.unbind(window, 'touchmove', setSV);
  34575. dom.unbind(window, 'mouseup', fieldUpSV);
  34576. dom.unbind(window, 'touchend', fieldUpSV);
  34577. onFinish();
  34578. }
  34579. function fieldUpH() {
  34580. dom.unbind(window, 'mousemove', setH);
  34581. dom.unbind(window, 'touchmove', setH);
  34582. dom.unbind(window, 'mouseup', fieldUpH);
  34583. dom.unbind(window, 'touchend', fieldUpH);
  34584. onFinish();
  34585. }
  34586. function onBlur() {
  34587. var i = interpret(this.value);
  34588. if (i !== false) {
  34589. _this.__color.__state = i;
  34590. _this.setValue(_this.__color.toOriginal());
  34591. } else {
  34592. this.value = _this.__color.toString();
  34593. }
  34594. }
  34595. function onFinish() {
  34596. if (_this.__onFinishChange) {
  34597. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  34598. }
  34599. }
  34600. _this2.__saturation_field.appendChild(valueField);
  34601. _this2.__selector.appendChild(_this2.__field_knob);
  34602. _this2.__selector.appendChild(_this2.__saturation_field);
  34603. _this2.__selector.appendChild(_this2.__hue_field);
  34604. _this2.__hue_field.appendChild(_this2.__hue_knob);
  34605. _this2.domElement.appendChild(_this2.__input);
  34606. _this2.domElement.appendChild(_this2.__selector);
  34607. _this2.updateDisplay();
  34608. function setSV(e) {
  34609. if (e.type.indexOf('touch') === -1) {
  34610. e.preventDefault();
  34611. }
  34612. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  34613. var _ref = e.touches && e.touches[0] || e,
  34614. clientX = _ref.clientX,
  34615. clientY = _ref.clientY;
  34616. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  34617. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34618. if (v > 1) {
  34619. v = 1;
  34620. } else if (v < 0) {
  34621. v = 0;
  34622. }
  34623. if (s > 1) {
  34624. s = 1;
  34625. } else if (s < 0) {
  34626. s = 0;
  34627. }
  34628. _this.__color.v = v;
  34629. _this.__color.s = s;
  34630. _this.setValue(_this.__color.toOriginal());
  34631. return false;
  34632. }
  34633. function setH(e) {
  34634. if (e.type.indexOf('touch') === -1) {
  34635. e.preventDefault();
  34636. }
  34637. var fieldRect = _this.__hue_field.getBoundingClientRect();
  34638. var _ref2 = e.touches && e.touches[0] || e,
  34639. clientY = _ref2.clientY;
  34640. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34641. if (h > 1) {
  34642. h = 1;
  34643. } else if (h < 0) {
  34644. h = 0;
  34645. }
  34646. _this.__color.h = h * 360;
  34647. _this.setValue(_this.__color.toOriginal());
  34648. return false;
  34649. }
  34650. return _this2;
  34651. }
  34652. createClass(ColorController, [{
  34653. key: 'updateDisplay',
  34654. value: function updateDisplay() {
  34655. var i = interpret(this.getValue());
  34656. if (i !== false) {
  34657. var mismatch = false;
  34658. Common.each(Color.COMPONENTS, function (component) {
  34659. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  34660. mismatch = true;
  34661. return {};
  34662. }
  34663. }, this);
  34664. if (mismatch) {
  34665. Common.extend(this.__color.__state, i);
  34666. }
  34667. }
  34668. Common.extend(this.__temp.__state, this.__color.__state);
  34669. this.__temp.a = 1;
  34670. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  34671. var _flip = 255 - flip;
  34672. Common.extend(this.__field_knob.style, {
  34673. marginLeft: 100 * this.__color.s - 7 + 'px',
  34674. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  34675. backgroundColor: this.__temp.toHexString(),
  34676. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  34677. });
  34678. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  34679. this.__temp.s = 1;
  34680. this.__temp.v = 1;
  34681. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  34682. this.__input.value = this.__color.toString();
  34683. Common.extend(this.__input.style, {
  34684. backgroundColor: this.__color.toHexString(),
  34685. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  34686. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  34687. });
  34688. }
  34689. }]);
  34690. return ColorController;
  34691. }(Controller);
  34692. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  34693. function linearGradient(elem, x, a, b) {
  34694. elem.style.background = '';
  34695. Common.each(vendors, function (vendor) {
  34696. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  34697. });
  34698. }
  34699. function hueGradient(elem) {
  34700. elem.style.background = '';
  34701. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  34702. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34703. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34704. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34705. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34706. }
  34707. var css = {
  34708. load: function load(url, indoc) {
  34709. var doc = indoc || document;
  34710. var link = doc.createElement('link');
  34711. link.type = 'text/css';
  34712. link.rel = 'stylesheet';
  34713. link.href = url;
  34714. doc.getElementsByTagName('head')[0].appendChild(link);
  34715. },
  34716. inject: function inject(cssContent, indoc) {
  34717. var doc = indoc || document;
  34718. var injected = document.createElement('style');
  34719. injected.type = 'text/css';
  34720. injected.innerHTML = cssContent;
  34721. var head = doc.getElementsByTagName('head')[0];
  34722. try {
  34723. head.appendChild(injected);
  34724. } catch (e) {}
  34725. }
  34726. };
  34727. 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>";
  34728. var ControllerFactory = function ControllerFactory(object, property) {
  34729. var initialValue = object[property];
  34730. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  34731. return new OptionController(object, property, arguments[2]);
  34732. }
  34733. if (Common.isNumber(initialValue)) {
  34734. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  34735. if (Common.isNumber(arguments[4])) {
  34736. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  34737. }
  34738. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  34739. }
  34740. if (Common.isNumber(arguments[4])) {
  34741. return new NumberControllerBox(object, property, {
  34742. min: arguments[2],
  34743. max: arguments[3],
  34744. step: arguments[4]
  34745. });
  34746. }
  34747. return new NumberControllerBox(object, property, {
  34748. min: arguments[2],
  34749. max: arguments[3]
  34750. });
  34751. }
  34752. if (Common.isString(initialValue)) {
  34753. return new StringController(object, property);
  34754. }
  34755. if (Common.isFunction(initialValue)) {
  34756. return new FunctionController(object, property, '');
  34757. }
  34758. if (Common.isBoolean(initialValue)) {
  34759. return new BooleanController(object, property);
  34760. }
  34761. return null;
  34762. };
  34763. function requestAnimationFrame(callback) {
  34764. setTimeout(callback, 1000 / 60);
  34765. }
  34766. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  34767. var CenteredDiv = function () {
  34768. function CenteredDiv() {
  34769. classCallCheck(this, CenteredDiv);
  34770. this.backgroundElement = document.createElement('div');
  34771. Common.extend(this.backgroundElement.style, {
  34772. backgroundColor: 'rgba(0,0,0,0.8)',
  34773. top: 0,
  34774. left: 0,
  34775. display: 'none',
  34776. zIndex: '1000',
  34777. opacity: 0,
  34778. WebkitTransition: 'opacity 0.2s linear',
  34779. transition: 'opacity 0.2s linear'
  34780. });
  34781. dom.makeFullscreen(this.backgroundElement);
  34782. this.backgroundElement.style.position = 'fixed';
  34783. this.domElement = document.createElement('div');
  34784. Common.extend(this.domElement.style, {
  34785. position: 'fixed',
  34786. display: 'none',
  34787. zIndex: '1001',
  34788. opacity: 0,
  34789. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  34790. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  34791. });
  34792. document.body.appendChild(this.backgroundElement);
  34793. document.body.appendChild(this.domElement);
  34794. var _this = this;
  34795. dom.bind(this.backgroundElement, 'click', function () {
  34796. _this.hide();
  34797. });
  34798. }
  34799. createClass(CenteredDiv, [{
  34800. key: 'show',
  34801. value: function show() {
  34802. var _this = this;
  34803. this.backgroundElement.style.display = 'block';
  34804. this.domElement.style.display = 'block';
  34805. this.domElement.style.opacity = 0;
  34806. this.domElement.style.webkitTransform = 'scale(1.1)';
  34807. this.layout();
  34808. Common.defer(function () {
  34809. _this.backgroundElement.style.opacity = 1;
  34810. _this.domElement.style.opacity = 1;
  34811. _this.domElement.style.webkitTransform = 'scale(1)';
  34812. });
  34813. }
  34814. }, {
  34815. key: 'hide',
  34816. value: function hide() {
  34817. var _this = this;
  34818. var hide = function hide() {
  34819. _this.domElement.style.display = 'none';
  34820. _this.backgroundElement.style.display = 'none';
  34821. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  34822. dom.unbind(_this.domElement, 'transitionend', hide);
  34823. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  34824. };
  34825. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  34826. dom.bind(this.domElement, 'transitionend', hide);
  34827. dom.bind(this.domElement, 'oTransitionEnd', hide);
  34828. this.backgroundElement.style.opacity = 0;
  34829. this.domElement.style.opacity = 0;
  34830. this.domElement.style.webkitTransform = 'scale(1.1)';
  34831. }
  34832. }, {
  34833. key: 'layout',
  34834. value: function layout() {
  34835. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  34836. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  34837. }
  34838. }]);
  34839. return CenteredDiv;
  34840. }();
  34841. 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");
  34842. css.inject(styleSheet);
  34843. var CSS_NAMESPACE = 'dg';
  34844. var HIDE_KEY_CODE = 72;
  34845. var CLOSE_BUTTON_HEIGHT = 20;
  34846. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  34847. var SUPPORTS_LOCAL_STORAGE = function () {
  34848. try {
  34849. return !!window.localStorage;
  34850. } catch (e) {
  34851. return false;
  34852. }
  34853. }();
  34854. var SAVE_DIALOGUE = void 0;
  34855. var autoPlaceVirgin = true;
  34856. var autoPlaceContainer = void 0;
  34857. var hide = false;
  34858. var hideableGuis = [];
  34859. var GUI = function GUI(pars) {
  34860. var _this = this;
  34861. var params = pars || {};
  34862. this.domElement = document.createElement('div');
  34863. this.__ul = document.createElement('ul');
  34864. this.domElement.appendChild(this.__ul);
  34865. dom.addClass(this.domElement, CSS_NAMESPACE);
  34866. this.__folders = {};
  34867. this.__controllers = [];
  34868. this.__rememberedObjects = [];
  34869. this.__rememberedObjectIndecesToControllers = [];
  34870. this.__listening = [];
  34871. params = Common.defaults(params, {
  34872. closeOnTop: false,
  34873. autoPlace: true,
  34874. width: GUI.DEFAULT_WIDTH
  34875. });
  34876. params = Common.defaults(params, {
  34877. resizable: params.autoPlace,
  34878. hideable: params.autoPlace
  34879. });
  34880. if (!Common.isUndefined(params.load)) {
  34881. if (params.preset) {
  34882. params.load.preset = params.preset;
  34883. }
  34884. } else {
  34885. params.load = {
  34886. preset: DEFAULT_DEFAULT_PRESET_NAME
  34887. };
  34888. }
  34889. if (Common.isUndefined(params.parent) && params.hideable) {
  34890. hideableGuis.push(this);
  34891. }
  34892. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  34893. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  34894. params.scrollable = true;
  34895. }
  34896. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  34897. var saveToLocalStorage = void 0;
  34898. var titleRow = void 0;
  34899. Object.defineProperties(this, {
  34900. parent: {
  34901. get: function get$$1() {
  34902. return params.parent;
  34903. }
  34904. },
  34905. scrollable: {
  34906. get: function get$$1() {
  34907. return params.scrollable;
  34908. }
  34909. },
  34910. autoPlace: {
  34911. get: function get$$1() {
  34912. return params.autoPlace;
  34913. }
  34914. },
  34915. closeOnTop: {
  34916. get: function get$$1() {
  34917. return params.closeOnTop;
  34918. }
  34919. },
  34920. preset: {
  34921. get: function get$$1() {
  34922. if (_this.parent) {
  34923. return _this.getRoot().preset;
  34924. }
  34925. return params.load.preset;
  34926. },
  34927. set: function set$$1(v) {
  34928. if (_this.parent) {
  34929. _this.getRoot().preset = v;
  34930. } else {
  34931. params.load.preset = v;
  34932. }
  34933. setPresetSelectIndex(this);
  34934. _this.revert();
  34935. }
  34936. },
  34937. width: {
  34938. get: function get$$1() {
  34939. return params.width;
  34940. },
  34941. set: function set$$1(v) {
  34942. params.width = v;
  34943. setWidth(_this, v);
  34944. }
  34945. },
  34946. name: {
  34947. get: function get$$1() {
  34948. return params.name;
  34949. },
  34950. set: function set$$1(v) {
  34951. params.name = v;
  34952. if (titleRow) {
  34953. titleRow.innerHTML = params.name;
  34954. }
  34955. }
  34956. },
  34957. closed: {
  34958. get: function get$$1() {
  34959. return params.closed;
  34960. },
  34961. set: function set$$1(v) {
  34962. params.closed = v;
  34963. if (params.closed) {
  34964. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  34965. } else {
  34966. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  34967. }
  34968. this.onResize();
  34969. if (_this.__closeButton) {
  34970. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  34971. }
  34972. }
  34973. },
  34974. load: {
  34975. get: function get$$1() {
  34976. return params.load;
  34977. }
  34978. },
  34979. useLocalStorage: {
  34980. get: function get$$1() {
  34981. return useLocalStorage;
  34982. },
  34983. set: function set$$1(bool) {
  34984. if (SUPPORTS_LOCAL_STORAGE) {
  34985. useLocalStorage = bool;
  34986. if (bool) {
  34987. dom.bind(window, 'unload', saveToLocalStorage);
  34988. } else {
  34989. dom.unbind(window, 'unload', saveToLocalStorage);
  34990. }
  34991. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  34992. }
  34993. }
  34994. }
  34995. });
  34996. if (Common.isUndefined(params.parent)) {
  34997. this.closed = params.closed || false;
  34998. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  34999. dom.makeSelectable(this.domElement, false);
  35000. if (SUPPORTS_LOCAL_STORAGE) {
  35001. if (useLocalStorage) {
  35002. _this.useLocalStorage = true;
  35003. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35004. if (savedGui) {
  35005. params.load = JSON.parse(savedGui);
  35006. }
  35007. }
  35008. }
  35009. this.__closeButton = document.createElement('div');
  35010. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35011. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35012. if (params.closeOnTop) {
  35013. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35014. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35015. } else {
  35016. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35017. this.domElement.appendChild(this.__closeButton);
  35018. }
  35019. dom.bind(this.__closeButton, 'click', function () {
  35020. _this.closed = !_this.closed;
  35021. });
  35022. } else {
  35023. if (params.closed === undefined) {
  35024. params.closed = true;
  35025. }
  35026. var titleRowName = document.createTextNode(params.name);
  35027. dom.addClass(titleRowName, 'controller-name');
  35028. titleRow = addRow(_this, titleRowName);
  35029. var onClickTitle = function onClickTitle(e) {
  35030. e.preventDefault();
  35031. _this.closed = !_this.closed;
  35032. return false;
  35033. };
  35034. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35035. dom.addClass(titleRow, 'title');
  35036. dom.bind(titleRow, 'click', onClickTitle);
  35037. if (!params.closed) {
  35038. this.closed = false;
  35039. }
  35040. }
  35041. if (params.autoPlace) {
  35042. if (Common.isUndefined(params.parent)) {
  35043. if (autoPlaceVirgin) {
  35044. autoPlaceContainer = document.createElement('div');
  35045. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35046. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35047. document.body.appendChild(autoPlaceContainer);
  35048. autoPlaceVirgin = false;
  35049. }
  35050. autoPlaceContainer.appendChild(this.domElement);
  35051. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35052. }
  35053. if (!this.parent) {
  35054. setWidth(_this, params.width);
  35055. }
  35056. }
  35057. this.__resizeHandler = function () {
  35058. _this.onResizeDebounced();
  35059. };
  35060. dom.bind(window, 'resize', this.__resizeHandler);
  35061. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35062. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35063. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35064. this.onResize();
  35065. if (params.resizable) {
  35066. addResizeHandle(this);
  35067. }
  35068. saveToLocalStorage = function saveToLocalStorage() {
  35069. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35070. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35071. }
  35072. };
  35073. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35074. function resetWidth() {
  35075. var root = _this.getRoot();
  35076. root.width += 1;
  35077. Common.defer(function () {
  35078. root.width -= 1;
  35079. });
  35080. }
  35081. if (!params.parent) {
  35082. resetWidth();
  35083. }
  35084. };
  35085. GUI.toggleHide = function () {
  35086. hide = !hide;
  35087. Common.each(hideableGuis, function (gui) {
  35088. gui.domElement.style.display = hide ? 'none' : '';
  35089. });
  35090. };
  35091. GUI.CLASS_AUTO_PLACE = 'a';
  35092. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35093. GUI.CLASS_MAIN = 'main';
  35094. GUI.CLASS_CONTROLLER_ROW = 'cr';
  35095. GUI.CLASS_TOO_TALL = 'taller-than-window';
  35096. GUI.CLASS_CLOSED = 'closed';
  35097. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  35098. GUI.CLASS_CLOSE_TOP = 'close-top';
  35099. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  35100. GUI.CLASS_DRAG = 'drag';
  35101. GUI.DEFAULT_WIDTH = 245;
  35102. GUI.TEXT_CLOSED = 'Close Controls';
  35103. GUI.TEXT_OPEN = 'Open Controls';
  35104. GUI._keydownHandler = function (e) {
  35105. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  35106. GUI.toggleHide();
  35107. }
  35108. };
  35109. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  35110. Common.extend(GUI.prototype, {
  35111. add: function add(object, property) {
  35112. return _add(this, object, property, {
  35113. factoryArgs: Array.prototype.slice.call(arguments, 2)
  35114. });
  35115. },
  35116. addColor: function addColor(object, property) {
  35117. return _add(this, object, property, {
  35118. color: true
  35119. });
  35120. },
  35121. remove: function remove(controller) {
  35122. this.__ul.removeChild(controller.__li);
  35123. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  35124. var _this = this;
  35125. Common.defer(function () {
  35126. _this.onResize();
  35127. });
  35128. },
  35129. destroy: function destroy() {
  35130. if (this.parent) {
  35131. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  35132. }
  35133. if (this.autoPlace) {
  35134. autoPlaceContainer.removeChild(this.domElement);
  35135. }
  35136. var _this = this;
  35137. Common.each(this.__folders, function (subfolder) {
  35138. _this.removeFolder(subfolder);
  35139. });
  35140. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  35141. removeListeners(this);
  35142. },
  35143. addFolder: function addFolder(name) {
  35144. if (this.__folders[name] !== undefined) {
  35145. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  35146. }
  35147. var newGuiParams = {
  35148. name: name,
  35149. parent: this
  35150. };
  35151. newGuiParams.autoPlace = this.autoPlace;
  35152. if (this.load && this.load.folders && this.load.folders[name]) {
  35153. newGuiParams.closed = this.load.folders[name].closed;
  35154. newGuiParams.load = this.load.folders[name];
  35155. }
  35156. var gui = new GUI(newGuiParams);
  35157. this.__folders[name] = gui;
  35158. var li = addRow(this, gui.domElement);
  35159. dom.addClass(li, 'folder');
  35160. return gui;
  35161. },
  35162. removeFolder: function removeFolder(folder) {
  35163. this.__ul.removeChild(folder.domElement.parentElement);
  35164. delete this.__folders[folder.name];
  35165. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  35166. delete this.load.folders[folder.name];
  35167. }
  35168. removeListeners(folder);
  35169. var _this = this;
  35170. Common.each(folder.__folders, function (subfolder) {
  35171. folder.removeFolder(subfolder);
  35172. });
  35173. Common.defer(function () {
  35174. _this.onResize();
  35175. });
  35176. },
  35177. open: function open() {
  35178. this.closed = false;
  35179. },
  35180. close: function close() {
  35181. this.closed = true;
  35182. },
  35183. hide: function hide() {
  35184. this.domElement.style.display = 'none';
  35185. },
  35186. show: function show() {
  35187. this.domElement.style.display = '';
  35188. },
  35189. onResize: function onResize() {
  35190. var root = this.getRoot();
  35191. if (root.scrollable) {
  35192. var top = dom.getOffset(root.__ul).top;
  35193. var h = 0;
  35194. Common.each(root.__ul.childNodes, function (node) {
  35195. if (!(root.autoPlace && node === root.__save_row)) {
  35196. h += dom.getHeight(node);
  35197. }
  35198. });
  35199. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  35200. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  35201. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  35202. } else {
  35203. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  35204. root.__ul.style.height = 'auto';
  35205. }
  35206. }
  35207. if (root.__resize_handle) {
  35208. Common.defer(function () {
  35209. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  35210. });
  35211. }
  35212. if (root.__closeButton) {
  35213. root.__closeButton.style.width = root.width + 'px';
  35214. }
  35215. },
  35216. onResizeDebounced: Common.debounce(function () {
  35217. this.onResize();
  35218. }, 50),
  35219. remember: function remember() {
  35220. if (Common.isUndefined(SAVE_DIALOGUE)) {
  35221. SAVE_DIALOGUE = new CenteredDiv();
  35222. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  35223. }
  35224. if (this.parent) {
  35225. throw new Error('You can only call remember on a top level GUI.');
  35226. }
  35227. var _this = this;
  35228. Common.each(Array.prototype.slice.call(arguments), function (object) {
  35229. if (_this.__rememberedObjects.length === 0) {
  35230. addSaveMenu(_this);
  35231. }
  35232. if (_this.__rememberedObjects.indexOf(object) === -1) {
  35233. _this.__rememberedObjects.push(object);
  35234. }
  35235. });
  35236. if (this.autoPlace) {
  35237. setWidth(this, this.width);
  35238. }
  35239. },
  35240. getRoot: function getRoot() {
  35241. var gui = this;
  35242. while (gui.parent) {
  35243. gui = gui.parent;
  35244. }
  35245. return gui;
  35246. },
  35247. getSaveObject: function getSaveObject() {
  35248. var toReturn = this.load;
  35249. toReturn.closed = this.closed;
  35250. if (this.__rememberedObjects.length > 0) {
  35251. toReturn.preset = this.preset;
  35252. if (!toReturn.remembered) {
  35253. toReturn.remembered = {};
  35254. }
  35255. toReturn.remembered[this.preset] = getCurrentPreset(this);
  35256. }
  35257. toReturn.folders = {};
  35258. Common.each(this.__folders, function (element, key) {
  35259. toReturn.folders[key] = element.getSaveObject();
  35260. });
  35261. return toReturn;
  35262. },
  35263. save: function save() {
  35264. if (!this.load.remembered) {
  35265. this.load.remembered = {};
  35266. }
  35267. this.load.remembered[this.preset] = getCurrentPreset(this);
  35268. markPresetModified(this, false);
  35269. this.saveToLocalStorageIfPossible();
  35270. },
  35271. saveAs: function saveAs(presetName) {
  35272. if (!this.load.remembered) {
  35273. this.load.remembered = {};
  35274. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  35275. }
  35276. this.load.remembered[presetName] = getCurrentPreset(this);
  35277. this.preset = presetName;
  35278. addPresetOption(this, presetName, true);
  35279. this.saveToLocalStorageIfPossible();
  35280. },
  35281. revert: function revert(gui) {
  35282. Common.each(this.__controllers, function (controller) {
  35283. if (!this.getRoot().load.remembered) {
  35284. controller.setValue(controller.initialValue);
  35285. } else {
  35286. recallSavedValue(gui || this.getRoot(), controller);
  35287. }
  35288. if (controller.__onFinishChange) {
  35289. controller.__onFinishChange.call(controller, controller.getValue());
  35290. }
  35291. }, this);
  35292. Common.each(this.__folders, function (folder) {
  35293. folder.revert(folder);
  35294. });
  35295. if (!gui) {
  35296. markPresetModified(this.getRoot(), false);
  35297. }
  35298. },
  35299. listen: function listen(controller) {
  35300. var init = this.__listening.length === 0;
  35301. this.__listening.push(controller);
  35302. if (init) {
  35303. updateDisplays(this.__listening);
  35304. }
  35305. },
  35306. updateDisplay: function updateDisplay() {
  35307. Common.each(this.__controllers, function (controller) {
  35308. controller.updateDisplay();
  35309. });
  35310. Common.each(this.__folders, function (folder) {
  35311. folder.updateDisplay();
  35312. });
  35313. }
  35314. });
  35315. function addRow(gui, newDom, liBefore) {
  35316. var li = document.createElement('li');
  35317. if (newDom) {
  35318. li.appendChild(newDom);
  35319. }
  35320. if (liBefore) {
  35321. gui.__ul.insertBefore(li, liBefore);
  35322. } else {
  35323. gui.__ul.appendChild(li);
  35324. }
  35325. gui.onResize();
  35326. return li;
  35327. }
  35328. function removeListeners(gui) {
  35329. dom.unbind(window, 'resize', gui.__resizeHandler);
  35330. if (gui.saveToLocalStorageIfPossible) {
  35331. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  35332. }
  35333. }
  35334. function markPresetModified(gui, modified) {
  35335. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  35336. if (modified) {
  35337. opt.innerHTML = opt.value + '*';
  35338. } else {
  35339. opt.innerHTML = opt.value;
  35340. }
  35341. }
  35342. function augmentController(gui, li, controller) {
  35343. controller.__li = li;
  35344. controller.__gui = gui;
  35345. Common.extend(controller, {
  35346. options: function options(_options) {
  35347. if (arguments.length > 1) {
  35348. var nextSibling = controller.__li.nextElementSibling;
  35349. controller.remove();
  35350. return _add(gui, controller.object, controller.property, {
  35351. before: nextSibling,
  35352. factoryArgs: [Common.toArray(arguments)]
  35353. });
  35354. }
  35355. if (Common.isArray(_options) || Common.isObject(_options)) {
  35356. var _nextSibling = controller.__li.nextElementSibling;
  35357. controller.remove();
  35358. return _add(gui, controller.object, controller.property, {
  35359. before: _nextSibling,
  35360. factoryArgs: [_options]
  35361. });
  35362. }
  35363. },
  35364. name: function name(_name) {
  35365. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  35366. return controller;
  35367. },
  35368. listen: function listen() {
  35369. controller.__gui.listen(controller);
  35370. return controller;
  35371. },
  35372. remove: function remove() {
  35373. controller.__gui.remove(controller);
  35374. return controller;
  35375. }
  35376. });
  35377. if (controller instanceof NumberControllerSlider) {
  35378. var box = new NumberControllerBox(controller.object, controller.property, {
  35379. min: controller.__min,
  35380. max: controller.__max,
  35381. step: controller.__step
  35382. });
  35383. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  35384. var pc = controller[method];
  35385. var pb = box[method];
  35386. controller[method] = box[method] = function () {
  35387. var args = Array.prototype.slice.call(arguments);
  35388. pb.apply(box, args);
  35389. return pc.apply(controller, args);
  35390. };
  35391. });
  35392. dom.addClass(li, 'has-slider');
  35393. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  35394. } else if (controller instanceof NumberControllerBox) {
  35395. var r = function r(returned) {
  35396. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  35397. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  35398. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  35399. controller.remove();
  35400. var newController = _add(gui, controller.object, controller.property, {
  35401. before: controller.__li.nextElementSibling,
  35402. factoryArgs: [controller.__min, controller.__max, controller.__step]
  35403. });
  35404. newController.name(oldName);
  35405. if (wasListening) newController.listen();
  35406. return newController;
  35407. }
  35408. return returned;
  35409. };
  35410. controller.min = Common.compose(r, controller.min);
  35411. controller.max = Common.compose(r, controller.max);
  35412. } else if (controller instanceof BooleanController) {
  35413. dom.bind(li, 'click', function () {
  35414. dom.fakeEvent(controller.__checkbox, 'click');
  35415. });
  35416. dom.bind(controller.__checkbox, 'click', function (e) {
  35417. e.stopPropagation();
  35418. });
  35419. } else if (controller instanceof FunctionController) {
  35420. dom.bind(li, 'click', function () {
  35421. dom.fakeEvent(controller.__button, 'click');
  35422. });
  35423. dom.bind(li, 'mouseover', function () {
  35424. dom.addClass(controller.__button, 'hover');
  35425. });
  35426. dom.bind(li, 'mouseout', function () {
  35427. dom.removeClass(controller.__button, 'hover');
  35428. });
  35429. } else if (controller instanceof ColorController) {
  35430. dom.addClass(li, 'color');
  35431. controller.updateDisplay = Common.compose(function (val) {
  35432. li.style.borderLeftColor = controller.__color.toString();
  35433. return val;
  35434. }, controller.updateDisplay);
  35435. controller.updateDisplay();
  35436. }
  35437. controller.setValue = Common.compose(function (val) {
  35438. if (gui.getRoot().__preset_select && controller.isModified()) {
  35439. markPresetModified(gui.getRoot(), true);
  35440. }
  35441. return val;
  35442. }, controller.setValue);
  35443. }
  35444. function recallSavedValue(gui, controller) {
  35445. var root = gui.getRoot();
  35446. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  35447. if (matchedIndex !== -1) {
  35448. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  35449. if (controllerMap === undefined) {
  35450. controllerMap = {};
  35451. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  35452. }
  35453. controllerMap[controller.property] = controller;
  35454. if (root.load && root.load.remembered) {
  35455. var presetMap = root.load.remembered;
  35456. var preset = void 0;
  35457. if (presetMap[gui.preset]) {
  35458. preset = presetMap[gui.preset];
  35459. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  35460. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  35461. } else {
  35462. return;
  35463. }
  35464. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  35465. var value = preset[matchedIndex][controller.property];
  35466. controller.initialValue = value;
  35467. controller.setValue(value);
  35468. }
  35469. }
  35470. }
  35471. }
  35472. function _add(gui, object, property, params) {
  35473. if (object[property] === undefined) {
  35474. throw new Error('Object "' + object + '" has no property "' + property + '"');
  35475. }
  35476. var controller = void 0;
  35477. if (params.color) {
  35478. controller = new ColorController(object, property);
  35479. } else {
  35480. var factoryArgs = [object, property].concat(params.factoryArgs);
  35481. controller = ControllerFactory.apply(gui, factoryArgs);
  35482. }
  35483. if (params.before instanceof Controller) {
  35484. params.before = params.before.__li;
  35485. }
  35486. recallSavedValue(gui, controller);
  35487. dom.addClass(controller.domElement, 'c');
  35488. var name = document.createElement('span');
  35489. dom.addClass(name, 'property-name');
  35490. name.innerHTML = controller.property;
  35491. var container = document.createElement('div');
  35492. container.appendChild(name);
  35493. container.appendChild(controller.domElement);
  35494. var li = addRow(gui, container, params.before);
  35495. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  35496. if (controller instanceof ColorController) {
  35497. dom.addClass(li, 'color');
  35498. } else {
  35499. dom.addClass(li, _typeof(controller.getValue()));
  35500. }
  35501. augmentController(gui, li, controller);
  35502. gui.__controllers.push(controller);
  35503. return controller;
  35504. }
  35505. function getLocalStorageHash(gui, key) {
  35506. return document.location.href + '.' + key;
  35507. }
  35508. function addPresetOption(gui, name, setSelected) {
  35509. var opt = document.createElement('option');
  35510. opt.innerHTML = name;
  35511. opt.value = name;
  35512. gui.__preset_select.appendChild(opt);
  35513. if (setSelected) {
  35514. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  35515. }
  35516. }
  35517. function showHideExplain(gui, explain) {
  35518. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  35519. }
  35520. function addSaveMenu(gui) {
  35521. var div = gui.__save_row = document.createElement('li');
  35522. dom.addClass(gui.domElement, 'has-save');
  35523. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  35524. dom.addClass(div, 'save-row');
  35525. var gears = document.createElement('span');
  35526. gears.innerHTML = '&nbsp;';
  35527. dom.addClass(gears, 'button gears');
  35528. var button = document.createElement('span');
  35529. button.innerHTML = 'Save';
  35530. dom.addClass(button, 'button');
  35531. dom.addClass(button, 'save');
  35532. var button2 = document.createElement('span');
  35533. button2.innerHTML = 'New';
  35534. dom.addClass(button2, 'button');
  35535. dom.addClass(button2, 'save-as');
  35536. var button3 = document.createElement('span');
  35537. button3.innerHTML = 'Revert';
  35538. dom.addClass(button3, 'button');
  35539. dom.addClass(button3, 'revert');
  35540. var select = gui.__preset_select = document.createElement('select');
  35541. if (gui.load && gui.load.remembered) {
  35542. Common.each(gui.load.remembered, function (value, key) {
  35543. addPresetOption(gui, key, key === gui.preset);
  35544. });
  35545. } else {
  35546. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  35547. }
  35548. dom.bind(select, 'change', function () {
  35549. for (var index = 0; index < gui.__preset_select.length; index++) {
  35550. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  35551. }
  35552. gui.preset = this.value;
  35553. });
  35554. div.appendChild(select);
  35555. div.appendChild(gears);
  35556. div.appendChild(button);
  35557. div.appendChild(button2);
  35558. div.appendChild(button3);
  35559. if (SUPPORTS_LOCAL_STORAGE) {
  35560. var explain = document.getElementById('dg-local-explain');
  35561. var localStorageCheckBox = document.getElementById('dg-local-storage');
  35562. var saveLocally = document.getElementById('dg-save-locally');
  35563. saveLocally.style.display = 'block';
  35564. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  35565. localStorageCheckBox.setAttribute('checked', 'checked');
  35566. }
  35567. showHideExplain(gui, explain);
  35568. dom.bind(localStorageCheckBox, 'change', function () {
  35569. gui.useLocalStorage = !gui.useLocalStorage;
  35570. showHideExplain(gui, explain);
  35571. });
  35572. }
  35573. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  35574. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  35575. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  35576. SAVE_DIALOGUE.hide();
  35577. }
  35578. });
  35579. dom.bind(gears, 'click', function () {
  35580. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  35581. SAVE_DIALOGUE.show();
  35582. newConstructorTextArea.focus();
  35583. newConstructorTextArea.select();
  35584. });
  35585. dom.bind(button, 'click', function () {
  35586. gui.save();
  35587. });
  35588. dom.bind(button2, 'click', function () {
  35589. var presetName = prompt('Enter a new preset name.');
  35590. if (presetName) {
  35591. gui.saveAs(presetName);
  35592. }
  35593. });
  35594. dom.bind(button3, 'click', function () {
  35595. gui.revert();
  35596. });
  35597. }
  35598. function addResizeHandle(gui) {
  35599. var pmouseX = void 0;
  35600. gui.__resize_handle = document.createElement('div');
  35601. Common.extend(gui.__resize_handle.style, {
  35602. width: '6px',
  35603. marginLeft: '-3px',
  35604. height: '200px',
  35605. cursor: 'ew-resize',
  35606. position: 'absolute'
  35607. });
  35608. function drag(e) {
  35609. e.preventDefault();
  35610. gui.width += pmouseX - e.clientX;
  35611. gui.onResize();
  35612. pmouseX = e.clientX;
  35613. return false;
  35614. }
  35615. function dragStop() {
  35616. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  35617. dom.unbind(window, 'mousemove', drag);
  35618. dom.unbind(window, 'mouseup', dragStop);
  35619. }
  35620. function dragStart(e) {
  35621. e.preventDefault();
  35622. pmouseX = e.clientX;
  35623. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  35624. dom.bind(window, 'mousemove', drag);
  35625. dom.bind(window, 'mouseup', dragStop);
  35626. return false;
  35627. }
  35628. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  35629. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  35630. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  35631. }
  35632. function setWidth(gui, w) {
  35633. gui.domElement.style.width = w + 'px';
  35634. if (gui.__save_row && gui.autoPlace) {
  35635. gui.__save_row.style.width = w + 'px';
  35636. }
  35637. if (gui.__closeButton) {
  35638. gui.__closeButton.style.width = w + 'px';
  35639. }
  35640. }
  35641. function getCurrentPreset(gui, useInitialValues) {
  35642. var toReturn = {};
  35643. Common.each(gui.__rememberedObjects, function (val, index) {
  35644. var savedValues = {};
  35645. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  35646. Common.each(controllerMap, function (controller, property) {
  35647. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  35648. });
  35649. toReturn[index] = savedValues;
  35650. });
  35651. return toReturn;
  35652. }
  35653. function setPresetSelectIndex(gui) {
  35654. for (var index = 0; index < gui.__preset_select.length; index++) {
  35655. if (gui.__preset_select[index].value === gui.preset) {
  35656. gui.__preset_select.selectedIndex = index;
  35657. }
  35658. }
  35659. }
  35660. function updateDisplays(controllerArray) {
  35661. if (controllerArray.length !== 0) {
  35662. requestAnimationFrame$1.call(window, function () {
  35663. updateDisplays(controllerArray);
  35664. });
  35665. }
  35666. Common.each(controllerArray, function (c) {
  35667. c.updateDisplay();
  35668. });
  35669. }
  35670. var color = {
  35671. Color: Color,
  35672. math: ColorMath,
  35673. interpret: interpret
  35674. };
  35675. exports.color = color;
  35676. var controllers = {
  35677. Controller: Controller,
  35678. BooleanController: BooleanController,
  35679. OptionController: OptionController,
  35680. StringController: StringController,
  35681. NumberController: NumberController,
  35682. NumberControllerBox: NumberControllerBox,
  35683. NumberControllerSlider: NumberControllerSlider,
  35684. FunctionController: FunctionController,
  35685. ColorController: ColorController
  35686. };
  35687. exports.controllers = controllers;
  35688. var dom$1 = {
  35689. dom: dom
  35690. };
  35691. exports.dom = dom$1;
  35692. var gui = {
  35693. GUI: GUI
  35694. };
  35695. exports.gui = gui;
  35696. var GUI$1 = GUI;
  35697. exports.GUI = GUI$1;
  35698. var index = {
  35699. color: color,
  35700. controllers: controllers,
  35701. dom: dom$1,
  35702. gui: gui,
  35703. GUI: GUI$1
  35704. };
  35705. var _default = index;
  35706. exports.default = _default;
  35707. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  35708. "use strict";
  35709. Object.defineProperty(exports, "__esModule", {
  35710. value: true
  35711. });
  35712. exports.default = void 0;
  35713. /**
  35714. * @author mrdoob / http://mrdoob.com/
  35715. */
  35716. var Stats = function () {
  35717. var mode = 0;
  35718. var container = document.createElement('div');
  35719. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  35720. container.addEventListener('click', function (event) {
  35721. event.preventDefault();
  35722. showPanel(++mode % container.children.length);
  35723. }, false); //
  35724. function addPanel(panel) {
  35725. container.appendChild(panel.dom);
  35726. return panel;
  35727. }
  35728. function showPanel(id) {
  35729. for (var i = 0; i < container.children.length; i++) {
  35730. container.children[i].style.display = i === id ? 'block' : 'none';
  35731. }
  35732. mode = id;
  35733. } //
  35734. var beginTime = (performance || Date).now(),
  35735. prevTime = beginTime,
  35736. frames = 0;
  35737. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  35738. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  35739. if (self.performance && self.performance.memory) {
  35740. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  35741. }
  35742. showPanel(0);
  35743. return {
  35744. REVISION: 16,
  35745. dom: container,
  35746. addPanel: addPanel,
  35747. showPanel: showPanel,
  35748. begin: function () {
  35749. beginTime = (performance || Date).now();
  35750. },
  35751. end: function () {
  35752. frames++;
  35753. var time = (performance || Date).now();
  35754. msPanel.update(time - beginTime, 200);
  35755. if (time >= prevTime + 1000) {
  35756. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  35757. prevTime = time;
  35758. frames = 0;
  35759. if (memPanel) {
  35760. var memory = performance.memory;
  35761. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  35762. }
  35763. }
  35764. return time;
  35765. },
  35766. update: function () {
  35767. beginTime = this.end();
  35768. },
  35769. // Backwards Compatibility
  35770. domElement: container,
  35771. setMode: showPanel
  35772. };
  35773. };
  35774. Stats.Panel = function (name, fg, bg) {
  35775. var min = Infinity,
  35776. max = 0,
  35777. round = Math.round;
  35778. var PR = round(window.devicePixelRatio || 1);
  35779. var WIDTH = 80 * PR,
  35780. HEIGHT = 48 * PR,
  35781. TEXT_X = 3 * PR,
  35782. TEXT_Y = 2 * PR,
  35783. GRAPH_X = 3 * PR,
  35784. GRAPH_Y = 15 * PR,
  35785. GRAPH_WIDTH = 74 * PR,
  35786. GRAPH_HEIGHT = 30 * PR;
  35787. var canvas = document.createElement('canvas');
  35788. canvas.width = WIDTH;
  35789. canvas.height = HEIGHT;
  35790. canvas.style.cssText = 'width:80px;height:48px';
  35791. var context = canvas.getContext('2d');
  35792. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  35793. context.textBaseline = 'top';
  35794. context.fillStyle = bg;
  35795. context.fillRect(0, 0, WIDTH, HEIGHT);
  35796. context.fillStyle = fg;
  35797. context.fillText(name, TEXT_X, TEXT_Y);
  35798. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35799. context.fillStyle = bg;
  35800. context.globalAlpha = 0.9;
  35801. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35802. return {
  35803. dom: canvas,
  35804. update: function (value, maxValue) {
  35805. min = Math.min(min, value);
  35806. max = Math.max(max, value);
  35807. context.fillStyle = bg;
  35808. context.globalAlpha = 1;
  35809. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  35810. context.fillStyle = fg;
  35811. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  35812. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  35813. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  35814. context.fillStyle = bg;
  35815. context.globalAlpha = 0.9;
  35816. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  35817. }
  35818. };
  35819. };
  35820. var _default = Stats;
  35821. exports.default = _default;
  35822. },{}],"index.js":[function(require,module,exports) {
  35823. "use strict";
  35824. var _ThreeTilesRenderer = require("../src/ThreeTilesRenderer.js");
  35825. var _three = require("three");
  35826. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  35827. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  35828. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  35829. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35830. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  35831. 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; }
  35832. let camera, controls, scene, renderer, tiles, cameraHelper;
  35833. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  35834. let box;
  35835. let offsetParent;
  35836. let statsContainer, stats;
  35837. let params = {
  35838. 'errorTarget': 6,
  35839. 'errorThreshold': 60,
  35840. 'maxDepth': 15,
  35841. 'loadSiblings': true,
  35842. 'up': '+Y',
  35843. 'displayBounds': false,
  35844. 'showThirdPerson': true,
  35845. 'reload': reinstantiateTiles
  35846. };
  35847. init();
  35848. animate();
  35849. function reinstantiateTiles() {
  35850. const url = window.location.hash.replace(/^#/, '') || './SampleTileset/tileset.json';
  35851. if (tiles) {
  35852. offsetParent.remove(tiles.group);
  35853. }
  35854. tiles = new _ThreeTilesRenderer.ThreeTilesRenderer(url, camera, renderer);
  35855. offsetParent.add(tiles.group);
  35856. }
  35857. function init() {
  35858. // Third person camera view
  35859. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  35860. thirdPersonCamera.position.set(50, 40, 40);
  35861. thirdPersonCamera.lookAt(0, 0, 0);
  35862. thirdPersonRenderer = new _three.WebGLRenderer({
  35863. antialias: true
  35864. });
  35865. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  35866. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  35867. thirdPersonRenderer.setClearColor(0xdddddd);
  35868. document.body.appendChild(thirdPersonRenderer.domElement);
  35869. thirdPersonRenderer.domElement.style.position = 'fixed';
  35870. thirdPersonRenderer.domElement.style.left = '5px';
  35871. thirdPersonRenderer.domElement.style.bottom = '5px';
  35872. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  35873. thirdPersonControls.screenSpacePanning = false;
  35874. thirdPersonControls.minDistance = 1;
  35875. thirdPersonControls.maxDistance = 2000; // primary camera view
  35876. scene = new _three.Scene();
  35877. renderer = new _three.WebGLRenderer({
  35878. antialias: true
  35879. });
  35880. renderer.setPixelRatio(window.devicePixelRatio);
  35881. renderer.setSize(window.innerWidth, window.innerHeight);
  35882. renderer.setClearColor(0xcccccc);
  35883. renderer.gammaInput = true;
  35884. renderer.gameOutput = true;
  35885. document.body.appendChild(renderer.domElement);
  35886. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  35887. camera.position.set(100, 100, 100);
  35888. cameraHelper = new _three.CameraHelper(camera);
  35889. scene.add(cameraHelper); // controls
  35890. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  35891. controls.screenSpacePanning = false;
  35892. controls.minDistance = 1;
  35893. controls.maxDistance = 2000; // lights
  35894. var dirLight = new _three.DirectionalLight(0xffffff);
  35895. dirLight.position.set(1, 1, 1);
  35896. scene.add(dirLight);
  35897. var ambLight = new _three.AmbientLight(0x222222);
  35898. scene.add(ambLight);
  35899. box = new _three.Box3();
  35900. offsetParent = new _three.Group();
  35901. scene.add(offsetParent);
  35902. reinstantiateTiles();
  35903. onWindowResize();
  35904. window.addEventListener('resize', onWindowResize, false); // GUI
  35905. const gui = new dat.GUI();
  35906. const tiles = gui.addFolder('Tiles Options');
  35907. tiles.add(params, 'loadSiblings');
  35908. tiles.add(params, 'errorTarget').min(0).max(50);
  35909. tiles.add(params, 'errorThreshold').min(0).max(1000);
  35910. tiles.add(params, 'maxDepth').min(1).max(100);
  35911. tiles.add(params, 'up', ['+Y', '-Z']);
  35912. tiles.open();
  35913. gui.add(params, 'displayBounds');
  35914. gui.add(params, 'showThirdPerson');
  35915. gui.add(params, 'reload');
  35916. gui.open(); // TilesRenderer stats display
  35917. let textShadow = [];
  35918. for (let x = -1; x <= 1; x++) {
  35919. for (let y = -1; y <= 1; y++) {
  35920. let valX = x;
  35921. let valY = y;
  35922. if (valX !== 0 && valY !== 0) {
  35923. valX *= Math.cos(Math.PI / 4);
  35924. valY *= Math.sin(Math.PI / 4);
  35925. }
  35926. valX *= 1.5;
  35927. valY *= 1.5;
  35928. textShadow.push(`white ${valX}px ${valY}px 0`);
  35929. }
  35930. }
  35931. statsContainer = document.createElement('div');
  35932. statsContainer.style.position = 'absolute';
  35933. statsContainer.style.top = 0;
  35934. statsContainer.style.left = 0;
  35935. statsContainer.style.width = '100%';
  35936. statsContainer.style.textAlign = 'center';
  35937. statsContainer.style.textShadow = textShadow.join(',');
  35938. statsContainer.style.padding = '10px';
  35939. document.body.appendChild(statsContainer); // Stats
  35940. stats = new _statsModule.default();
  35941. stats.showPanel(0);
  35942. document.body.appendChild(stats.dom);
  35943. }
  35944. function onWindowResize() {
  35945. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  35946. thirdPersonCamera.updateProjectionMatrix();
  35947. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  35948. camera.aspect = window.innerWidth / window.innerHeight;
  35949. camera.updateProjectionMatrix();
  35950. renderer.setSize(window.innerWidth, window.innerHeight);
  35951. }
  35952. function animate() {
  35953. // update options
  35954. tiles.errorTarget = params.errorTarget;
  35955. tiles.errorThreshold = params.errorThreshold;
  35956. tiles.loadSiblings = params.loadSiblings;
  35957. tiles.maxDepth = params.maxDepth;
  35958. tiles.displayBounds = params.displayBounds; // update tiles
  35959. tiles.update();
  35960. window.tiles = tiles;
  35961. offsetParent.rotation.set(0, 0, 0);
  35962. if (params.up === '-Z') {
  35963. offsetParent.rotation.x = Math.PI / 2;
  35964. } // update tiles center
  35965. if (tiles.getBounds(box)) {
  35966. box.getCenter(tiles.group.position);
  35967. tiles.group.position.multiplyScalar(-1);
  35968. }
  35969. stats.begin();
  35970. render();
  35971. stats.end();
  35972. requestAnimationFrame(animate);
  35973. }
  35974. function render() {
  35975. // render primary view
  35976. cameraHelper.visible = false;
  35977. renderer.render(scene, camera); // render third person view
  35978. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  35979. if (params.showThirdPerson) {
  35980. cameraHelper.visible = true;
  35981. thirdPersonRenderer.render(scene, thirdPersonCamera);
  35982. }
  35983. statsContainer.innerText = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}`;
  35984. }
  35985. },{"../src/ThreeTilesRenderer.js":"../src/ThreeTilesRenderer.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  35986. var global = arguments[3];
  35987. var OVERLAY_ID = '__parcel__error__overlay__';
  35988. var OldModule = module.bundle.Module;
  35989. function Module(moduleName) {
  35990. OldModule.call(this, moduleName);
  35991. this.hot = {
  35992. data: module.bundle.hotData,
  35993. _acceptCallbacks: [],
  35994. _disposeCallbacks: [],
  35995. accept: function (fn) {
  35996. this._acceptCallbacks.push(fn || function () {});
  35997. },
  35998. dispose: function (fn) {
  35999. this._disposeCallbacks.push(fn);
  36000. }
  36001. };
  36002. module.bundle.hotData = null;
  36003. }
  36004. module.bundle.Module = Module;
  36005. var checkedAssets, assetsToAccept;
  36006. var parent = module.bundle.parent;
  36007. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  36008. var hostname = "" || location.hostname;
  36009. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  36010. var ws = new WebSocket(protocol + '://' + hostname + ':' + "58020" + '/');
  36011. ws.onmessage = function (event) {
  36012. checkedAssets = {};
  36013. assetsToAccept = [];
  36014. var data = JSON.parse(event.data);
  36015. if (data.type === 'update') {
  36016. var handled = false;
  36017. data.assets.forEach(function (asset) {
  36018. if (!asset.isNew) {
  36019. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  36020. if (didAccept) {
  36021. handled = true;
  36022. }
  36023. }
  36024. }); // Enable HMR for CSS by default.
  36025. handled = handled || data.assets.every(function (asset) {
  36026. return asset.type === 'css' && asset.generated.js;
  36027. });
  36028. if (handled) {
  36029. console.clear();
  36030. data.assets.forEach(function (asset) {
  36031. hmrApply(global.parcelRequire, asset);
  36032. });
  36033. assetsToAccept.forEach(function (v) {
  36034. hmrAcceptRun(v[0], v[1]);
  36035. });
  36036. } else if (location.reload) {
  36037. // `location` global exists in a web worker context but lacks `.reload()` function.
  36038. location.reload();
  36039. }
  36040. }
  36041. if (data.type === 'reload') {
  36042. ws.close();
  36043. ws.onclose = function () {
  36044. location.reload();
  36045. };
  36046. }
  36047. if (data.type === 'error-resolved') {
  36048. console.log('[parcel] ✨ Error resolved');
  36049. removeErrorOverlay();
  36050. }
  36051. if (data.type === 'error') {
  36052. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  36053. removeErrorOverlay();
  36054. var overlay = createErrorOverlay(data);
  36055. document.body.appendChild(overlay);
  36056. }
  36057. };
  36058. }
  36059. function removeErrorOverlay() {
  36060. var overlay = document.getElementById(OVERLAY_ID);
  36061. if (overlay) {
  36062. overlay.remove();
  36063. }
  36064. }
  36065. function createErrorOverlay(data) {
  36066. var overlay = document.createElement('div');
  36067. overlay.id = OVERLAY_ID; // html encode message and stack trace
  36068. var message = document.createElement('div');
  36069. var stackTrace = document.createElement('pre');
  36070. message.innerText = data.error.message;
  36071. stackTrace.innerText = data.error.stack;
  36072. 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>';
  36073. return overlay;
  36074. }
  36075. function getParents(bundle, id) {
  36076. var modules = bundle.modules;
  36077. if (!modules) {
  36078. return [];
  36079. }
  36080. var parents = [];
  36081. var k, d, dep;
  36082. for (k in modules) {
  36083. for (d in modules[k][1]) {
  36084. dep = modules[k][1][d];
  36085. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  36086. parents.push(k);
  36087. }
  36088. }
  36089. }
  36090. if (bundle.parent) {
  36091. parents = parents.concat(getParents(bundle.parent, id));
  36092. }
  36093. return parents;
  36094. }
  36095. function hmrApply(bundle, asset) {
  36096. var modules = bundle.modules;
  36097. if (!modules) {
  36098. return;
  36099. }
  36100. if (modules[asset.id] || !bundle.parent) {
  36101. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  36102. asset.isNew = !modules[asset.id];
  36103. modules[asset.id] = [fn, asset.deps];
  36104. } else if (bundle.parent) {
  36105. hmrApply(bundle.parent, asset);
  36106. }
  36107. }
  36108. function hmrAcceptCheck(bundle, id) {
  36109. var modules = bundle.modules;
  36110. if (!modules) {
  36111. return;
  36112. }
  36113. if (!modules[id] && bundle.parent) {
  36114. return hmrAcceptCheck(bundle.parent, id);
  36115. }
  36116. if (checkedAssets[id]) {
  36117. return;
  36118. }
  36119. checkedAssets[id] = true;
  36120. var cached = bundle.cache[id];
  36121. assetsToAccept.push([bundle, id]);
  36122. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36123. return true;
  36124. }
  36125. return getParents(global.parcelRequire, id).some(function (id) {
  36126. return hmrAcceptCheck(global.parcelRequire, id);
  36127. });
  36128. }
  36129. function hmrAcceptRun(bundle, id) {
  36130. var cached = bundle.cache[id];
  36131. bundle.hotData = {};
  36132. if (cached) {
  36133. cached.hot.data = bundle.hotData;
  36134. }
  36135. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  36136. cached.hot._disposeCallbacks.forEach(function (cb) {
  36137. cb(bundle.hotData);
  36138. });
  36139. }
  36140. delete bundle.cache[id];
  36141. bundle(id);
  36142. cached = bundle.cache[id];
  36143. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36144. cached.hot._acceptCallbacks.forEach(function (cb) {
  36145. cb();
  36146. });
  36147. return true;
  36148. }
  36149. }
  36150. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  36151. //# sourceMappingURL=example.e31bb0bc.js.map